Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mypy fails with mixed types in variable length tuple [closed]

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]
like image 710
grahamstratton Avatar asked Nov 03 '25 22:11

grahamstratton


1 Answers

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)

like image 116
STerliakov Avatar answered Nov 05 '25 13:11

STerliakov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!