namedtuple

Extend tuples and provide some niceties


In [1]:
from collections import namedtuple

In [12]:
# Let's create a namedtuple called Point that takes x and y
# verbose=True shows you the implementation
Point = namedtuple('Point', ['x', 'y'], verbose=True)


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')



In [15]:
# New point with x=11 and y=12
p = Point(11, 12)

In [16]:
p


Out[16]:
Point(x=11, y=12)

In [17]:
# x
p[0]


Out[17]:
11

In [19]:
# y
p[1]


Out[19]:
12

In [20]:
# Isn't it nicer to be able to reference things by their name and not an index?
p.x


Out[20]:
11

In [21]:
p.y


Out[21]:
12

In [24]:
# p is really a tuple so it's hashable, in other words it can be used as a key in dictionaries
hash(p)


Out[24]:
3713075136762760156

In [25]:
x = {}

In [28]:
# Dictionaries are not hashable
hash(x)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-0393e386f18b> in <module>()
----> 1 hash(x)

TypeError: unhashable type: 'dict'

In [26]:
p


Out[26]:
Point(x=11, y=12)

In [ ]:
x[p] = 2

In [27]:
x


Out[27]:
{Point(x=11, y=12): 2}