Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
23 changes: 16 additions & 7 deletions mypy/stubgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -861,13 +861,8 @@ def visit_class_def(self, o: ClassDef) -> None:
if self.analyzed and (spec := find_dataclass_transform_spec(o)):
self.processing_dataclass = True
self.dataclass_field_specifier = spec.field_specifiers
for base_type_expr in o.base_type_exprs:
if (
isinstance(base_type_expr, (NameExpr, MemberExpr))
and self.get_fullname(base_type_expr) == "pydantic.BaseModel"
):
self.processing_pydantic_model = True
break
if self._inherits_from_pydantic_basemodel(o):
self.processing_pydantic_model = True
super().visit_class_def(o)
self.dedent()
self._vars.pop()
Expand All @@ -887,6 +882,20 @@ def visit_class_def(self, o: ClassDef) -> None:
self.processing_enum = False
self.processing_pydantic_model = False

def _inherits_from_pydantic_basemodel(self, class_def: ClassDef) -> bool:
"""Check if a class directly or indirectly inherits from pydantic.BaseModel"""
for base_type_expr in class_def.base_type_exprs:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: why do we need this branch?

Copy link
Author

@teplandr teplandr Jul 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @sobolevn! Because without it, the check for direct inheritance doesn't work. As I wrote previously, mro contains the following list: [<TypeInfo main.User>, <TypeInfo main.BaseUser>, <TypeInfo builtins.object>] and no pydantic.BaseModel. I would be happy to know the reason, but have no idea.

if (
isinstance(base_type_expr, (NameExpr, MemberExpr))
and self.get_fullname(base_type_expr) == "pydantic.BaseModel"
):
return True
if self.analyzed and class_def.info:
for base_class in class_def.info.mro:
if base_class.fullname == "pydantic.BaseModel":
return True
return False

def get_base_types(self, cdef: ClassDef) -> list[str]:
"""Get list of base classes for a class."""
base_types: list[str] = []
Expand Down
2 changes: 1 addition & 1 deletion test-data/unit/stubgen.test
Original file line number Diff line number Diff line change
Expand Up @@ -4801,7 +4801,7 @@ class User(BaseModel):
age: int
address: Address | None = ...

[case testPydanticBaseModelInheritance]
[case testPydanticBaseModelInheritance_semanal]
from pydantic import BaseModel

class BaseUser(BaseModel):
Expand Down
Loading