Skip to content
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

Fix PEP487 __set_name__ protocol in BaseModel #4407

Merged
merged 7 commits into from Aug 21, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/4407-tlambert03.md
@@ -0,0 +1 @@
Fix PEP487 protocol in `BaseModel`: call `__set_name__` on namespace values that implement the method.
6 changes: 6 additions & 0 deletions pydantic/main.py
Expand Up @@ -286,6 +286,12 @@ def is_untouched(v: Any) -> bool:
if resolve_forward_refs:
cls.__try_update_forward_refs__()

# preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487
for name, obj in namespace.items():
set_name = getattr(obj, '__set_name__', None)
if callable(set_name):
set_name(cls, name)

return cls

def __instancecheck__(self, instance: Any) -> bool:
Expand Down
24 changes: 24 additions & 0 deletions tests/test_create_model.py
Expand Up @@ -222,3 +222,27 @@ class TestGenericModel(GenericModel):
result = AAModel[int](aa=1)
assert result.aa == 1
assert result.__config__.orm_mode is True


def test_set_name():

from unittest.mock import Mock
tlambert03 marked this conversation as resolved.
Show resolved Hide resolved

from pydantic.fields import ModelPrivateAttr
tlambert03 marked this conversation as resolved.
Show resolved Hide resolved

mock = Mock()

class class_deco(ModelPrivateAttr):
def __init__(self, fn):
super().__init__()
self.fn = fn

def __set_name__(self, owner, name):
mock(owner, name)

class A(BaseModel):
@class_deco
def _some_func(self):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you also call _some_func to check it's a proper bound method.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

working on this one still, don't merge yet :)

return self

mock.assert_called_once_with(A, '_some_func')