Skip to content Skip to sidebar Skip to footer

How Named Tuples Are Implemented Internally In Python?

Named tuples are easy to create, lightweight object types. namedtuple instances can be referenced using object-like variable deferencing or the standard tuple syntax. If these dat

Solution 1:

Actually, it's very easy to find out how a given namedtuple is implemented: if you pass the keyword argument verbose=True when creating it, its class definition is printed:

>>> Point = namedtuple('Point', "x y", verbose=True)
from builtins importpropertyas _property, tupleas _tuplefrom operator import itemgetter as _itemgetter
from collections import OrderedDict

classPoint(tuple):
    'Point(x, y)'

    __slots__ = ()

    _fields = ('x', 'y')

    def__new__(_cls, x, y):
        'Create new instance of Point(x, y)'return _tuple.__new__(_cls, (x, y))

    @classmethoddef_make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new Point object from a sequence or iterable'
        result = new(cls, iterable)
        iflen(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result

    def_replace(_self, **kwds):
        'Return a new Point object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('x', 'y'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % list(kwds))
        return result

    def__repr__(self):
        'Return a nicely formatted representation string'return self.__class__.__name__ + '(x=%r, y=%r)' % self

    @propertydef__dict__(self):
        'A new OrderedDict mapping field names to their values'return OrderedDict(zip(self._fields, self))

    def_asdict(self):
        '''Return a new OrderedDict which maps field names to their values.
           This method is obsolete.  Use vars(nt) or nt.__dict__ instead.
        '''return self.__dict__

    def__getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'returntuple(self)

    def__getstate__(self):
        'Exclude the OrderedDict from pickling'returnNone

    x = _property(_itemgetter(0), doc='Alias for field number 0')

    y = _property(_itemgetter(1), doc='Alias for field number 1')

So, it's a subclass of tuple with some extra methods to give it the required behaviour, a _fields class-level constant containing the field names, and property methods for attribute access to the tuple's members.

As for the code behind actually building this class definition, that's deep magic.

Post a Comment for "How Named Tuples Are Implemented Internally In Python?"