Skip to content

Commit e2d2c11

Browse files
AFanaeiJukkaL
authored andcommitted
Produce error when NamedTuple is assigned to attribute (#7662)
Fixes #7531.
1 parent 70f2857 commit e2d2c11

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

mypy/semanal.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2126,14 +2126,17 @@ def analyze_namedtuple_assign(self, s: AssignmentStmt) -> bool:
21262126
"""Check if s defines a namedtuple."""
21272127
if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.analyzed, NamedTupleExpr):
21282128
return True # This is a valid and analyzed named tuple definition, nothing to do here.
2129-
if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr):
2129+
if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], (NameExpr, MemberExpr)):
21302130
return False
21312131
lvalue = s.lvalues[0]
21322132
name = lvalue.name
21332133
is_named_tuple, info = self.named_tuple_analyzer.check_namedtuple(s.rvalue, name,
21342134
self.is_func_scope())
21352135
if not is_named_tuple:
21362136
return False
2137+
if isinstance(s.lvalues[0], MemberExpr):
2138+
self.fail("NamedTuple type as an attribute is not supported", lvalue)
2139+
return False
21372140
# Yes, it's a valid namedtuple, but defer if it is not ready.
21382141
if not info:
21392142
self.mark_incomplete(name, lvalue, becomes_typeinfo=True)

test-data/unit/pythoneval.test

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1479,3 +1479,15 @@ def f_suppresses() -> int:
14791479
[out]
14801480
_testUnreachableWithStdlibContextManagersNoStrictOptional.py:9: error: Statement is unreachable
14811481
_testUnreachableWithStdlibContextManagersNoStrictOptional.py:15: error: Statement is unreachable
1482+
1483+
[case testNamedTupleAtRunTime]
1484+
from typing import NamedTuple
1485+
1486+
class A:
1487+
def __init__(self) -> None:
1488+
self.b = NamedTuple('x', [('s', str), ('n', int)])
1489+
1490+
reveal_type(A().b)
1491+
[out]
1492+
_testNamedTupleAtRunTime.py:5: error: NamedTuple type as an attribute is not supported
1493+
_testNamedTupleAtRunTime.py:7: note: Revealed type is 'Any'

0 commit comments

Comments
 (0)