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

Difference between defining typing.Dict and dict?

There is no real difference between using a plain typing.Dict and dict, no. However, typing.Dict is a Generic type * that lets you specify the type of the keys and values too, making it more flexible: def change_bandwidths(new_bandwidths: typing.Dict[str, str], user_id: int, user_name: str) -> bool: As such, it could well be that at some … Read more

What is the type hint for a (any) python module?

and types.ModuleType() is a constructor. That doesn’t matter. types.ModuleType is still a reference to a type, just like str and int are. There is no need for a generic Module[typehint] annotation, so types.ModuleType is exacly what you need to use here. For example, the official Python typeshed project provides a type hint annotation for sys.modules … Read more

Can I omit Optional if I set default to None?

No. Omitting Optional was previously allowed, but has since been removed. A past version of this PEP allowed type checkers to assume an optional type when the default value is None […] This is no longer the recommended behavior. Type checkers should move towards requiring the optional type to be made explicit. Some tools may … 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

What’s the difference between a constrained TypeVar and a Union?

T‘s type must be consistent across multiple uses within a given scope, while U‘s does not. With a Union type used as function parameters, the arguments as well as the return type can all be different: U = Union[int, str] def union_f(arg1: U, arg2: U) -> U: return arg1 x = union_f(1, “b”) # No … Read more

tech