Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1 | __all__ = ['deque', 'defaultdict', 'NamedTuple'] |
| 2 | |
| 3 | from _collections import deque, defaultdict |
| 4 | from operator import itemgetter as _itemgetter |
| 5 | import sys as _sys |
| 6 | |
| 7 | def NamedTuple(typename, s): |
| 8 | """Returns a new subclass of tuple with named fields. |
| 9 | |
| 10 | >>> Point = NamedTuple('Point', 'x y') |
| 11 | >>> Point.__doc__ # docstring for the new class |
| 12 | 'Point(x, y)' |
| 13 | >>> p = Point(11, y=22) # instantiate with positional args or keywords |
| 14 | >>> p[0] + p[1] # works just like the tuple (11, 22) |
| 15 | 33 |
| 16 | >>> x, y = p # unpacks just like a tuple |
| 17 | >>> x, y |
| 18 | (11, 22) |
| 19 | >>> p.x + p.y # fields also accessable by name |
| 20 | 33 |
| 21 | >>> p # readable __repr__ with name=value style |
| 22 | Point(x=11, y=22) |
| 23 | |
| 24 | """ |
| 25 | |
| 26 | field_names = s.split() |
| 27 | nargs = len(field_names) |
| 28 | |
| 29 | def __new__(cls, *args, **kwds): |
| 30 | if kwds: |
| 31 | try: |
| 32 | args += tuple(kwds[name] for name in field_names[len(args):]) |
| 33 | except KeyError as name: |
| 34 | raise TypeError('%s missing required argument: %s' % (typename, name)) |
| 35 | if len(args) != nargs: |
| 36 | raise TypeError('%s takes exactly %d arguments (%d given)' % (typename, nargs, len(args))) |
| 37 | return tuple.__new__(cls, args) |
| 38 | |
| 39 | repr_template = '%s(%s)' % (typename, ', '.join('%s=%%r' % name for name in field_names)) |
| 40 | |
| 41 | m = dict(vars(tuple)) # pre-lookup superclass methods (for faster lookup) |
| 42 | m.update(__doc__= '%s(%s)' % (typename, ', '.join(field_names)), |
| 43 | __slots__ = (), # no per-instance dict (so instances are same size as tuples) |
| 44 | __new__ = __new__, |
| 45 | __repr__ = lambda self, _format=repr_template.__mod__: _format(self), |
| 46 | __module__ = _sys._getframe(1).f_globals['__name__'], |
| 47 | ) |
| 48 | m.update((name, property(_itemgetter(index))) for index, name in enumerate(field_names)) |
| 49 | |
| 50 | return type(typename, (tuple,), m) |
| 51 | |
| 52 | |
| 53 | if __name__ == '__main__': |
| 54 | # verify that instances are pickable |
| 55 | from cPickle import loads, dumps |
| 56 | Point = NamedTuple('Point', 'x y') |
| 57 | p = Point(x=10, y=20) |
| 58 | assert p == loads(dumps(p)) |
| 59 | |
| 60 | import doctest |
| 61 | TestResults = NamedTuple('TestResults', 'failed attempted') |
| 62 | print(TestResults(*doctest.testmod())) |