namedtuple 

Send to Kindle
home » snippets » python » namedtuple



Methods / Properties

_asdict

# Return a new OrderedDict which maps field names to their corresponding values:
# Changed in version 3.1: Returns an OrderedDict instead of a regular dict.
somenamedtuple._asdict()

_replace

# Return a new instance of the named tuple replacing specified fields with new values:
somenamedtuple._replace(kwargs)
_fields
Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples.


Sample Code

Basic

Point = namedtuple('Point', ['x', 'y'])
Point = namedtuple('Point', 'x y')

New type with more fields

Point3D = namedtuple('Point3D', Point._fields + ('z',))

Simulating default values

Default values can be implemented by using _replace() to customize a prototype instance:

Account = namedtuple('Account', 'owner balance transaction_count')
default_account = Account('<owner name>', 0.0, 0)
johns_account = default_account._replace(owner='John')
janes_account = default_account._replace(owner='Jane')

Inheriting

class Point(namedtuple('Point', 'x y')):
    __slots__ = ()
    @property
    def hypot(self):
        return (self.x ** 2 + self.y ** 2) ** 0.5
    def __str__(self):
        return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)