Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e53bd8e

Browse files
committed
Issue 29310: Document typing.NamedTuple default argument syntax
1 parent dc4ce0e commit e53bd8e

1 file changed

Lines changed: 18 additions & 4 deletions

File tree

Doc/library/typing.rst

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -735,10 +735,21 @@ The module defines the following classes, functions and decorators:
735735

736736
Employee = collections.namedtuple('Employee', ['name', 'id'])
737737

738-
The resulting class has one extra attribute: ``_field_types``,
739-
giving a dict mapping field names to types. (The field names
740-
are in the ``_fields`` attribute, which is part of the namedtuple
741-
API.)
738+
To give a field a default value, you can assign to it in the class body::
739+
740+
class Employee(NamedTuple):
741+
name: str
742+
id: int = 3
743+
744+
employee = Employee('Guido')
745+
assert employee.id == 3
746+
747+
Fields with a default value must come after any fields without a default.
748+
749+
The resulting class has two extra attributes: ``_field_types``,
750+
giving a dict mapping field names to types, and ``field_defaults``, a dict
751+
mapping field names to default values. (The field names are in the
752+
``_fields`` attribute, which is part of the namedtuple API.)
742753

743754
Backward-compatible usage::
744755

@@ -747,6 +758,9 @@ The module defines the following classes, functions and decorators:
747758
.. versionchanged:: 3.6
748759
Added support for :pep:`526` variable annotation syntax.
749760

761+
.. versionchanged:: 3.6.1
762+
Added support for default values.
763+
750764
.. function:: NewType(typ)
751765

752766
A helper function to indicate a distinct types to a typechecker,

0 commit comments

Comments
 (0)