[Python-checkins] cpython (3.6): Issue 29310: Document typing.NamedTuple default argument syntax

raymond.hettinger python-checkins at python.org
Sat Jan 28 23:17:14 EST 2017


https://hg.python.org/cpython/rev/b33c3f26eefa
changeset:   106327:b33c3f26eefa
branch:      3.6
parent:      106323:ff3312ce1d14
user:        Raymond Hettinger <python at rcn.com>
date:        Sat Jan 28 20:16:40 2017 -0800
summary:
  Issue 29310: Document typing.NamedTuple default argument syntax

files:
  Doc/library/typing.rst |  22 ++++++++++++++++++----
  1 files changed, 18 insertions(+), 4 deletions(-)


diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst
--- a/Doc/library/typing.rst
+++ b/Doc/library/typing.rst
@@ -735,10 +735,21 @@
 
        Employee = collections.namedtuple('Employee', ['name', 'id'])
 
-   The resulting class has one extra attribute: ``_field_types``,
-   giving a dict mapping field names to types.  (The field names
-   are in the ``_fields`` attribute, which is part of the namedtuple
-   API.)
+   To give a field a default value, you can assign to it in the class body::
+
+      class Employee(NamedTuple):
+          name: str
+          id: int = 3
+
+      employee = Employee('Guido')
+      assert employee.id == 3
+
+   Fields with a default value must come after any fields without a default.
+
+   The resulting class has two extra attributes: ``_field_types``,
+   giving a dict mapping field names to types, and ``field_defaults``, a dict
+   mapping field names to default values.  (The field names are in the
+   ``_fields`` attribute, which is part of the namedtuple API.)
 
    Backward-compatible usage::
 
@@ -747,6 +758,9 @@
    .. versionchanged:: 3.6
       Added support for :pep:`526` variable annotation syntax.
 
+   .. versionchanged:: 3.6.1
+      Added support for default values.
+
 .. function:: NewType(typ)
 
    A helper function to indicate a distinct types to a typechecker,

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list