Skip to content

Override __subclasscheck__ on ModelMetaclass to avoid memory leak and performance issues #11116

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions pydantic/_internal/_generics.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,9 @@ def get_model_typevars_map(cls: type[BaseModel]) -> dict[TypeVar, Any] | None:
generic_metadata = cls.__pydantic_generic_metadata__
origin = generic_metadata['origin']
args = generic_metadata['args']
if not args:
# No need to go into `iter_contained_typevars`:
return {}
return dict(zip(iter_contained_typevars(origin), args))


Expand Down
9 changes: 8 additions & 1 deletion pydantic/_internal/_model_construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,11 +325,18 @@ def __prepare__(cls, *args: Any, **kwargs: Any) -> dict[str, object]:
return _ModelNamespaceDict()

def __instancecheck__(self, instance: Any) -> bool:
"""Avoid calling ABC _abc_instancecheck unless we're pretty sure.

See #3829 and python/cpython#92810
"""
return hasattr(instance, '__pydantic_decorators__') and super().__instancecheck__(instance)

def __subclasscheck__(self, subclass: type[Any]) -> bool:
"""Avoid calling ABC _abc_subclasscheck unless we're pretty sure.

See #3829 and python/cpython#92810
"""
return hasattr(instance, '__pydantic_validator__') and super().__instancecheck__(instance)
return hasattr(subclass, '__pydantic_decorators__') and super().__subclasscheck__(subclass)

@staticmethod
def _collect_bases_data(bases: tuple[type[Any], ...]) -> tuple[set[str], set[str], dict[str, ModelPrivateAttr]]:
Expand Down
Loading