Search code examples
pythonmypymetaclass

Mypy error on __init_subclass__ example from python documentation


From the official Python 3 documentation for __init__subclass__:

class Philosopher:
    def __init_subclass__(cls, /, default_name: str, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.default_name = default_name

class AustralianPhilosopher(Philosopher, default_name="Bruce"):
    pass

The problem is, mypy raises "Type[Philosopher]" has no attribute "default_name". What is the solution for this? How can I make mypy take these values?


Solution

  • Just like the style of other statically-typed languages, you simply declare the variable as an attribute in the class body:

    from typing import ClassVar
    
    class Philosopher:
        default_name: ClassVar[str]
        def __init_subclass__(cls, /, default_name: str, **kwargs: object) -> None:
            super().__init_subclass__(**kwargs)
            cls.default_name = default_name