mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
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:
@@ -0,0 +1 @@
|
||||
Speedup `__isinstancecheck__` on pydantic models when the type is not a model, may also avoid memory "leaks".
|
||||
@@ -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__
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user