Skip to content

Commit 028bd91

Browse files
authored
Make NamedTuple attributes read-only (#5299)
Fixes #5293
1 parent add0ea5 commit 028bd91

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

mypy/subtypes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -524,7 +524,7 @@ def get_member_flags(name: str, info: TypeInfo) -> Set[int]:
524524
if v.var.is_staticmethod or v.var.is_classmethod:
525525
return {IS_CLASS_OR_STATIC}
526526
# just a variable
527-
if isinstance(v, Var):
527+
if isinstance(v, Var) and not v.is_property:
528528
flags = {IS_SETTABLE}
529529
if v.is_classvar:
530530
flags.add(IS_CLASSVAR)

test-data/unit/check-namedtuple.test

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,23 @@ a.y = 5 # E: Property "y" defined in "X" is read-only
5151
-- a.z = 5 # not supported yet
5252

5353

54+
[case testTypingNamedTupleAttributesAreReadOnly]
55+
from typing import NamedTuple
56+
from typing_extensions import Protocol
57+
58+
class HasX(Protocol):
59+
x: str
60+
61+
class A(NamedTuple):
62+
x: str
63+
64+
a: HasX = A("foo")
65+
a.x = "bar"
66+
[out]
67+
main:10: error: Incompatible types in assignment (expression has type "A", variable has type "HasX")
68+
main:10: note: Protocol member HasX.x expected settable variable, got read-only attribute
69+
70+
5471
[case testNamedTupleCreateWithPositionalArguments]
5572
from collections import namedtuple
5673

0 commit comments

Comments
 (0)