cloudevents / sdk-python

Python SDK for CloudEvents
https://pypi.org/p/cloudevents/
Apache License 2.0
279 stars 55 forks source link

Support for pydantic v2 #215

Closed gaborbernat closed 1 year ago

gaborbernat commented 1 year ago

https://github.com/cloudevents/sdk-python/blob/main/cloudevents/pydantic/event.py#L87

https://docs.pydantic.dev/latest/migration/

xSAVIKx commented 1 year ago

Hey @gaborbernat, thx for pointing this out. Is there any info on how one may support both v1 and v2 of Pydantic? While switching to v2 completely will break things for the library users.

gaborbernat commented 1 year ago

I don't think there's support for supporting both... You could do some gimnastics to switch implementation based on detected version 🤷‍♂️ but will get messy.

febus982 commented 1 year ago

The main problem could be testing but the pydantic V2 implementation includes the old V1, namespaced in the pydantic.v1 module.

It looks horrible but importing the BaseModel like this might work:

pydantic_version = pydantic.version.VERSION.split('.')[0]

from pydantic import BaseModel as BaseModelV2
if pydantic_version == '1'
    from pydantic BaseModel as BaseModelV1
else
    from pydantic.v1 BaseModel as BaseModelV1

class _CloudEventBaseV1(BaseModelV1):
   # Existing implementation

class _CloudEventBaseV2(BaseModelV2):
   # Pydantic V2 configured model

if pydantic_version == '1':
    CloudEvent = _CloudEventBaseV1
else:
    CloudEvent = _CloudEventBaseV2

It looks horrible, I know.