Is Unpacking a Type Hint Possible? or Its Workarounds?

Inyoung Kim 김인영

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?

Daniil Fajnberg

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related