Reputation: 1280
Is there a way to type hint a tuple of elements without having to define each inner element a bunch of times?
Example:
a = ((1, 2), (2, 3), (3, 4), (4, 5))
a: Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int], Tuple[int, int]]
I am looking for something that may look like this
a: Tuple[5*Tuple[int, int]]
as otherwise my code would become very verbose in order to indicate something like that (tuple containing 5 tuples of 4 ints)
Upvotes: 5
Views: 2458
Reputation: 7569
There's a few options here. (All examples here assume a = ((1, 2), (3, 4), (5, 6), (7, 8))
, i.e., a tuple
consisting of 4 (<int>, <int>)
tuples.)
You could, as has been suggested in the comments, just use a type alias for the inner type:
from typing import Tuple
X = Tuple[int, int]
a: Tuple[X, X, X, X]
You could also use a type alias for the whole annotation if it's still too long, perhaps using typing.Annotated
to clarify what's going on in your code:
from typing import Tuple, Annotated
X = Tuple[int, int]
IntTupleSequence = Annotated[
Tuple[X, X, X, X],
"Some useful metatadata here giving "
"some documentation about this type alias"
]
a: IntTupleSequence
You could also use typing.Sequence
, which is useful for if you have a homogenous sequence (that may be mutable or immutable) that's either of indeterminate length or would be too long to feasibly annotate using typing.Tuple
:
from typing import Sequence, Tuple
a: Sequence[Tuple[int, int]]
You can achieve the same thing as Sequence
by using Tuple
with a literal ellipsis. The ellipsis here signifies that the tuple will be of indeterminate length but homogenous type.
from typing Sequence, Tuple
a: Tuple[Tuple[int, int], ...]
I prefer using Sequence
to using Tuple
with an ellipsis, however. It's more concise, seems like a more intuitive syntax to me (...
is used to mean something similar to Any
in other parts of the typing
module such as Callable
), and I rarely find there's anything gained by telling the type-checker that my immutable Sequence
is specifically of type tuple
. That's just my opinion, however.
A final option might be to use a NamedTuple
instead of a tuple
for variable a
. However, that might be overkill if all items in your tuple are of a homogenous type. (NamedTuple
is most useful for annotating heterogeneous tuples.)
Upvotes: 7