-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Delay instance faux-immutablity until after model_post_init
completes.
#11495
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
Comments
I'm kind of surprised no one has reported an issue on the CPython issue tracker about this for stdlib dataclasses (which suffer from the same issue). I can see how this can be useful, although I think it makes sense to behave as it does today by definition: the post init logic happens after initialization, meaning the model should be frozen. It might be best to require the user to explicitly "unfreeze" the model, e.g. with a context manager: class Model(BaseModel, frozen=True):
def model_post_init(self, context):
with self.with_config(frozen=False):
# Apply mutations This API has the benefit of being extendable to other configuration values, e.g. Doing this for Wdyt @davidhewitt? |
Hmm, interesting.
I agree with this. I think that as well as The API to temporarily unfreeze - or modify other config - yes, that sound reasonable. I think in general in |
Discussed with the team, we prefer not going this way for now. Trying to bypass I'm leaving the feature request open as it isn't directly related, and we might allow such mutations in |
Initial Checks
Description
Goal:
post_model_init
Case
As a data scientist, I often create classes that have very complex, multi-field validation and inference and imputation using the entire object.
I currently use
model_post_init
to "clean up" and impute missing fields.Alternatives considered:
Init and
model_post_init
using an unfrozen class, that feeds the results into the frozen class.https://gist.github.com/gregglind/0ee7074a1642dfc485564f5bdf245d59
Code habit changes to avoid this creating such complex objects.
Blockers
model_post_init
Prior art
Others have raised related issues about 'frozen':
Affected Components
.model_dump()
and.model_dump_json()
model_construct()
, pickling, private attributes, ORM modeThe text was updated successfully, but these errors were encountered: