Allow a base class to restrict the type of subclass's inner class
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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 class Meta must implement a certain protocol:
# Defined in the framework
class InnerMetaProtocol(Protocol):
example_attr: str
class Model:
Meta: type[InnerMetaProtocol]
# An application developer using framework
class Widget(Model):
class Meta:
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]).
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the issue's Playground example and compare the declared Model.Meta type with the subclass's inner Meta class. The work is done when mypy reports the incompatible int example and supports the stated protocol and concrete-class cases.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100