python / python/mypy

(🎁) No warning about `TypeAlias` to bare `TypeVar` when using `TypeAlias`

Open
#13,376 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature priority-2-low topic-runtime-semantics topic-type-alias topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Strangely, the correct error is reported when the TypeAlias is omitted.

from typing import TypeVar, TypeAlias

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the provided test.py reproduction and compare it with the playground configuration using mypy master, Python 3.10, and strict flags. Trace why the TypeAlias form accepts TAlias[int] while the direct alias reports an invalid TypeVar target; done means the alias form produces an appropriate diagnostic and does not accept the invalid subscripted use.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.