Skip to content

Commit 3c062be

Browse files
committed
Produce error when NamedTuple is assigned to attribute
Fixes #7531
1 parent bd00106 commit 3c062be

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

mypy/semanal.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2120,14 +2120,17 @@ def analyze_namedtuple_assign(self, s: AssignmentStmt) -> bool:
21202120
"""Check if s defines a namedtuple."""
21212121
if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.analyzed, NamedTupleExpr):
21222122
return True # This is a valid and analyzed named tuple definition, nothing to do here.
2123-
if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr):
2123+
if len(s.lvalues) != 1 or type(s.lvalues[0]) not in [NameExpr, MemberExpr]:
21242124
return False
21252125
lvalue = s.lvalues[0]
21262126
name = lvalue.name
21272127
is_named_tuple, info = self.named_tuple_analyzer.check_namedtuple(s.rvalue, name,
21282128
self.is_func_scope())
21292129
if not is_named_tuple:
21302130
return False
2131+
if isinstance(s.lvalues[0], MemberExpr):
2132+
self.fail("NamedTuple type as an attribute is not supported", s.lvalues[0])
2133+
return False
21312134
# Yes, it's a valid namedtuple, but defer if it is not ready.
21322135
if not info:
21332136
self.mark_incomplete(name, lvalue, becomes_typeinfo=True)

test-data/unit/check-namedtuple.test

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -853,3 +853,10 @@ b = (1, 2)
853853
if not b:
854854
''() # E: "str" not callable
855855
[builtins fixtures/tuple.pyi]
856+
857+
[case testNamedTupleAtRunTime]
858+
from typing import NamedTuple
859+
860+
class A:
861+
def __init__(self) -> None:
862+
self.b = NamedTuple('x', [('s', str), ('n', int)]) # E: NamedTuple type as an attribute is not supported

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy