NamedTuple ¶
- class NamedTuple ¶
-
Typed version of
collections.namedtuple()
.Usage:
class Employee(NamedTuple): name: str id: int
This is equivalent to:
Employee = collections.namedtuple('Employee', ['name', 'id'])
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 an extra attribute
__annotations__
giving a dict that maps the field names to the field types. (The field names are in the_fields
attribute and the default values are in the_field_defaults
attribute both of which are part of the namedtuple API.)NamedTuple
subclasses can also have docstrings and methods:class Employee(NamedTuple): """Represents an employee.""" name: str id: int = 3 def __repr__(self) -> str: return f'<Employee {self.name}, id={self.id}>'
Backward-compatible usage:
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
Changed in version 3.6: Added support for PEP 526 variable annotation syntax.
Changed in version 3.6.1: Added support for default values, methods, and docstrings.
Changed in version 3.8: Deprecated the
_field_types
attribute in favor of the more standard__annotations__
attribute which has the same information.Changed in version 3.8: The
_field_types
and__annotations__
attributes are now regular dictionaries instead of instances ofOrderedDict
.