mypy fails on code where a variable length tuple contains different types. What should I be doing here?
for i, *s in [(1, 'a'), (2, 'b', 'c')]:
print(hex(i), '_'.join(s))
main.py:2: error: Argument 1 to "hex" has incompatible type "int | str"; expected "int | SupportsIndex" [arg-type]
main.py:2: error: Argument 1 to "join" of "str" has incompatible type "list[int | str]"; expected "Iterable[str]" [arg-type]
PEP 646 introduced a way to spell variadic tuples with fixed prefixes and suffices.
A tuple of "int followed by zero or more strings" would be denoted
tuple[int, *tuple[str, ...]]
However, mypy will not infer such complex types from literals without type context. Annotating your list explicitly suffices:
options: list[tuple[int, *tuple[str, ...]]] = [(1, 'a'), (2, 'b', 'c')]
for i, *s in options:
print(hex(i), '_'.join(s))
(if you're on python < 3.11, use typing_extensions.Unpack[] instead of * unpacking)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With