Is it possible to use type hinting when unpacking a tuple? I want to do this, but it results in a SyntaxError
:
from typing import Tuple
t: Tuple[int, int] = (1, 2)
a: int, b: int = t
# ^ SyntaxError: invalid syntax
Is it possible to use type hinting when unpacking a tuple? I want to do this, but it results in a SyntaxError
:
from typing import Tuple
t: Tuple[int, int] = (1, 2)
a: int, b: int = t
# ^ SyntaxError: invalid syntax
According to PEP-0526, you should annotate the types first, then do the unpacking
a: int
b: int
a, b = t
In my case i use the typing.cast
function to type hint an unpack operation.
t: tuple[int, int] = (1, 2)
a, b = t
# type hint of a -> Literal[1]
# type hint of b -> Literal[2]
By using the cast(new_type, old_type)
you can cast those ugly literals into integers.
from typing import cast
a, b = cast(tuple[int, int], t)
# type hint of a -> int
# type hint of b -> int
This can be useful while working with Numpy NDArrays with Unknown
types
# type hint of arr -> ndarray[Unknown, Unknown]
a, b = cast(tuple[float, float], arr[i, j, :2]
# type hint of a -> float
# type hint of b -> float