Search code examples
pythontype-hinting

Is Unpacking a Type Hint Possible? or Its Workarounds?


Is there a way to unpack a tuple type alias? For example,

ResultTypeA = tuple[float, float, dict[str, float]]
ResultTypeB = tuple[*ResultTypeA, str, str]

So that ResultTypeB evaluates to

  • tuple[float, float, dict[str, float], str, str]

instead of

  • tuple[tuple[float, float, dict[str, float]], str, str]

If not possible, what would be a workaround for this?


Solution

  • What you are looking for may be the new typing.TypeVarTuple as proposed by PEP 646. Due to how new it is (Python 3.11+) and how big of a change this produces, many static type checkers still do not fully support it (see this mypy issue for example).

    Maybe typing.Unpack is actually more applicable in this case, but again hardly useful so long as type checkers don't support it.

    But at a certain point, you should probably ask yourself, if your design is all that good, if your type annotations become this complex.