pythonmypypython-typing

Annotate a tuple with variable number of items and first item is of different type


A few valid values for a tuple that I'm trying to annotate:

("foo", 1, 2)
("bar", 11)
("baz", 42, 31, 20, 0, -700, 44444, 12345, 1, 2, 3, 4, 5, 6, 7, 8, 9)

I was expecting this to work:

my_tuple: Tuple[str, int, ...]  # doesn't work!

... but that throws error: Unexpected '...'

Any way to annotate this structure?


Solution

  • In Python 3.11 I can now do the following:

    my_tuple: tuple[str, *tuple[int, ...]] = ("foo", 1, 2)
    

    This was added in PEP 646


    For Python pre-3.11 (courtesy of @FMeinicke) typing_extensions.Unpack can be used instead [1,2,3].

    from typing_extensions import Unpack
    
    my_tuple: tuple[str, Unpack[tuple[int, ...]]] = ("foo", 1, 2)
    

    though, note that there might still be issues with generic typed aliases pre-3.11, see https://github.com/python/typing_extensions/issues/103.