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

Support validate call decorator for methods in classes with __slots__ #7883

Merged
merged 1 commit into from Oct 20, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
8 changes: 8 additions & 0 deletions pydantic/_internal/_validate_call.py
Expand Up @@ -108,6 +108,11 @@ def __get__(self, obj: Any, objtype: type[Any] | None = None) -> ValidateCallWra

bound_function = self.raw_function.__get__(obj, objtype)
result = self.__class__(bound_function, self._config, self._validate_return)

# skip binding to instance when obj or objtype has __slots__ attribute
if hasattr(obj, '__slots__') or hasattr(objtype, '__slots__'):
return result

if self._name is not None:
if obj is not None:
object.__setattr__(obj, self._name, result)
Expand All @@ -120,3 +125,6 @@ def __set_name__(self, owner: Any, name: str) -> None:

def __repr__(self) -> str:
return f'ValidateCallWrapper({self.raw_function})'

def __eq__(self, other):
return self.raw_function == other.raw_function
29 changes: 29 additions & 0 deletions tests/test_validate_call.py
Expand Up @@ -725,3 +725,32 @@ async def foo(a: Any) -> int:
'input': 'x',
}
]


def test_validate_call_with_slots() -> None:
class ClassWithSlots:
__slots__ = {}

@validate_call(validate_return=True)
def some_instance_method(self, x: str) -> str:
return x

@classmethod
@validate_call(validate_return=True)
def some_class_method(cls, x: str) -> str:
return x

@staticmethod
@validate_call(validate_return=True)
def some_static_method(x: str) -> str:
return x

c = ClassWithSlots()
assert c.some_instance_method(x='potato') == 'potato'
assert c.some_class_method(x='pepper') == 'pepper'
assert c.some_static_method(x='onion') == 'onion'

# verify that equality still holds for instance methods
assert c.some_instance_method == c.some_instance_method
assert c.some_class_method == c.some_class_method
assert c.some_static_method == c.some_static_method