Skip to content

Commit 97d9ed5

Browse files
authored
Add basic support for typing_extensions.TypeVar (#14313)
This PR only adds the existing `TypeVar` support for the `typing_extensions` variant. I.e. it does not include support for `default` or `infer_variance`. Fixes #14312
1 parent d391f10 commit 97d9ed5

File tree

3 files changed

+39
-3
lines changed

3 files changed

+39
-3
lines changed

mypy/semanal.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3847,7 +3847,7 @@ def process_typevar_declaration(self, s: AssignmentStmt) -> bool:
38473847
Return True if this looks like a type variable declaration (but maybe
38483848
with errors), otherwise return False.
38493849
"""
3850-
call = self.get_typevarlike_declaration(s, ("typing.TypeVar",))
3850+
call = self.get_typevarlike_declaration(s, ("typing.TypeVar", "typing_extensions.TypeVar"))
38513851
if not call:
38523852
return False
38533853

test-data/unit/check-generics.test

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2663,3 +2663,36 @@ def foo(x: A) -> A:
26632663
# N: (Hint: Use "B" in function signature to bind "B" inside a function)
26642664
return y.x
26652665
return bar()[0]
2666+
2667+
2668+
-- TypeVar imported from typing_extensions
2669+
-- ---------------------------------------
2670+
2671+
[case testTypeVarTypingExtensionsSimpleGeneric]
2672+
from typing import Generic
2673+
from typing_extensions import TypeVar
2674+
2675+
T = TypeVar("T")
2676+
2677+
class A(Generic[T]):
2678+
def __init__(self, value: T) -> None:
2679+
self.value = value
2680+
2681+
a: A = A(8)
2682+
b: A[str] = A("")
2683+
2684+
reveal_type(A(1.23)) # N: Revealed type is "__main__.A[builtins.float]"
2685+
2686+
[builtins fixtures/tuple.pyi]
2687+
2688+
[case testTypeVarTypingExtensionsSimpleBound]
2689+
from typing_extensions import TypeVar
2690+
2691+
T= TypeVar("T")
2692+
2693+
def func(var: T) -> T:
2694+
return var
2695+
2696+
reveal_type(func(1)) # N: Revealed type is "builtins.int"
2697+
2698+
[builtins fixtures/tuple.pyi]

test-data/unit/lib-stub/typing_extensions.pyi

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
from typing import TypeVar, Any, Mapping, Iterator, NoReturn as NoReturn, Dict, Type
1+
import typing
2+
from typing import Any, Mapping, Iterator, NoReturn as NoReturn, Dict, Type
23
from typing import TYPE_CHECKING as TYPE_CHECKING
34
from typing import NewType as NewType, overload as overload
45

56
import sys
67

7-
_T = TypeVar('_T')
8+
_T = typing.TypeVar('_T')
89

910
class _SpecialForm:
1011
def __getitem__(self, typeargs: Any) -> Any:
@@ -25,6 +26,8 @@ Literal: _SpecialForm = ...
2526

2627
Annotated: _SpecialForm = ...
2728

29+
TypeVar: _SpecialForm
30+
2831
ParamSpec: _SpecialForm
2932
Concatenate: _SpecialForm
3033

0 commit comments

Comments
 (0)