Currently, I am checking for tuples with multiple (e.g. three) numbers of arbitrary but equal type in the following form:
from typing import Tuple, Union
Union[Tuple[int, int, int], Tuple[float, float, float]]
I want to make this check more generic, also allowing numpy number types. I.e. I tried to use numbers.Number:
from numbers import Number
from typing import Tuple
Tuple[Number, Number, Number]
The above snipped also allows tuples of mixed types as long as everything is a number.
I'd like to restrict the tuple to numbers of equal type.
How can this be achieved?
Technically, this question applies to Python and the type hints specification itself. However, as pointed out in the comments, its handling is implementation specific, i.e. MyPy will not catch every edge case and/or inconsistency. Personally, I am using run-time checks with typeguard for testing and deactivate them entirely in production.
TypeVarbut then realized thatnp.floatingandnp.integerare floats/ints, i.e.isinstance(np.float64(3), float) -> True.np.number. Besides, anumpy.float64is - under most circumstances, depending on configuration, platform and compiler options (sys.float_info) - literally identical to a Pythonfloat, so this kind of thing would actually be ok for me.pytestand hypothesis plus run-time checks.T = TypeVar('T', int, float); Tuple[T, T, T]does not work for you? It should be equivalent to your "manual" versionsTuple[int, int, int]andTuple[float, float, float], so if these manual versions work for you, so should theTypeVarversion.