Skip to content

Commit

Permalink
Support validate call decorator for methods in classes with `__slots_…
Browse files Browse the repository at this point in the history
…_` (#7883)
  • Loading branch information
sydney-runkle committed Oct 20, 2023
1 parent 8b88a9e commit 4dd40ae
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
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

0 comments on commit 4dd40ae

Please sign in to comment.