@@ -170,7 +170,7 @@ class BaseModel(metaclass=_model_construction.ModelMetaclass):
170
170
"""
171
171
172
172
__pydantic_setattr_handlers__ : ClassVar [Dict [str , Callable [[BaseModel , Any ], None ]]] # noqa: UP006
173
- """__setattr__ handlers. Used to speed up __setattr__. """
173
+ """__setattr__ handlers. Memoizing the setattr handlers leads to a dramatic performance improvement in ` __setattr__` """
174
174
175
175
__pydantic_computed_fields__ : ClassVar [Dict [str , ComputedFieldInfo ]] # noqa: UP006
176
176
"""A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects."""
@@ -893,17 +893,20 @@ def __getattr__(self, item: str) -> Any:
893
893
raise AttributeError (f'{ type (self ).__name__ !r} object has no attribute { item !r} ' )
894
894
895
895
def __setattr__ (self , name : str , value : Any ) -> None :
896
- if (fast_memo_handler := self .__pydantic_setattr_handlers__ .get (name )) is not None :
897
- fast_memo_handler (self , value )
896
+ if (setattr_handler := self .__pydantic_setattr_handlers__ .get (name )) is not None :
897
+ setattr_handler (self , value )
898
898
return
899
899
900
- if (fast_memo_handler := self ._setattr_handler (name , value )) is not None :
901
- fast_memo_handler (self , value ) # call here to not memo on possibly unknown fields
902
- self .__pydantic_setattr_handlers__ [name ] = fast_memo_handler
900
+ if (setattr_handler := self ._setattr_handler (name , value )) is not None :
901
+ setattr_handler (self , value ) # call here to not memo on possibly unknown fields
902
+ self .__pydantic_setattr_handlers__ [name ] = setattr_handler # memoize the handler for faster access
903
903
904
904
def _setattr_handler (self , name : str , value : Any ) -> Callable [[BaseModel , Any ], None ] | None :
905
- """Returns a handler for setting an attribute on the model instance. This handler can be memoized to
906
- the class. Gives None when memoization is not safe, then the attribute is set directly.
905
+ """Get a handler for setting an attribute on the model instance.
906
+
907
+ Returns:
908
+ A handler for setting an attribute on the model instance. Used for memoization of the handler.
909
+ Gives None when memoization is not safe, then the attribute is set directly.
907
910
"""
908
911
cls = self .__class__
909
912
if name in cls .__class_vars__ :
0 commit comments