mypy is really handy and catches a lot of bugs, but when I write "scientific" applications, I often end up doing:
def my_func(number: Union[float, int]): # Do something
number
is either a float or int, depending on the user's input. Is there an official way to do that?
PEP 484 introduced type hints — a way to make Python feel statically typed. While type hints can help structure your projects better, they are just that — hints — and by default do not affect the runtime.
Union type; Union[X, Y] is equivalent to X | Y and means either X or Y. To define a union, use e.g. Union[int, str] or the shorthand int | str . Using that shorthand is recommended.
The purpose of the Any type is to indicate to the type checker that a part of the program should not be checked. A variable (or function parameter) that is annotated with the Any type accepts any value, and the type checker allows any operation on it.
List. Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
You can define your own type to address this and keep your code cleaner.
FloatInt = Union[float, int] def my_func(number: FloatInt): # Do something
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 typefloat
, an argument of typeint
is acceptable; similar, for an argument annotated as having type complex, arguments of type float or int are acceptable.
(Bold emphasis mine).
Ideally you would still use numbers.Real
:
from numbers import Real def my_func(number: Real):
as that would accept fractions.Fraction()
and decimal.Decimal()
objects as well; the number pyramid is broader than just integers and floating point values.
However, these are not currently working when using mypy
to do your type checking, see Mypy #3186.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With