New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
freeze_time
doesn't work with pydantic
#480
Comments
I found that pydantic==1.9.2 still works, but it would be nice to see this resovled. |
I re-tested with @Tehtehteh example and it worked with pydantic v2. |
If you're stuck with pydantic 1.10 and need a workaround for this, you can replace your
"""
Hack to ensure that we never import pydantic from inside a `freeze_time`.
The freezegun library monkey patches or replaces certain types such as `date`
or `datetime` in order to make them return whatever frozen time we specified.
That doesn't play nicely with Pydantic, which uses such types as metaclasses.
When you use a fake class as a metaclass, it may start breaking at import time,
with an error like this:
TypeError: metaclass conflict: the metaclass of a derived class must be a
(non-strict) subclass of the metaclasses of all its bases
The incompatibility with Pydantic is documented in an issue:
https://github.com/spulec/freezegun/issues/480
The fix here is to make sure that whenever you import freeze_time,
pydantic.types (the module that fails) is already imported and cached
in `sys.modules`, so it's fine if any downstream code attempts to import it.
"""
import pydantic.types
from freezegun import freeze_time
__all__ = [
"freeze_time",
] |
Any update on this? I'm still hitting this bug with pydantic v2. For others facing this issue, there is an alternative lib very similar to freezegun which is working without issues called time-machine. |
@chrisk314 you might be able to work around the issue with an |
@samueldg thanks for the suggestion. I did try out the work around you shared above. unfortunately it didn't work in my case. My issue was actually being caused by an import from the Huggingface For me a better solution was to switch to time-machine library: that library is providing the same functionality; it's working correctly; and I don't need any work arounds introduced into the tests. Would be nice if there was a fix for freezegun as it's a great library. |
Relevant part of the stack trace for the similar problem coming from the Huggingface transformers library in case it's useful for debugging this issue.
|
Overview
It seems that
freezegun.freeze_time
patch is incompatible withpydantic
imports, because of some datetime classes re-definition. Minimal working example:This code throws following error:
Requirements.txt
The text was updated successfully, but these errors were encountered: