From 30850455b96a804094bfba99b71119c989976280 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Mon, 19 Dec 2022 11:41:56 +0100 Subject: [PATCH] Add basic support for typing_extensions.TypeVar --- mypy/semanal.py | 2 +- test-data/unit/check-generics.test | 33 +++++++++++++++++++ test-data/unit/lib-stub/typing_extensions.pyi | 7 ++-- 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/mypy/semanal.py b/mypy/semanal.py index fee66ae9b2ccf..9160097028305 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -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 diff --git a/test-data/unit/check-generics.test b/test-data/unit/check-generics.test index dd7e31528a4fe..27441ce908fe8 100644 --- a/test-data/unit/check-generics.test +++ b/test-data/unit/check-generics.test @@ -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] diff --git a/test-data/unit/lib-stub/typing_extensions.pyi b/test-data/unit/lib-stub/typing_extensions.pyi index e92f7e9135027..cbf692fc71111 100644 --- a/test-data/unit/lib-stub/typing_extensions.pyi +++ b/test-data/unit/lib-stub/typing_extensions.pyi @@ -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: @@ -25,6 +26,8 @@ Literal: _SpecialForm = ... Annotated: _SpecialForm = ... +TypeVar: _SpecialForm + ParamSpec: _SpecialForm Concatenate: _SpecialForm