Why is cls() allowed in Python mypy?

Viewed 76

Why is cls() accepted by mypy in

from __future__ import annotations
from typing import TypeVar

T = TypeVar("T", bound="A")

class A:
    @classmethod
    def create(cls: type[T]) -> T:
        return cls()

If I subclass A with a different __init__ signature,

class B(A):
    def __init__(self, a: int):
        super().__init__()
        self.a = a

B.create()

It still passes mypy (which I don't think it should), but at runtime I get

TypeError: __init__() missing 1 required positional argument: 'a'

as expected.

(this question is based on this one but here I'm asking why no error rather than why error)

0 Answers
Related