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

Type hinting / annotation (PEP 484) for numpy.ndarray

Update Check recent numpy versions for a new typing module https://numpy.org/doc/stable/reference/typing.html#module-numpy.typing dated answer It looks like typing module was developed at: https://github.com/python/typing The main numpy repository is at https://github.com/numpy/numpy Python bugs and commits can be tracked at http://bugs.python.org/ The usual way of adding a feature is to fork the main repository, develop the feature till … Read more

Defining a recursive type hint in Python?

You can specify recursive types in the typing language by using type aliases and forward reference strings, Garthoks = Union[Garthok, Iterable[‘Garthoks’]] Note that recursive types are not yet supported by mypy. But it will likely be added eventually. Update 2020/9/14: Microsoft announces support for recursive types in Pyright/Pylance. Some types of forward references are handled … 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

Python 3 dictionary with known keys typing

As pointed out by Blckknght, you and Stanislav Ivanov in the comments, you can use NamedTuple: from typing import NamedTuple class NameInfo(NamedTuple): name: str first_letter: str def get_info(name: str) -> NameInfo: return NameInfo(name=name, first_letter=name[0]) Starting from Python 3.8 you can use TypedDict which is more similar to what you want: from typing import TypedDict class … Read more

Can you annotate return type when value is instance of cls?

Use a generic type to indicate that you’ll be returning an instance of cls: from typing import Type, TypeVar T = TypeVar(‘T’, bound=’TrivialClass’) class TrivialClass: # … @classmethod def from_int(cls: Type[T], int_arg: int) -> T: # … return cls(…) Any subclass overriding the class method but then returning an instance of a parent class (TrivialClass … Read more