You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
For regular classvars, attributes and methods, mypy already checks that the types in a subclass match those declared in the superclass. However, this checking does not extend to inner classes in the subclass. It seems inner classes are ignored by mypy entirely.
For example, a framework could define an abstract class Model whose inner class Meta must implement a certain protocol:
# Defined in the frameworkclassInnerMetaProtocol(Protocol):
example_attr: strclassModel:
Meta: type[InnerMetaProtocol]
# An application developer using frameworkclassWidget(Model):
classMeta:
example_attr=123# This should be an error: int is not str
Class Widget implements Model, whose attribute Meta should conform to type[InnerMetaProtocol], meaning it requires attribute example_attr: str. But currently mypy ignores this constraint: Playground.
It's probably useful to support this with not just protocols, but also concrete classes (e.g. Meta: type[ConcreteClass]).
There is a workaround, if the Meta class is defined separately (not as inner class), and then assigned to the attribute. But this feels very unnatural and clunky for people coming from the Django ecosystem. (Playground)
# An application developer using frameworkclassWidgetMeta:
example_attr=123classWidget(Model):
Meta=WidgetMeta# E: Incompatible types in assignment (expression has type "Type[WidgetMeta]", base class "Model" defined the type as "Type[InnerMetaProtocol]")
Although this is only a piece of the puzzle: to take full advantage of this with Django, we would also need optional Protocol members, or something like #5504 (total=False for Protocols).
Feature
For regular classvars, attributes and methods, mypy already checks that the types in a subclass match those declared in the superclass. However, this checking does not extend to inner classes in the subclass. It seems inner classes are ignored by mypy entirely.
For example, a framework could define an abstract class
Model
whose inner classMeta
must implement a certain protocol:Class
Widget
implementsModel
, whose attributeMeta
should conform totype[InnerMetaProtocol]
, meaning it requires attributeexample_attr: str
. But currently mypy ignores this constraint: Playground.It's probably useful to support this with not just protocols, but also concrete classes (e.g.
Meta: type[ConcreteClass]
).Pitch
This pattern of inner
Meta
classes is used quite extensively in the Django ecosystem, including for Django models, forms, Django REST Framework serializers, djangorestframework-dataclasses, etc. I'm sure there are other use cases as well, but I don't know off the top of my head.The text was updated successfully, but these errors were encountered: