It would be nice if you could access the "source" object in a root_validator (coming soon; see #817) when the model was being initialized via a call to from_orm. This would enable almost any form of custom loading from an orm object possible by use of a root validator.
I think this can be accomplished now by making changes only to the GetterDict class:
""" Hack to make object's smell just enough like dicts for validate_model. """__slots__= ('_obj', '_overrides')
def__init__(self, obj: Any):
self._obj=objself._overrides: Optional[Dict] =None# NEWLY ADDED# NEWLY ADDEDdefsource_object(self):
returnself._obj# NEWLY ADDEDdef__setitem__(self, key, value):
defget(self, item: Any, default: Any) ->Any:
# SLIGHTLY MODIFIEDifself._overridesisNone:
# This check could be removed if we make the _overrides non-optional# but I think that would come with a *slightly* larger performance penalty if not usedreturngetattr(self._obj, item, default)
returnself._overrides.get(item) orgetattr(self._obj, item, default)
""" We don't want to get any other attributes of obj if the model didn't explicitly ask for them """returnset()
The only performance sacrifice if not making use of the feature is the check if self._overrides is None (it seems to me like the impact would be miniscule in practice).
This would allow things like:
frompydanticimportBaseModel, Schema, root_validatorfrompydantic.utilsimportGetterDictclassMyModelORM:
x: inty: str=Schema(None)
# This is how you know it got called via from_ormvalues['y'] =values.source_object().orm_propertyreturnvaluesclassConfig:
# MyModel x=1 y='hello'
@samuelcolvin I can't think of any breaking changes this would introduce, can you? Would this be interesting to you?
The text was updated successfully, but these errors were encountered: