Skip to content

Commit 9e8a7ff

Browse files
committed
add field name restrictions to namedtuple spec
1 parent 54b6ce2 commit 9e8a7ff

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

docs/spec/namedtuples.rst

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,14 @@ Type checkers should support the class syntax::
2020
y: int
2121
units: str = "meters"
2222

23+
Fields must be annotated attributes - methods and un-annotated attributes are not
24+
considered fields. Field names may not start with an underscore.
25+
26+
class MyTuple(NamedTuple):
27+
x1 = 1 # Not a field
28+
def x2() -> None: pass # Not a field
29+
_x3: int # Type error: illegal field name
30+
2331
Regardless of whether the class syntax or factory function call is used to define
2432
a named tuple, type checkers should synthesize a ``__new__`` method based on
2533
the named tuple fields. This mirrors the runtime behavior. In the example
@@ -79,17 +87,21 @@ A type checker may support the factory function call in its various forms::
7987
Point5 = NamedTuple('Point5', [('x', int), ('y', int)])
8088
Point6 = NamedTuple('Point6', (('x', int), ('y', int)))
8189

82-
At runtime, the ``namedtuple`` function disallows field names that are
83-
illegal Python identifiers and either raises an exception or replaces these
84-
fields with a parameter name of the form ``_N``. The behavior depends on
85-
the value of the ``rename`` argument. Type checkers may replicate this
86-
behavior statically::
90+
At runtime, the ``namedtuple`` function disallows field names that begin with
91+
an underscore or are illegal Python identifiers, and either raises an exception
92+
or replaces these fields with a parameter name of the form ``_N``. The behavior
93+
depends on the value of the ``rename`` argument. Type checkers may replicate
94+
this behavior statically::
8795

8896
NT1 = namedtuple("NT1", ["a", "a"]) # Type error (duplicate field name)
8997
NT2 = namedtuple("NT2", ["abc", "def"], rename=False) # Type error (illegal field name)
98+
NT3 = namedtuple("NT3", ["abc", "_d"], rename=False) # Type error (illegal field name)
99+
100+
NT4 = namedtuple("NT4", ["abc", "def"], rename=True) # OK
101+
NT4(abc="", _1="") # OK
90102

91-
NT3 = namedtuple("NT3", ["abc", "def"], rename=True) # OK
92-
NT3(abc="", _1="") # OK
103+
NT5 = namedtuple("NT5", ["abc", "_d"], rename=True) # OK
104+
NT5(abc="", _1="") # OK
93105

94106
The ``namedtuple`` function also supports a ``defaults`` keyword argument that
95107
specifies default values for the fields. Type checkers may support this::

0 commit comments

Comments
 (0)