Python: type-hinting a classmethod that returns an instance of the class, for a class that is inherited

For an example of how to apply Brian’s answer: with a TypeVar: from typing import TypeVar AnyA = TypeVar(“AnyA”, bound=”A”) class A: def __init__(self): print(“A”) self.hello = “hello” @classmethod def bobo(cls: type[AnyA]) -> AnyA: return cls() class B(A): def __init__(self): print(“B”) super().__init__() self.world = “world” reveal_type(B.bobo()) # B with Self: from typing import Self class … Read more

How to annotate function that takes a tuple of variable length? (variadic tuple type annotation)

We can annotate variable-length homogeneous tuples using the … literal (aka Ellipsis) like this: def process_tuple(t: Tuple[str, …]): … or for Python3.9+ def process_tuple(t: tuple[str, …]): … After that, the errors should go away. From the docs: To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, …]. A plain Tuple is … Read more

mypy, type hint: Union[float, int] -> is there a Number type?

Use float only, as int is implied in that type: def my_func(number: float): PEP 484 Type Hints specifically states that: Rather than requiring that users write import numbers and then use numbers.Float etc., this PEP proposes a straightforward shortcut that is almost as effective: when an argument is annotated as having type float, an argument … Read more

A way to subclass NamedTuple for purposes of typechecking

The way named tuples are constructed make inheritance from typing.NamedTuple classes as yet not possible. You’d have to write your own metaclass to extend the typing.NamedTupleMeta class to make subclassing work, and even then the class generated by collections.namedtuple() is just not built to extend. Instead, you want to use the new dataclasses module to … Read more

Specify length of Sequence or List with Python typing module

You can’t. A list is a mutable, variable length structure. If you need a fixed-length structure, use a tuple instead: Tuple[float, float, float, float, float, float, float, float, float, float] Or better still, use a named tuple, which has both indices and named attributes: class BunchOfFloats(NamedTuple): foo: float bar: float baz: float spam: float ham: … Read more