Skip to content

Commit e9d28a0

Browse files
TRMandersongvanrossum
authored andcommitted
Prevent crash on retrieving TypeVar from class (python#2544)
* Add test for accessing TypeVar class members * Add trailing newline * TypeVar class members should have the type TypeVarType
1 parent 9ad4019 commit e9d28a0

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

mypy/checkmember.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
Overloaded, TypeVarType, UnionType, PartialType,
88
DeletedType, NoneTyp, TypeType, function_type
99
)
10-
from mypy.nodes import TypeInfo, FuncBase, Var, FuncDef, SymbolNode, Context, MypyFile
10+
from mypy.nodes import TypeInfo, FuncBase, Var, FuncDef, SymbolNode, Context, MypyFile, TypeVarExpr
1111
from mypy.nodes import ARG_POS, ARG_STAR, ARG_STAR2
1212
from mypy.nodes import Decorator, OverloadedFuncDef
1313
from mypy.messages import MessageBuilder
@@ -379,6 +379,9 @@ def analyze_class_attribute_access(itype: Instance,
379379
not_ready_callback(name, context)
380380
return AnyType()
381381

382+
if isinstance(node.node, TypeVarExpr):
383+
return TypeVarType(node.tvar_def, node.tvar_def.line, node.tvar_def.column)
384+
382385
if isinstance(node.node, TypeInfo):
383386
return type_object_type(node.node, builtin_type)
384387

test-data/unit/check-typevar-values.test

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -489,3 +489,11 @@ def outer(x: T) -> T:
489489
return inner1('a') # E: Argument 1 to "inner1" has incompatible type "str"; expected "int"
490490
return inner1(x)
491491
[out]
492+
493+
[case testClassMemberTypeVarInFunctionBody]
494+
from typing import TypeVar
495+
class C:
496+
T = TypeVar('T', int)
497+
def f(self, x: T) -> T:
498+
A = C.T
499+
return x

0 commit comments

Comments
 (0)