Sigma65535
Sigma65535

Reputation: 381

How does collections.namedtuple work?

I am studying the code of "namedtuple" in Python.(Python 3.6.3). I run the code :

from collections import namedtuple,_iskeyword
Point = namedtuple('Point', ['x', 'y'],rename=False,verbose=True)
p = Point(2,3)
print(p)

and then the console print such as :

from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict

class Point(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))

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new Point object from a sequence or iterable'
        result = new(cls, iterable)
        if len(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

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values.'
        return OrderedDict(zip(self._fields, self))

    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return tuple(self)

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

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

this is the class definition, I am confused with the class's definition:

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

At here the property as _property, the fget function of property is _itemgetter(0).

My question is:

What the return of _itemgetter(0)?

How does the _property work in this case?

Upvotes: 0

Views: 3731

Answers (1)

Mike Müller
Mike Müller

Reputation: 85542

Short Answer

It allows you to use p[0] as well as p.x to retrieve the value 2:

>>> p.x
2
>>> p[0]
2

Explanation

property allows you to call a method without the (). So p.x instead of p.x().

itemgetter(0) is a function for the [] indexing syntax. In this case it gets the element at this index from the underlying tuple.

It returns a new function:

>>> f = _itemgetter(0)

Calling this function:

>>> f(t)
10

has the same effect as:

>>> t[0]
10

Finally, property makes it "callable" without adding the ()at the end.

Upvotes: 2

Related Questions