Skip to content

Commit

Permalink
speedup __instancecheck__ check on BaseModel when they fail (#4081)
Browse files Browse the repository at this point in the history
* speedup __instancecheck__ check on BaseModel when they fail

* add change description

* linting
  • Loading branch information
samuelcolvin authored May 17, 2022
1 parent a7e896c commit abea823
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
1 change: 1 addition & 0 deletions changes/4081-samuelcolvin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Speedup `__isinstancecheck__` on pydantic models when the type is not a model, may also avoid memory "leaks".
8 changes: 8 additions & 0 deletions pydantic/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,14 @@ def is_untouched(v: Any) -> bool:

return cls

def __instancecheck__(self, instance: Any) -> bool:
"""
Avoid calling ABC _abc_subclasscheck unless we're pretty sure.
See #3829 and python/cpython#92810
"""
return hasattr(instance, '__fields__') and super().__instancecheck__(instance)


object_setattr = object.__setattr__

Expand Down
14 changes: 14 additions & 0 deletions tests/test_edge_cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -1932,3 +1932,17 @@ def __new__(cls, data: int):

m = MyModel(my_int=IntSubclass(123))
assert m.my_int.__class__ == IntSubclass


def test_model_issubclass():
assert not issubclass(int, BaseModel)

class MyModel(BaseModel):
x: int

assert issubclass(MyModel, BaseModel)

class Custom:
__fields__ = True

assert not issubclass(Custom, BaseModel)

0 comments on commit abea823

Please sign in to comment.