Skip to content

Commit 15fb8b7

Browse files
elazargJukkaL
authored andcommitted
Don't accept underscore for namedtuple fields (#2092)
1 parent 48ae978 commit 15fb8b7

File tree

2 files changed

+8
-0
lines changed

2 files changed

+8
-0
lines changed

mypy/semanal.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1656,6 +1656,10 @@ def parse_namedtuple_args(self, call: CallExpr,
16561656
items, types, ok = self.parse_namedtuple_fields_with_types(listexpr.items, call)
16571657
if not types:
16581658
types = [AnyType() for _ in items]
1659+
underscore = [item for item in items if item.startswith('_')]
1660+
if underscore:
1661+
self.fail("namedtuple() Field names cannot start with an underscore: "
1662+
+ ', '.join(underscore), call)
16591663
return items, types, ok
16601664

16611665
def parse_namedtuple_fields_with_types(self, nodes: List[Node],

test-data/unit/check-namedtuple.test

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ a = x[1]
99
a, b, c = x # E: Need more than 2 values to unpack (3 expected)
1010
x[2] # E: Tuple index out of range
1111

12+
[case testNamedTupleNoUnderscoreFields]
13+
from collections import namedtuple
14+
15+
X = namedtuple('X', 'x, _y, _z') # E: namedtuple() Field names cannot start with an underscore: _y, _z
1216

1317
[case testNamedTupleAccessingAttributes]
1418
from collections import namedtuple

0 commit comments

Comments
 (0)