Skip to content

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

Open
@KotlinIsland

Description

@KotlinIsland
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]

Activity

hauntsaninja

hauntsaninja commented on Aug 11, 2022

@hauntsaninja
Collaborator

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

KotlinIsland

KotlinIsland commented on Aug 11, 2022

@KotlinIsland
ContributorAuthor

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

TypeError: 'TypeVar' object is not subscriptable

(OP has now been updated)

changed the title [-](🐞) `TypeAlias` to a bare `TypeVar` is treated as a generic type, not as as a `TypeVar`[/-] [+]Warn about `TypeAlias` to bare `TypeVar`s[/+] on Aug 11, 2022
changed the title [-]Warn about `TypeAlias` to bare `TypeVar`s[/-] [+](🎁) Warn about `TypeAlias` to bare `TypeVar`s[/+] on Aug 11, 2022
sobolevn

sobolevn commented on Aug 21, 2022

@sobolevn
Member

Also related #13449 (comment)

KotlinIsland

KotlinIsland commented on Mar 3, 2023

@KotlinIsland
ContributorAuthor

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 topic-runtime-semantics mypy doesn't model runtime semantics correctly ?

2 remaining items

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @sobolevn@hauntsaninja@KotlinIsland@AlexWaygood

        Issue actions

          (🎁) No warning about `TypeAlias` to bare `TypeVar` when using `TypeAlias` · Issue #13376 · python/mypy