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

PythonType HintingMypyPython TypingUnion Types

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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 of type int 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.

Solution 2 - Python

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

Solution 3 - Python

Python > 3.10 allows you to do the following.

def my_func(number: int | float) -> int | float: 

Solution 4 - Python

For people who come to this question for the more general problem of Union typing hints for entities which don't have an existing supertype in common, for example Union[int, numpy.ndarray], the solution is to import Union from typing.

Example 1:

from typing import Union

def my_func(number: Union[float, int]):
    # Do something

Example 2:

from typing import Union
import numpy as np

def my_func(x: Union[float, np.ndarray]):
    # do something
    # Do something

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJPFrancoiaView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonCurt WelchView Answer on Stackoverflow
Solution 3 - PythonSuperNovaView Answer on Stackoverflow
Solution 4 - Pythonpatapouf_aiView Answer on Stackoverflow