Skip to content

Commit

Permalink
Add basic support for typing_extensions.TypeVar (#14313)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
cdce8p authored Dec 19, 2022
1 parent d391f10 commit 97d9ed5
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
2 changes: 1 addition & 1 deletion mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -3847,7 +3847,7 @@ def process_typevar_declaration(self, s: AssignmentStmt) -> bool:
Return True if this looks like a type variable declaration (but maybe
with errors), otherwise return False.
"""
call = self.get_typevarlike_declaration(s, ("typing.TypeVar",))
call = self.get_typevarlike_declaration(s, ("typing.TypeVar", "typing_extensions.TypeVar"))
if not call:
return False

Expand Down
33 changes: 33 additions & 0 deletions test-data/unit/check-generics.test
Original file line number Diff line number Diff line change
Expand Up @@ -2663,3 +2663,36 @@ def foo(x: A) -> A:
# N: (Hint: Use "B" in function signature to bind "B" inside a function)
return y.x
return bar()[0]


-- TypeVar imported from typing_extensions
-- ---------------------------------------

[case testTypeVarTypingExtensionsSimpleGeneric]
from typing import Generic
from typing_extensions import TypeVar

T = TypeVar("T")

class A(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value

a: A = A(8)
b: A[str] = A("")

reveal_type(A(1.23)) # N: Revealed type is "__main__.A[builtins.float]"

[builtins fixtures/tuple.pyi]

[case testTypeVarTypingExtensionsSimpleBound]
from typing_extensions import TypeVar

T= TypeVar("T")

def func(var: T) -> T:
return var

reveal_type(func(1)) # N: Revealed type is "builtins.int"

[builtins fixtures/tuple.pyi]
7 changes: 5 additions & 2 deletions test-data/unit/lib-stub/typing_extensions.pyi
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from typing import TypeVar, Any, Mapping, Iterator, NoReturn as NoReturn, Dict, Type
import typing
from typing import Any, Mapping, Iterator, NoReturn as NoReturn, Dict, Type
from typing import TYPE_CHECKING as TYPE_CHECKING
from typing import NewType as NewType, overload as overload

import sys

_T = TypeVar('_T')
_T = typing.TypeVar('_T')

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

Annotated: _SpecialForm = ...

TypeVar: _SpecialForm

ParamSpec: _SpecialForm
Concatenate: _SpecialForm

Expand Down

0 comments on commit 97d9ed5

Please sign in to comment.