pydantic / pydantic-extra-types

Extra Pydantic types.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support ZoneInfo in BaseModel

laurens-teirlynck opened this issue · comments

Initial Checks

  • I have searched Google & GitHub for similar requests and couldn't find anything
  • I have read and followed the docs and still think this feature is missing

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. pydantic/pydantic#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

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?

Sure, I don't mind giving this a go

@laurens-teirlynck,

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

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.

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 😄