mypy icon indicating copy to clipboard operation
mypy copied to clipboard

(🎁) Warn about `TypeAlias` to bare `TypeVar`s

Open KotlinIsland opened this issue 3 years ago • 2 comments

from typing import TypeVar, TypeAlias

T = TypeVar("T")
TAlias: TypeAlias = T

def foo(
    t1: TAlias[int],  # no error
    t2: TAlias,  # error: Missing type parameters for generic type "TAlias"
) -> None: ...

Treating it as a generic type and not as TypeVar is incorrect as at runtime it is not subscriptable:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    t1: TAlias[int],  # no error
TypeError: 'TypeVar' object is not subscriptable

playground

KotlinIsland avatar Aug 11 '22 02:08 KotlinIsland

I think this is "as designed". This is just a very dumb generic type alias

hauntsaninja avatar Aug 11 '22 03:08 hauntsaninja

@hauntsaninja I know, the issue is that it's a runtime error:

TypeError: 'TypeVar' object is not subscriptable

(OP has now been updated)

KotlinIsland avatar Aug 11 '22 03:08 KotlinIsland

Also related https://github.com/python/mypy/issues/13449#issuecomment-1221507260

sobolevn avatar Aug 21 '22 11:08 sobolevn

Strangely, it correctly reports the error when the TypeAlias is ommitted.

from typing import TypeVar, TypeAlias

T = TypeVar("T")
TAlias = T  # error: Type variable "__main__.T" is invalid as target for type alias  [misc]

Can we have https://github.com/python/mypy/labels/topic-runtime-semantics?

KotlinIsland avatar Mar 03 '23 02:03 KotlinIsland