python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.47k stars 2.83k forks source link

Type application is only supported for generic classes #17804

Open IvanKirpichnikov opened 1 month ago

IvanKirpichnikov commented 1 month ago

To Reproduce

from typing import Any, TYPE_CHECKING

if TYPE_CHECKING:
    from typing import Union, TypeVar
    T = TypeVar('T')
    WithProtocols = Union[T, T]  # noqa: UP007,PYI016
else:
    class WithProtocols:
        def __class_getitem__(cls, item: Any) -> Any:
            return item

WithProtocols[int]

Expected Behavior I expected mypy not to swear

Actual behavior error: Type application is only supported for generic classes [misc]

My environment mypy == 3.11.1 python == 3.11.8

erictraut commented 1 month ago

Here are a couple of workarounds:

from typing import TypeVar

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

or

type WithProtocols[T] = T
IvanKirpichnikov commented 1 month ago

Here are a couple of workarounds:

from typing import TypeVar

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

or

type WithProtocols[T] = T

Unfortunately, pyright swears with such code :(

IvanKirpichnikov commented 1 month ago

Here are a couple of workarounds:

from typing import TypeVar

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

or

type WithProtocols[T] = T

Unfortunately, pyright swears with such code :(

oops, I confused it with Union[T]. Excuse me

But the above decision is not valid