speedup __instancecheck__ check on BaseModel when they fail (#4081)

* speedup __instancecheck__ check on BaseModel when they fail

* add change description

* linting
This commit is contained in:
Samuel Colvin
2022-05-17 14:13:36 +01:00
committed by GitHub
parent a7e896c5a3
commit abea8232ee
3 changed files with 23 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
Speedup `__isinstancecheck__` on pydantic models when the type is not a model, may also avoid memory "leaks".
+8
View File
@@ -295,6 +295,14 @@ class ModelMetaclass(ABCMeta):
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__
+14
View File
@@ -1932,3 +1932,17 @@ def test_int_subclass():
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)