Mypy error on __init_subclass__ example from python documentation

Question:

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?

Asked By: I hate JS

||

Answers:

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

Answered By: dROOOze
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.