pydantic / pydantic-extra-types

Extra Pydantic types.
MIT License
181 stars 48 forks source link

Support ZoneInfo in BaseModel #103

Open laurens-teirlynck opened 11 months ago

laurens-teirlynck commented 11 months ago

Initial Checks

Description

I feel like it should be possible to create a BaseModel with a ZoneInfo (or pydantic's TzInfo) like in the snippet below. If you try to run this, a PydanticSchemaGenerationError is raised. https://github.com/pydantic/pydantic/issues/4987 reported the same thing, but was closed by the author after working around the issue.

from pydantic import BaseModel

from zoneinfo import ZoneInfo
# from pydantic_core import TzInfo

class Model(BaseModel):
    timezone: ZoneInfo
    # timezone: TzInfo

# PydanticSchemaGenerationError(
# pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class 'pydantic_core._pydantic_core.TzInfo'>. Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it.
# If you got this error by calling handler(<some type>) within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema(<some type>)` since we do not call `__get_pydantic_core_schema__` on `<some type>` otherwise to avoid infinite recursion.
# For further information visit https://errors.pydantic.dev/2.4/u/schema-for-unknown-type

Affected Components

sydney-runkle commented 11 months ago

Hi @laurens-teirlynck,

Thanks for submitting this feature request. Seems reasonable - I'd be more than happy to review a PR adding this feature 😄. Is this something you'd be interested in opening a PR for?

laurens-teirlynck commented 11 months ago

Sure, I don't mind giving this a go

sydney-runkle commented 11 months ago

@laurens-teirlynck,

Maybe something that would make more sense in pydantic-extra-types

laurens-teirlynck commented 11 months ago

Is it correct that supporting this in pydantic-extra-types would require a new Python class? ZoneInfo and TzInfo already exist, and it would be nice to be able to use one of those two.

sydney-runkle commented 11 months ago

Hi @laurens-teirlynck,

Yep, you'd want to create a type that subclasses from ZoneInfo and implements like __get_pydantic_core_schema__ and __get_pydantic_json_schema__.

You can also take this approach in order to support ZoneInfo in your own project in the meantime! I'm going to move this issue over to pydantic-extra-types 😄