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
default_factory
being run prior to object init
#1491
Comments
I'm not sure I would call this a bug. Since it'll be consistent, you should be able to just start with I can't think of another safe workaround. |
- by calling it only once if possible (fix pydantic#1491) - by not setting the default value in the schema (fix pydantic#1520)
@samuelcolvin Unfortunately our team also encountered this bug. Starting with |
@bharel if you're writing to a file or messing with the environment in a factory function you're doing something very wrong. |
What is the purpose of running default factory function on class creation? |
@samuelcolvin I'm sorry but I don't think this is wrong:
All I'm using is pydantic, and it'll fail on import time if the env doesn't exist. |
See #1504, it's called to get the field type - I think this is fixed on #1504 by making type annotations required for fields with a factory. But I haven't looked through #1504 completely I think it might require some more work.
This is an interesting use case, I'll think more about how best to work around the problem or solve it completely. |
@samuelcolvin |
see #1504, is there anything you think is wrong with that? It seems a good fix to me. |
@samuelcolvin I'm asking regarding the example @bharel posted. Would that PR fix that also? (i.e will not call the factory on class definition?) |
Why don't you try the PR and find out? Then you could report back here how it works or comment on the PR with suggestions. |
@samuelcolvin sorry, I think I read in the PR that it makes it run only once (I assumed it meant instead of twice, but actually it meant only on initialization, not class deifintion). |
Bug
default_factory
gets run twice before any object instantiation. This is obvious for callables with side-effects:The text was updated successfully, but these errors were encountered: