Skip to content

Produce error when NamedTuple is assigned to attribute #7662

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -2120,14 +2120,17 @@ def analyze_namedtuple_assign(self, s: AssignmentStmt) -> bool:
"""Check if s defines a namedtuple."""
if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.analyzed, NamedTupleExpr):
return True # This is a valid and analyzed named tuple definition, nothing to do here.
if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr):
if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], (NameExpr, MemberExpr)):
return False
lvalue = s.lvalues[0]
name = lvalue.name
is_named_tuple, info = self.named_tuple_analyzer.check_namedtuple(s.rvalue, name,
self.is_func_scope())
if not is_named_tuple:
return False
if isinstance(s.lvalues[0], MemberExpr):
self.fail("NamedTuple type as an attribute is not supported", lvalue)
return False
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved this block to start but then a NamedTuple type as an attrib ... error was generated on every attribute assignment statement.
as the error should raise only if RHS is NamedTuple, i think this block is better at the end.

# Yes, it's a valid namedtuple, but defer if it is not ready.
if not info:
self.mark_incomplete(name, lvalue, becomes_typeinfo=True)
Expand Down
12 changes: 12 additions & 0 deletions test-data/unit/pythoneval.test
Original file line number Diff line number Diff line change
Expand Up @@ -1453,3 +1453,15 @@ def f_suppresses() -> int:
[out]
_testUnreachableWithStdlibContextManagersNoStrictOptional.py:9: error: Statement is unreachable
_testUnreachableWithStdlibContextManagersNoStrictOptional.py:15: error: Statement is unreachable

[case testNamedTupleAtRunTime]
from typing import NamedTuple

class A:
def __init__(self) -> None:
self.b = NamedTuple('x', [('s', str), ('n', int)])

reveal_type(A().b)
[out]
_testNamedTupleAtRunTime.py:5: error: NamedTuple type as an attribute is not supported
_testNamedTupleAtRunTime.py:7: note: Revealed type is 'Any'