@@ -20,6 +20,14 @@ Type checkers should support the class syntax::
20
20
y: int
21
21
units: str = "meters"
22
22
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
+
23
31
Regardless of whether the class syntax or factory function call is used to define
24
32
a named tuple, type checkers should synthesize a ``__new__ `` method based on
25
33
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::
79
87
Point5 = NamedTuple('Point5', [('x', int), ('y', int)])
80
88
Point6 = NamedTuple('Point6', (('x', int), ('y', int)))
81
89
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::
87
95
88
96
NT1 = namedtuple("NT1", ["a", "a"]) # Type error (duplicate field name)
89
97
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
90
102
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
93
105
94
106
The ``namedtuple `` function also supports a ``defaults `` keyword argument that
95
107
specifies default values for the fields. Type checkers may support this::
0 commit comments