Validating detailed types in python dataclasses

Instead of checking for type equality, you should use isinstance. But you cannot use a parametrized generic type (typing.List[int]) to do so, you must use the “generic” version (typing.List). So you will be able to check for the container type but not the contained types. Parametrized generic types define an __origin__ attribute that you can … Read more

Type hints: solve circular dependency [duplicate]

You can use a forward reference by using a string name for the not-yet-defined Client class: class Server(): def register_client(self, client: ‘Client’) pass As of Python 3.7, you can also postpone all runtime parsing of annotations by adding the following __future__ import at the top of your module: from __future__ import annotations at which point … Read more

How to annotate a type that’s a class object (instead of a class instance)?

To annotate an object that is a class, use typing.Type. For example, this would tell the type checker that some_class is class Foo or any of its subclasses: from typing import Type class Foo: … class Bar(Foo): … class Baz: … some_class: Type[Foo] some_class = Foo # ok some_class = Bar # ok some_class = … Read more

typing.Any vs object?

Yes, there is a difference. Although in Python 3, all objects are instances of object, including object itself, only Any documents that the return value should be disregarded by the typechecker. The Any type docstring states that object is a subclass of Any and vice-versa: >>> import typing >>> print(typing.Any.__doc__) Special type indicating an unconstrained … Read more

Python type hinting with exceptions

Type hinting can’t say anything about exceptions. They are entirely out of scope for the feature. You can still document the exception in the docstring however. From PEP 484 — Type Hints: Exceptions No syntax for listing explicitly raised exceptions is proposed. Currently the only known use case for this feature is documentational, in which … 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