diff --git a/mypy/checkmember.py b/mypy/checkmember.py index ede8b9189698..6c934dccb022 100644 --- a/mypy/checkmember.py +++ b/mypy/checkmember.py @@ -406,7 +406,9 @@ def analyze_class_attribute_access(itype: Instance, return AnyType() if isinstance(node.node, TypeVarExpr): - return TypeVarType(node.tvar_def, node.tvar_def.line, node.tvar_def.column) + msg.fail('Type variable "{}.{}" cannot be used as an expression'.format( + itype.type.name(), name), context) + return AnyType() if isinstance(node.node, TypeInfo): return type_object_type(node.node, builtin_type) diff --git a/mypy/typeanal.py b/mypy/typeanal.py index dc1e22a32969..d5132421f8d5 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -43,6 +43,9 @@ def analyze_type_alias(node: Expression, # that we don't support straight string literals as type aliases # (only string literals within index expressions). if isinstance(node, RefExpr): + # Note that this misses the case where someone tried to use a + # class-referenced type variable as a type alias. It's easier to catch + # that one in checkmember.py if node.kind == UNBOUND_TVAR or node.kind == BOUND_TVAR: fail_func('Type variable "{}" is invalid as target for type alias'.format( node.fullname), node) diff --git a/test-data/unit/check-typevar-values.test b/test-data/unit/check-typevar-values.test index f41710ee155b..36df2235a209 100644 --- a/test-data/unit/check-typevar-values.test +++ b/test-data/unit/check-typevar-values.test @@ -496,12 +496,20 @@ def outer(x: T) -> T: [out] [case testClassMemberTypeVarInFunctionBody] -from typing import TypeVar +from typing import TypeVar, List class C: T = TypeVar('T', bound=int) def f(self, x: T) -> T: - A = C.T - return x + L = List[C.T] # a valid type alias + l: L = [] + reveal_type(l) # E: Revealed type is 'builtins.list[T`-1]' + y: C.T = x + l.append(x) + C.T # E: Type variable "C.T" cannot be used as an expression + A = C.T # E: Type variable "C.T" cannot be used as an expression + return l[0] + +[builtins fixtures/list.pyi] [case testParameterLessGenericAsRestriction] from typing import Sequence, Iterable, TypeVar