How to pass generic through type alias?

Question:

How to pass generic through type alias?

a: typing.Tuple[int, int, int] = (1, 1, 1) 

a: typing.Tuple[int, int] = (1, 1) 

We can customize the number of generics. However:

T = typing.Tuple

a: T[int, int, int] = (1, 1, 1) 

This will not work, unless:

T = typing.Tuple[int, int, int]

a: T[int, int, int] = (1, 1, 1) 

This will not work too

T = typing.Tuple[ int , ... ]

a: T[int, int, int] = (1, 1, 1) 

But my goal is:

T = typing.Tuple

a: T[int, int, int] = (1, 1, 1) 

a: T[int, int] = (1, 1)

able to customize generic like typing.Tuple. How can I do it?

Asked By: Micah

||

Answers:

If I am not mistaken, this is indeed a bug in mypy, which comes down to the type checker wrongly assuming that the type arguments to the generic — in this case Tuple — are just Any during aliasing. (see discussion here)

The workaround is relatively straightforward. You don’t assign, you alias on import:

from builtins import tuple as t  # for Python 3.9+
from typing import Tuple as T

a: T[int, int, int] = (1, 1, 1)
b: t[float, float] = (1., 2.)
Answered By: Daniil Fajnberg
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.