8000 Code review fixes · pydantic/pydantic@d9d4272 · GitHub
[go: up one dir, main page]

Skip to content

Commit d9d4272

Browse files
Code review fixes
1 parent 3a285fd commit d9d4272

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

pydantic/main.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ class BaseModel(metaclass=_model_construction.ModelMetaclass):
170170
"""
171171

172172
__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__`"""
174174

175175
__pydantic_computed_fields__: ClassVar[Dict[str, ComputedFieldInfo]] # noqa: UP006
176176
"""A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects."""
@@ -893,17 +893,20 @@ def __getattr__(self, item: str) -> Any:
893893
raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
894894

895895
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)
898898
return
899899

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
903903

904904
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.
907910
"""
908911
cls = self.__class__
909912
if name in cls.__class_vars__:

0 commit comments

Comments
 (0)
0