Skip to content

Commit abea823

Browse files
authored
speedup __instancecheck__ check on BaseModel when they fail (#4081)
* speedup __instancecheck__ check on BaseModel when they fail * add change description * linting
1 parent a7e896c commit abea823

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

changes/4081-samuelcolvin.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Speedup `__isinstancecheck__` on pydantic models when the type is not a model, may also avoid memory "leaks".

pydantic/main.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,14 @@ def is_untouched(v: Any) -> bool:
295295

296296
return cls
297297

298+
def __instancecheck__(self, instance: Any) -> bool:
299+
"""
300+
Avoid calling ABC _abc_subclasscheck unless we're pretty sure.
301+
302+
See #3829 and python/cpython#92810
303+
"""
304+
return hasattr(instance, '__fields__') and super().__instancecheck__(instance)
305+
298306

299307
object_setattr = object.__setattr__
300308

tests/test_edge_cases.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1932,3 +1932,17 @@ def __new__(cls, data: int):
19321932

19331933
m = MyModel(my_int=IntSubclass(123))
19341934
assert m.my_int.__class__ == IntSubclass
1935+
1936+
1937+
def test_model_issubclass():
1938+
assert not issubclass(int, BaseModel)
1939+
1940+
class MyModel(BaseModel):
1941+
x: int
1942+
1943+
assert issubclass(MyModel, BaseModel)
1944+
1945+
class Custom:
1946+
__fields__ = True
1947+
1948+
assert not issubclass(Custom, BaseModel)

0 commit comments

Comments
 (0)