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
a
earlier, are you certain you haven't done that? –
Couple a = int(a)
or other re-assignments. If you work with mypy for static type checking, use --allow-redefinition
to avoid the warning –
Malka 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
© 2022 - 2024 — McMap. All rights reserved.
def f() -> Tuple[int, int]: return 1, 2
and my unpackeda, b = f()
both wanta: float
andb: float
. – Embezzlea
andb
will contain integers. No matter which type hints you'll use. – Naperya
andb
should be floats, and will contain floats later, then I'd like to hint them as floats regardless of what function gives their initial value or what hinting it has. – Embezzlea, b = (float(x) for x in f())
. – Naperyint
is actually compatible with/assignable tofloat
from a type checking standpoint (e.g.a: float = 4
is fine). – Lentissimo