rest25/library/collections.rst => rest262/library/collections.rst
2:mod:`collections` --- High-performance container datatypes
3===========================================================
4
5.. module:: collections
6   :synopsis: High-performance datatypes
7.. moduleauthor:: Raymond Hettinger <python@rcn.com>
8.. sectionauthor:: Raymond Hettinger <python@rcn.com>
9
n10- 
11.. versionadded:: 2.4
12
n12+.. testsetup:: *
13+ 
14+   from collections import *
15+   import itertools
16+   __name__ = '<doctest>'
17+ 
13-This module implements high-performance container datatypes.  Currently, there
18+This module implements high-performance container datatypes.  Currently,
14-are two datatypes, deque and defaultdict. Future additions may include balanced
19+there are two datatypes, :class:`deque` and :class:`defaultdict`, and
15-trees and ordered dictionaries.
20+one datatype factory function, :func:`namedtuple`.
16
17.. versionchanged:: 2.5
n18-   Added defaultdict.
n23+   Added :class:`defaultdict`.
24+ 
25+.. versionchanged:: 2.6
26+   Added :func:`namedtuple`.
27+ 
28+The specialized containers provided in this module provide alternatives
29+to Python's general purpose built-in containers, :class:`dict`,
30+:class:`list`, :class:`set`, and :class:`tuple`.
31+ 
32+Besides the containers provided here, the optional :mod:`bsddb`
33+module offers the ability to create in-memory or file based ordered
34+dictionaries with string keys using the :meth:`bsddb.btopen` method.
35+ 
36+In addition to containers, the collections module provides some ABCs
37+(abstract base classes) that can be used to test whether a class
38+provides a particular interface, for example, is it hashable or
39+a mapping.
40+ 
41+.. versionchanged:: 2.6
42+   Added abstract base classes.
43+ 
44+ABCs - abstract base classes
45+----------------------------
46+ 
47+The collections module offers the following ABCs:
48+ 
49+=========================  =====================  ======================  ====================================================
50+ABC                        Inherits               Abstract Methods        Mixin Methods
51+=========================  =====================  ======================  ====================================================
52+:class:`Container`                                ``__contains__``
53+:class:`Hashable`                                 ``__hash__``
54+:class:`Iterable`                                 ``__iter__``
55+:class:`Iterator`          :class:`Iterable`      ``__next__``            ``__iter__``
56+:class:`Sized`                                    ``__len__``
57+:class:`Callable`                                 ``__call__``
58+ 
59+:class:`Sequence`          :class:`Sized`,        ``__getitem__``         ``__contains__``. ``__iter__``, ``__reversed__``.
60+                           :class:`Iterable`,                             ``index``, and ``count``
61+                           :class:`Container`
62+ 
63+:class:`MutableSequence`   :class:`Sequence`      ``__setitem__``         Inherited Sequence methods and
64+                                                  ``__delitem__``,        ``append``, ``reverse``, ``extend``, ``pop``,
65+                                                  and ``insert``          ``remove``, and ``__iadd__``
66+ 
67+:class:`Set`               :class:`Sized`,                                ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
68+                           :class:`Iterable`,                             ``__gt__``, ``__ge__``, ``__and__``, ``__or__``
69+                           :class:`Container`                             ``__sub__``, ``__xor__``, and ``isdisjoint``
70+ 
71+:class:`MutableSet`        :class:`Set`           ``add`` and             Inherited Set methods and
72+                                                  ``discard``             ``clear``, ``pop``, ``remove``, ``__ior__``,
73+                                                                          ``__iand__``, ``__ixor__``, and ``__isub__``
74+ 
75+:class:`Mapping`           :class:`Sized`,        ``__getitem__``         ``__contains__``, ``keys``, ``items``, ``values``,
76+                           :class:`Iterable`,                             ``get``, ``__eq__``, and ``__ne__``
77+                           :class:`Container`
78+ 
79+:class:`MutableMapping`    :class:`Mapping`       ``__setitem__`` and     Inherited Mapping methods and
80+                                                  ``__delitem__``         ``pop``, ``popitem``, ``clear``, ``update``,
81+                                                                          and ``setdefault``
82+ 
83+ 
84+:class:`MappingView`       :class:`Sized`                                 ``__len__``
85+:class:`KeysView`          :class:`MappingView`,                          ``__contains__``,
86+                           :class:`Set`                                   ``__iter__``
87+:class:`ItemsView`         :class:`MappingView`,                          ``__contains__``,
88+                           :class:`Set`                                   ``__iter__``
89+:class:`ValuesView`        :class:`MappingView`                           ``__contains__``, ``__iter__``
90+=========================  =====================  ======================  ====================================================
91+ 
92+These ABCs allow us to ask classes or instances if they provide
93+particular functionality, for example::
94+ 
95+    size = None
96+    if isinstance(myvar, collections.Sized):
97+        size = len(myvar)
98+ 
99+Several of the ABCs are also useful as mixins that make it easier to develop
100+classes supporting container APIs.  For example, to write a class supporting
101+the full :class:`Set` API, it only necessary to supply the three underlying
102+abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`.
103+The ABC supplies the remaining methods such as :meth:`__and__` and
104+:meth:`isdisjoint` ::
105+ 
106+    class ListBasedSet(collections.Set):
107+         ''' Alternate set implementation favoring space over speed
108+             and not requiring the set elements to be hashable. '''
109+         def __init__(self, iterable):
110+             self.elements = lst = []
111+             for value in iterable:
112+                 if value not in lst:
113+                     lst.append(value)
114+         def __iter__(self):
115+             return iter(self.elements)
116+         def __contains__(self, value):
117+             return value in self.elements
118+         def __len__(self):
119+             return len(self.elements)
120+ 
121+    s1 = ListBasedSet('abcdef')
122+    s2 = ListBasedSet('defghi')
123+    overlap = s1 & s2            # The __and__() method is supported automatically
124+ 
125+Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
126+ 
127+(1)
128+   Since some set operations create new sets, the default mixin methods need
129+   a way to create new instances from an iterable. The class constructor is
130+   assumed to have a signature in the form ``ClassName(iterable)``.
131+   That assumption is factored-out to an internal classmethod called
132+   :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
133+   If the :class:`Set` mixin is being used in a class with a different
134+   constructor signature, you will need to override :meth:`from_iterable`
135+   with a classmethod that can construct new instances from
136+   an iterable argument.
137+ 
138+(2)
139+   To override the comparisons (presumably for speed, as the
140+   semantics are fixed), redefine :meth:`__le__` and
141+   then the other operations will automatically follow suit.
142+ 
143+(3)
144+   The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value
145+   for the set; however, :meth:`__hash__` is not defined because not all sets
146+   are hashable or immutable.  To add set hashabilty using mixins,
147+   inherit from both :meth:`Set` and :meth:`Hashable`, then define
148+   ``__hash__ = Set._hash``.
149+ 
150+.. seealso::
151+ 
152+   * `OrderedSet recipe <http://code.activestate.com/recipes/576694/>`_ for an
153+     example built on :class:`MutableSet`.
154+ 
155+   * For more about ABCs, see the :mod:`abc` module and :pep:`3119`.
19
20
21.. _deque-objects:
22
23:class:`deque` objects
24----------------------
25
26
n27-.. function:: deque([iterable])
n164+.. class:: deque([iterable[, maxlen]])
28
n29-   Returns a new deque objected initialized left-to-right (using :meth:`append`)
n166+   Returns a new deque object initialized left-to-right (using :meth:`append`) with
30-   with data from *iterable*.  If *iterable* is not specified, the new deque is
167+   data from *iterable*.  If *iterable* is not specified, the new deque is empty.
31-   empty.
32
33   Deques are a generalization of stacks and queues (the name is pronounced "deck"
34   and is short for "double-ended queue").  Deques support thread-safe, memory
35   efficient appends and pops from either side of the deque with approximately the
n36-   same ``O(1)`` performance in either direction.
n172+   same O(1) performance in either direction.
37
38   Though :class:`list` objects support similar operations, they are optimized for
n39-   fast fixed-length operations and incur ``O(n)`` memory movement costs for
n175+   fast fixed-length operations and incur O(n) memory movement costs for
40   ``pop(0)`` and ``insert(0, v)`` operations which change both the size and
41   position of the underlying data representation.
42
43   .. versionadded:: 2.4
44
n181+   If *maxlen* is not specified or is *None*, deques may grow to an
182+   arbitrary length.  Otherwise, the deque is bounded to the specified maximum
183+   length.  Once a bounded length deque is full, when new items are added, a
184+   corresponding number of items are discarded from the opposite end.  Bounded
185+   length deques provide functionality similar to the ``tail`` filter in
186+   Unix. They are also useful for tracking transactions and other pools of data
187+   where only the most recent activity is of interest.
188+ 
189+   .. versionchanged:: 2.6
190+      Added *maxlen* parameter.
191+ 
45-Deque objects support the following methods:
192+   Deque objects support the following methods:
46
47
n48-.. method:: XXX Class.append(x)
n195+   .. method:: append(x)
49
n50-   Add *x* to the right side of the deque.
n197+      Add *x* to the right side of the deque.
51
52
n53-.. method:: XXX Class.appendleft(x)
n200+   .. method:: appendleft(x)
54
n55-   Add *x* to the left side of the deque.
n202+      Add *x* to the left side of the deque.
56
57
n58-.. method:: XXX Class.clear()
n205+   .. method:: clear()
59
n60-   Remove all elements from the deque leaving it with length 0.
n207+      Remove all elements from the deque leaving it with length 0.
61
62
n63-.. method:: XXX Class.extend(iterable)
n210+   .. method:: extend(iterable)
64
n65-   Extend the right side of the deque by appending elements from the iterable
n212+      Extend the right side of the deque by appending elements from the iterable
66-   argument.
213+      argument.
67
68
n69-.. method:: XXX Class.extendleft(iterable)
n216+   .. method:: extendleft(iterable)
70
n71-   Extend the left side of the deque by appending elements from *iterable*.  Note,
n218+      Extend the left side of the deque by appending elements from *iterable*.
72-   the series of left appends results in reversing the order of elements in the
219+      Note, the series of left appends results in reversing the order of
73-   iterable argument.
220+      elements in the iterable argument.
74
75
n76-.. method:: XXX Class.pop()
n223+   .. method:: pop()
77
n78-   Remove and return an element from the right side of the deque. If no elements
n225+      Remove and return an element from the right side of the deque. If no
79-   are present, raises an :exc:`IndexError`.
226+      elements are present, raises an :exc:`IndexError`.
80
81
n82-.. method:: XXX Class.popleft()
n229+   .. method:: popleft()
83
n84-   Remove and return an element from the left side of the deque. If no elements are
n231+      Remove and return an element from the left side of the deque. If no
85-   present, raises an :exc:`IndexError`.
232+      elements are present, raises an :exc:`IndexError`.
86
87
n88-.. method:: XXX Class.remove(value)
n235+   .. method:: remove(value)
89
n90-   Removed the first occurrence of *value*.  If not found, raises a
n237+      Removed the first occurrence of *value*.  If not found, raises a
91-   :exc:`ValueError`.
238+      :exc:`ValueError`.
92
n93-   .. versionadded:: 2.5
n240+      .. versionadded:: 2.5
94
95
n96-.. method:: XXX Class.rotate(n)
n243+   .. method:: rotate(n)
97
n98-   Rotate the deque *n* steps to the right.  If *n* is negative, rotate to the
n245+      Rotate the deque *n* steps to the right.  If *n* is negative, rotate to
99-   left.  Rotating one step to the right is equivalent to:
246+      the left.  Rotating one step to the right is equivalent to:
100-   ``d.appendleft(d.pop())``.
247+      ``d.appendleft(d.pop())``.
248+ 
101
102In addition to the above, deques support iteration, pickling, ``len(d)``,
103``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with
n104-the :keyword:`in` operator, and subscript references such as ``d[-1]``.
n252+the :keyword:`in` operator, and subscript references such as ``d[-1]``.  Indexed
253+access is O(1) at both ends but slows to O(n) in the middle.  For fast random
254+access, use lists instead.
105
n106-Example::
n256+Example:
257+ 
258+.. doctest::
107
108   >>> from collections import deque
109   >>> d = deque('ghi')                 # make a new deque with three items
110   >>> for elem in d:                   # iterate over the deque's elements
n111-   ...     print elem.upper()   
n263+   ...     print elem.upper()
112   G
113   H
114   I
115
116   >>> d.append('j')                    # add a new entry to the right side
117   >>> d.appendleft('f')                # add a new entry to the left side
118   >>> d                                # show the representation of the deque
119   deque(['f', 'g', 'h', 'i', 'j'])
154
155   >>> d.extendleft('abc')              # extendleft() reverses the input order
156   >>> d
157   deque(['c', 'b', 'a'])
158
159
160.. _deque-recipes:
161
n162-Recipes
n314+:class:`deque` Recipes
163-^^^^^^^
315+^^^^^^^^^^^^^^^^^^^^^^
164
165This section shows various approaches to working with deques.
166
167The :meth:`rotate` method provides a way to implement :class:`deque` slicing and
168deletion.  For example, a pure python implementation of ``del d[n]`` relies on
169the :meth:`rotate` method to position elements to be popped::
170
171   def delete_nth(d, n):
172       d.rotate(-n)
173       d.popleft()
174       d.rotate(n)
175
176To implement :class:`deque` slicing, use a similar approach applying
177:meth:`rotate` to bring a target element to the left side of the deque. Remove
178old entries with :meth:`popleft`, add new entries with :meth:`extend`, and then
179reverse the rotation.
n180- 
181With minor variations on that approach, it is easy to implement Forth style
182stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``,
183``rot``, and ``roll``.
184
n185-A roundrobin task server can be built from a :class:`deque` using
186-:meth:`popleft` to select the current task and :meth:`append` to add it back to
187-the tasklist if the input stream is not exhausted::
188- 
189-   def roundrobin(*iterables):
190-       pending = deque(iter(i) for i in iterables)
191-       while pending:
192-           task = pending.popleft()
193-           try:
194-               yield task.next()
195-           except StopIteration:
196-               continue
197-           pending.append(task)
198- 
199-   >>> for value in roundrobin('abc', 'd', 'efgh'):
200-   ...     print value
201- 
202-   a
203-   d
204-   e
205-   b
206-   f
207-   c
208-   g
209-   h
210- 
211- 
212Multi-pass data reduction algorithms can be succinctly expressed and efficiently
213coded by extracting elements with multiple calls to :meth:`popleft`, applying
n214-the reduction function, and calling :meth:`append` to add the result back to the
n338+a reduction function, and calling :meth:`append` to add the result back to the
215-queue.
339+deque.
216
217For example, building a balanced binary tree of nested lists entails reducing
n218-two adjacent nodes into one by grouping them in a list::
n342+two adjacent nodes into one by grouping them in a list:
219
n220-   def maketree(iterable):
n344+   >>> def maketree(iterable):
221-       d = deque(iterable)
345+   ...     d = deque(iterable)
222-       while len(d) > 1:
346+   ...     while len(d) > 1:
223-           pair = [d.popleft(), d.popleft()]
347+   ...         pair = [d.popleft(), d.popleft()]
224-           d.append(pair)
348+   ...         d.append(pair)
225-       return list(d)
349+   ...     return list(d)
226- 
350+   ...
227   >>> print maketree('abcdefgh')
228   [[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
229
n354+Bounded length deques provide functionality similar to the ``tail`` filter
355+in Unix::
230
n357+   def tail(filename, n=10):
358+       'Return the last n lines of a file'
359+       return deque(open(filename), n)
231
232.. _defaultdict-objects:
233
234:class:`defaultdict` objects
235----------------------------
236
237
n238-.. function:: defaultdict([default_factory[, ...]])
n367+.. class:: defaultdict([default_factory[, ...]])
239
240   Returns a new dictionary-like object.  :class:`defaultdict` is a subclass of the
241   builtin :class:`dict` class.  It overrides one method and adds one writable
242   instance variable.  The remaining functionality is the same as for the
243   :class:`dict` class and is not documented here.
244
245   The first argument provides the initial value for the :attr:`default_factory`
246   attribute; it defaults to ``None``. All remaining arguments are treated the same
247   as if they were passed to the :class:`dict` constructor, including keyword
248   arguments.
249
250   .. versionadded:: 2.5
251
n252-:class:`defaultdict` objects support the following method in addition to the
n381+   :class:`defaultdict` objects support the following method in addition to the
253-standard :class:`dict` operations:
382+   standard :class:`dict` operations:
254
255
n256-.. method:: XXX Class.__missing__(key)
n385+   .. method:: defaultdict.__missing__(key)
257
n258-   If the :attr:`default_factory` attribute is ``None``, this raises an
n387+      If the :attr:`default_factory` attribute is ``None``, this raises a
259-   :exc:`KeyError` exception with the *key* as argument.
388+      :exc:`KeyError` exception with the *key* as argument.
260
n261-   If :attr:`default_factory` is not ``None``, it is called without arguments to
n390+      If :attr:`default_factory` is not ``None``, it is called without arguments
262-   provide a default value for the given *key*, this value is inserted in the
391+      to provide a default value for the given *key*, this value is inserted in
263-   dictionary for the *key*, and returned.
392+      the dictionary for the *key*, and returned.
264
n265-   If calling :attr:`default_factory` raises an exception this exception is
n394+      If calling :attr:`default_factory` raises an exception this exception is
266-   propagated unchanged.
395+      propagated unchanged.
267
n268-   This method is called by the :meth:`__getitem__` method of the :class:`dict`
n397+      This method is called by the :meth:`__getitem__` method of the
269-   class when the requested key is not found; whatever it returns or raises is then
398+      :class:`dict` class when the requested key is not found; whatever it
270-   returned or raised by :meth:`__getitem__`.
399+      returns or raises is then returned or raised by :meth:`__getitem__`.
271
n401+ 
272-:class:`defaultdict` objects support the following instance variable:
402+   :class:`defaultdict` objects support the following instance variable:
273
274
n275-.. data:: default_factory
n405+   .. attribute:: defaultdict.default_factory
276
n277-   This attribute is used by the :meth:`__missing__` method; it is initialized from
n407+      This attribute is used by the :meth:`__missing__` method; it is
278-   the first argument to the constructor, if present, or to ``None``,  if absent.
408+      initialized from the first argument to the constructor, if present, or to
409+      ``None``, if absent.
279
280
281.. _defaultdict-examples:
282
283:class:`defaultdict` Examples
284^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
285
286Using :class:`list` as the :attr:`default_factory`, it is easy to group a
n287-sequence of key-value pairs into a dictionary of lists::
n418+sequence of key-value pairs into a dictionary of lists:
288
289   >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
290   >>> d = defaultdict(list)
291   >>> for k, v in s:
n292-           d[k].append(v)
n423+   ...     d[k].append(v)
293- 
424+   ...
294   >>> d.items()
295   [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
296
297When each key is encountered for the first time, it is not already in the
298mapping; so an entry is automatically created using the :attr:`default_factory`
299function which returns an empty :class:`list`.  The :meth:`list.append`
300operation then attaches the value to the new list.  When keys are encountered
301again, the look-up proceeds normally (returning the list for that key) and the
302:meth:`list.append` operation adds another value to the list. This technique is
n303-simpler and faster than an equivalent technique using :meth:`dict.setdefault`::
n434+simpler and faster than an equivalent technique using :meth:`dict.setdefault`:
304
305   >>> d = {}
306   >>> for k, v in s:
n307-        d.setdefault(k, []).append(v)
n438+   ...     d.setdefault(k, []).append(v)
308- 
439+   ...
309   >>> d.items()
310   [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
311
312Setting the :attr:`default_factory` to :class:`int` makes the
313:class:`defaultdict` useful for counting (like a bag or multiset in other
n314-languages)::
n445+languages):
315
316   >>> s = 'mississippi'
317   >>> d = defaultdict(int)
318   >>> for k in s:
n319-           d[k] += 1
n450+   ...     d[k] += 1
320- 
451+   ...
321   >>> d.items()
322   [('i', 4), ('p', 2), ('s', 4), ('m', 1)]
323
324When a letter is first encountered, it is missing from the mapping, so the
325:attr:`default_factory` function calls :func:`int` to supply a default count of
n326-zero.  The increment operation then builds up the count for each letter. This
n457+zero.  The increment operation then builds up the count for each letter.
327-technique makes counting simpler and faster than an equivalent technique using
328-:meth:`dict.get`::
329
n330-   >>> d = {}
n459+The function :func:`int` which always returns zero is just a special case of
331-   >>> for k in s:
460+constant functions.  A faster and more flexible way to create constant functions
332-        d[k] = d.get(k, 0) + 1
461+is to use :func:`itertools.repeat` which can supply any constant value (not just
462+zero):
333
n334-   >>> d.items()
n464+   >>> def constant_factory(value):
335-   [('i', 4), ('p', 2), ('s', 4), ('m', 1)]
465+   ...     return itertools.repeat(value).next
466+   >>> d = defaultdict(constant_factory('<missing>'))
467+   >>> d.update(name='John', action='ran')
468+   >>> '%(name)s %(action)s to %(object)s' % d
469+   'John ran to <missing>'
336
337Setting the :attr:`default_factory` to :class:`set` makes the
n338-:class:`defaultdict` useful for building a dictionary of sets::
n472+:class:`defaultdict` useful for building a dictionary of sets:
339
340   >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
341   >>> d = defaultdict(set)
342   >>> for k, v in s:
n343-           d[k].add(v)
n477+   ...     d[k].add(v)
344- 
478+   ...
345   >>> d.items()
346   [('blue', set([2, 4])), ('red', set([1, 3]))]
347
t482+ 
483+.. _named-tuple-factory:
484+ 
485+:func:`namedtuple` Factory Function for Tuples with Named Fields
486+----------------------------------------------------------------
487+ 
488+Named tuples assign meaning to each position in a tuple and allow for more readable,
489+self-documenting code.  They can be used wherever regular tuples are used, and
490+they add the ability to access fields by name instead of position index.
491+ 
492+.. function:: namedtuple(typename, field_names, [verbose])
493+ 
494+   Returns a new tuple subclass named *typename*.  The new subclass is used to
495+   create tuple-like objects that have fields accessible by attribute lookup as
496+   well as being indexable and iterable.  Instances of the subclass also have a
497+   helpful docstring (with typename and field_names) and a helpful :meth:`__repr__`
498+   method which lists the tuple contents in a ``name=value`` format.
499+ 
500+   The *field_names* are a single string with each fieldname separated by whitespace
501+   and/or commas, for example ``'x y'`` or ``'x, y'``.  Alternatively, *field_names*
502+   can be a sequence of strings such as ``['x', 'y']``.
503+ 
504+   Any valid Python identifier may be used for a fieldname except for names
505+   starting with an underscore.  Valid identifiers consist of letters, digits,
506+   and underscores but do not start with a digit or underscore and cannot be
507+   a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, *print*,
508+   or *raise*.
509+ 
510+   If *verbose* is true, the class definition is printed just before being built.
511+ 
512+   Named tuple instances do not have per-instance dictionaries, so they are
513+   lightweight and require no more memory than regular tuples.
514+ 
515+   .. versionadded:: 2.6
516+ 
517+Example:
518+ 
519+.. doctest::
520+   :options: +NORMALIZE_WHITESPACE
521+ 
522+   >>> Point = namedtuple('Point', 'x y', verbose=True)
523+   class Point(tuple):
524+           'Point(x, y)'
525+   <BLANKLINE>
526+           __slots__ = ()
527+   <BLANKLINE>
528+           _fields = ('x', 'y')
529+   <BLANKLINE>
530+           def __new__(cls, x, y):
531+               return tuple.__new__(cls, (x, y))
532+   <BLANKLINE>
533+           @classmethod
534+           def _make(cls, iterable, new=tuple.__new__, len=len):
535+               'Make a new Point object from a sequence or iterable'
536+               result = new(cls, iterable)
537+               if len(result) != 2:
538+                   raise TypeError('Expected 2 arguments, got %d' % len(result))
539+               return result
540+   <BLANKLINE>
541+           def __repr__(self):
542+               return 'Point(x=%r, y=%r)' % self
543+   <BLANKLINE>
544+           def _asdict(t):
545+               'Return a new dict which maps field names to their values'
546+               return {'x': t[0], 'y': t[1]}
547+   <BLANKLINE>
548+           def _replace(self, **kwds):
549+               'Return a new Point object replacing specified fields with new values'
550+               result = self._make(map(kwds.pop, ('x', 'y'), self))
551+               if kwds:
552+                   raise ValueError('Got unexpected field names: %r' % kwds.keys())
553+               return result
554+   <BLANKLINE>
555+           def __getnewargs__(self):
556+               return tuple(self)
557+   <BLANKLINE>
558+           x = property(itemgetter(0))
559+           y = property(itemgetter(1))
560+ 
561+   >>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
562+   >>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
563+   33
564+   >>> x, y = p                # unpack like a regular tuple
565+   >>> x, y
566+   (11, 22)
567+   >>> p.x + p.y               # fields also accessible by name
568+   33
569+   >>> p                       # readable __repr__ with a name=value style
570+   Point(x=11, y=22)
571+ 
572+Named tuples are especially useful for assigning field names to result tuples returned
573+by the :mod:`csv` or :mod:`sqlite3` modules::
574+ 
575+   EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
576+ 
577+   import csv
578+   for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
579+       print emp.name, emp.title
580+ 
581+   import sqlite3
582+   conn = sqlite3.connect('/companydata')
583+   cursor = conn.cursor()
584+   cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
585+   for emp in map(EmployeeRecord._make, cursor.fetchall()):
586+       print emp.name, emp.title
587+ 
588+In addition to the methods inherited from tuples, named tuples support
589+three additional methods and one attribute.  To prevent conflicts with
590+field names, the method and attribute names start with an underscore.
591+ 
592+.. method:: somenamedtuple._make(iterable)
593+ 
594+   Class method that makes a new instance from an existing sequence or iterable.
595+ 
596+.. doctest::
597+ 
598+      >>> t = [11, 22]
599+      >>> Point._make(t)
600+      Point(x=11, y=22)
601+ 
602+.. method:: somenamedtuple._asdict()
603+ 
604+   Return a new dict which maps field names to their corresponding values::
605+ 
606+      >>> p._asdict()
607+      {'x': 11, 'y': 22}
608+ 
609+.. method:: somenamedtuple._replace(kwargs)
610+ 
611+   Return a new instance of the named tuple replacing specified fields with new
612+   values:
613+ 
614+::
615+ 
616+      >>> p = Point(x=11, y=22)
617+      >>> p._replace(x=33)
618+      Point(x=33, y=22)
619+ 
620+      >>> for partnum, record in inventory.items():
621+      ...     inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
622+ 
623+.. attribute:: somenamedtuple._fields
624+ 
625+   Tuple of strings listing the field names.  Useful for introspection
626+   and for creating new named tuple types from existing named tuples.
627+ 
628+.. doctest::
629+ 
630+      >>> p._fields            # view the field names
631+      ('x', 'y')
632+ 
633+      >>> Color = namedtuple('Color', 'red green blue')
634+      >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
635+      >>> Pixel(11, 22, 128, 255, 0)
636+      Pixel(x=11, y=22, red=128, green=255, blue=0)
637+ 
638+To retrieve a field whose name is stored in a string, use the :func:`getattr`
639+function:
640+ 
641+    >>> getattr(p, 'x')
642+    11
643+ 
644+To convert a dictionary to a named tuple, use the double-star-operator
645+(as described in :ref:`tut-unpacking-arguments`):
646+ 
647+   >>> d = {'x': 11, 'y': 22}
648+   >>> Point(**d)
649+   Point(x=11, y=22)
650+ 
651+Since a named tuple is a regular Python class, it is easy to add or change
652+functionality with a subclass.  Here is how to add a calculated field and
653+a fixed-width print format:
654+ 
655+    >>> class Point(namedtuple('Point', 'x y')):
656+    ...     __slots__ = ()
657+    ...     @property
658+    ...     def hypot(self):
659+    ...         return (self.x ** 2 + self.y ** 2) ** 0.5
660+    ...     def __str__(self):
661+    ...         return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)
662+ 
663+    >>> for p in Point(3, 4), Point(14, 5/7.):
664+    ...     print p
665+    Point: x= 3.000  y= 4.000  hypot= 5.000
666+    Point: x=14.000  y= 0.714  hypot=14.018
667+ 
668+The subclass shown above sets ``__slots__`` to an empty tuple.  This keeps
669+keep memory requirements low by preventing the creation of instance dictionaries.
670+ 
671+Subclassing is not useful for adding new, stored fields.  Instead, simply
672+create a new named tuple type from the :attr:`_fields` attribute:
673+ 
674+    >>> Point3D = namedtuple('Point3D', Point._fields + ('z',))
675+ 
676+Default values can be implemented by using :meth:`_replace` to
677+customize a prototype instance:
678+ 
679+    >>> Account = namedtuple('Account', 'owner balance transaction_count')
680+    >>> default_account = Account('<owner name>', 0.0, 0)
681+    >>> johns_account = default_account._replace(owner='John')
682+ 
683+Enumerated constants can be implemented with named tuples, but it is simpler
684+and more efficient to use a simple class declaration:
685+ 
686+    >>> Status = namedtuple('Status', 'open pending closed')._make(range(3))
687+    >>> Status.open, Status.pending, Status.closed
688+    (0, 1, 2)
689+    >>> class Status:
690+    ...     open, pending, closed = range(3)
691+ 
692+.. seealso::
693+ 
694+   `Named tuple recipe <http://code.activestate.com/recipes/500261/>`_
695+   adapted for Python 2.4.
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op