blob: 1e32f9921306b178c0858dfeba9d9a3e107b0347 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
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
10
Georg Brandl116aa622007-08-15 14:28:22 +000011This module implements high-performance container datatypes. Currently,
12there are two datatypes, :class:`deque` and :class:`defaultdict`, and
Raymond Hettingerebcee3f2008-02-06 19:54:00 +000013one datatype factory function, :func:`namedtuple`.
Georg Brandl116aa622007-08-15 14:28:22 +000014
Raymond Hettingerebcee3f2008-02-06 19:54:00 +000015The specialized containers provided in this module provide alternatives
16to Python's general purpose built-in containers, :class:`dict`,
17:class:`list`, :class:`set`, and :class:`tuple`.
18
19Besides the containers provided here, the optional :mod:`bsddb`
20module offers the ability to create in-memory or file based ordered
21dictionaries with string keys using the :meth:`bsddb.btopen` method.
Georg Brandl116aa622007-08-15 14:28:22 +000022
Mark Summerfield08898b42007-09-05 08:43:04 +000023In addition to containers, the collections module provides some ABCs
Raymond Hettingerebcee3f2008-02-06 19:54:00 +000024(abstract base classes) that can be used to test whether a class
25provides a particular interface, for example, is it hashable or
26a mapping.
27
28ABCs - abstract base classes
29----------------------------
30
31The collections module offers the following ABCs:
Mark Summerfield08898b42007-09-05 08:43:04 +000032
Raymond Hettinger409fb2c2008-02-09 02:17:06 +000033========================= ==================== ====================== ====================================================
34ABC Inherits Abstract Methods Mixin Methods
35========================= ==================== ====================== ====================================================
36:class:`Container` ``__contains__``
37:class:`Hashable` ``__hash__``
38:class:`Iterable` ``__iter__``
39:class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__``
40:class:`Sized` ``__len__``
41
42:class:`Mapping` :class:`Sized`, ``__getitem__``, ``__contains__``, ``keys``, ``items``, ``values``,
43 :class:`Iterable`, ``__len__``. and ``get``, ``__eq__``, and ``__ne__``
44 :class:`Container` ``__iter__``
45
46:class:`MutableMapping` :class:`Mapping` ``__getitem__`` Inherited Mapping methods and
47 ``__setitem__``, ``pop``, ``popitem``, ``clear``, ``update``,
48 ``__delitem__``, and ``setdefault``
49 ``__iter__``, and
50 ``__len__``
51
52:class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``. ``__iter__``, ``__reversed__``.
53 :class:`Iterable`, and ``__len__`` ``index``, and ``count``
54 :class:`Container`
55
56:class:`MutableSequnce` :class:`Sequence` ``__getitem__`` Inherited Sequence methods and
57 ``__delitem__``, ``append``, ``reverse``, ``extend``, ``pop``,
58 ``insert``, ``remove``, and ``__iadd__``
59 and ``__len__``
60
Raymond Hettinger7aebb642008-02-09 03:25:08 +000061:class:`Set` \(1) \(2) :class:`Sized`, ``__len__``, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
Raymond Hettinger409fb2c2008-02-09 02:17:06 +000062 :class:`Iterable`, ``__iter__``, and ``__gt__``, ``__ge__``, ``__and__``, ``__or__``
63 :class:`Container` ``__contains__`` ``__sub__``, ``__xor__``, and ``isdisjoint``
64
65:class:`MutableSet` :class:`Set` ``add`` and Inherited Set methods and
66 ``discard`` ``clear``, ``pop``, ``remove``, ``__ior__``,
67 ``__iand__``, ``__ixor__``, and ``__isub__``
68========================= ==================== ====================== ====================================================
Mark Summerfield08898b42007-09-05 08:43:04 +000069
Mark Summerfield08898b42007-09-05 08:43:04 +000070These ABCs allow us to ask classes or instances if they provide
71particular functionality, for example::
72
Mark Summerfield08898b42007-09-05 08:43:04 +000073 size = None
Raymond Hettingerebcee3f2008-02-06 19:54:00 +000074 if isinstance(myvar, collections.Sized):
Mark Summerfield08898b42007-09-05 08:43:04 +000075 size = len(myvar)
76
Raymond Hettingerebcee3f2008-02-06 19:54:00 +000077Several of the ABCs are also useful as mixins that make it easier to develop
78classes supporting container APIs. For example, to write a class supporting
79the full :class:`Set` API, it only necessary to supply the three underlying
80abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`.
81The ABC supplies the remaining methods such as :meth:`__and__` and
82:meth:`isdisjoint` ::
83
84 class ListBasedSet(collections.Set):
Raymond Hettingerc1b6a4a2008-02-08 23:46:23 +000085 ''' Alternate set implementation favoring space over speed
86 and not requiring the set elements to be hashable. '''
Raymond Hettingerebcee3f2008-02-06 19:54:00 +000087 def __init__(self, iterable):
Raymond Hettingerc1b6a4a2008-02-08 23:46:23 +000088 self.elements = lst = []
89 for value in iterable:
90 if value not in lst:
91 lst.append(value)
Raymond Hettingerebcee3f2008-02-06 19:54:00 +000092 def __iter__(self):
93 return iter(self.elements)
94 def __contains__(self, value):
95 return value in self.elements
96 def __len__(self):
97 return len(self.elements)
98
99 s1 = ListBasedSet('abcdef')
100 s2 = ListBasedSet('defghi')
101 overlap = s1 & s2 # The __and__() method is supported automatically
102
Raymond Hettinger7aebb642008-02-09 03:25:08 +0000103Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
104
105(1)
106 Since some set operations create new sets, the default mixin methods need
107 a way to create new instances from an iterable. The class constructor is
108 assumed to have a signature in the form ``ClassName(iterable)``.
109 That assumption is factored-out to a singleinternal classmethod called
110 :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
111 If the :class:`Set` mixin is being used in a class with a different
112 constructor signature, you will need to override :meth:`from_iterable`
113 with a classmethod that can construct new instances from
114 an iterable argument.
115
116(2)
117 To override the comparisons (presumably for speed, as the
118 semantics are fixed), redefine :meth:`__le__` and
119 then the other operations will automatically follow suit.
Raymond Hettingerebcee3f2008-02-06 19:54:00 +0000120
Mark Summerfield08898b42007-09-05 08:43:04 +0000121(For more about ABCs, see the :mod:`abc` module and :pep:`3119`.)
122
123
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125.. _deque-objects:
126
127:class:`deque` objects
128----------------------
129
130
Georg Brandl9afde1c2007-11-01 20:32:30 +0000131.. class:: deque([iterable[, maxlen]])
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133 Returns a new deque object initialized left-to-right (using :meth:`append`) with
134 data from *iterable*. If *iterable* is not specified, the new deque is empty.
135
136 Deques are a generalization of stacks and queues (the name is pronounced "deck"
137 and is short for "double-ended queue"). Deques support thread-safe, memory
138 efficient appends and pops from either side of the deque with approximately the
139 same O(1) performance in either direction.
140
141 Though :class:`list` objects support similar operations, they are optimized for
142 fast fixed-length operations and incur O(n) memory movement costs for
143 ``pop(0)`` and ``insert(0, v)`` operations which change both the size and
144 position of the underlying data representation.
145
Georg Brandl116aa622007-08-15 14:28:22 +0000146
Georg Brandl9afde1c2007-11-01 20:32:30 +0000147 If *maxlen* is not specified or is *None*, deques may grow to an
148 arbitrary length. Otherwise, the deque is bounded to the specified maximum
149 length. Once a bounded length deque is full, when new items are added, a
150 corresponding number of items are discarded from the opposite end. Bounded
151 length deques provide functionality similar to the ``tail`` filter in
152 Unix. They are also useful for tracking transactions and other pools of data
153 where only the most recent activity is of interest.
154
Georg Brandl9afde1c2007-11-01 20:32:30 +0000155
Georg Brandl116aa622007-08-15 14:28:22 +0000156Deque objects support the following methods:
157
Georg Brandl116aa622007-08-15 14:28:22 +0000158.. method:: deque.append(x)
159
160 Add *x* to the right side of the deque.
161
162
163.. method:: deque.appendleft(x)
164
165 Add *x* to the left side of the deque.
166
167
168.. method:: deque.clear()
169
170 Remove all elements from the deque leaving it with length 0.
171
172
173.. method:: deque.extend(iterable)
174
175 Extend the right side of the deque by appending elements from the iterable
176 argument.
177
178
179.. method:: deque.extendleft(iterable)
180
181 Extend the left side of the deque by appending elements from *iterable*. Note,
182 the series of left appends results in reversing the order of elements in the
183 iterable argument.
184
185
186.. method:: deque.pop()
187
188 Remove and return an element from the right side of the deque. If no elements
189 are present, raises an :exc:`IndexError`.
190
191
192.. method:: deque.popleft()
193
194 Remove and return an element from the left side of the deque. If no elements are
195 present, raises an :exc:`IndexError`.
196
197
198.. method:: deque.remove(value)
199
200 Removed the first occurrence of *value*. If not found, raises a
201 :exc:`ValueError`.
202
Georg Brandl116aa622007-08-15 14:28:22 +0000203
204.. method:: deque.rotate(n)
205
206 Rotate the deque *n* steps to the right. If *n* is negative, rotate to the
207 left. Rotating one step to the right is equivalent to:
208 ``d.appendleft(d.pop())``.
209
210In addition to the above, deques support iteration, pickling, ``len(d)``,
211``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with
212the :keyword:`in` operator, and subscript references such as ``d[-1]``.
213
214Example::
215
216 >>> from collections import deque
217 >>> d = deque('ghi') # make a new deque with three items
218 >>> for elem in d: # iterate over the deque's elements
Georg Brandl6911e3c2007-09-04 07:15:32 +0000219 ... print(elem.upper())
Georg Brandl116aa622007-08-15 14:28:22 +0000220 G
221 H
222 I
223
224 >>> d.append('j') # add a new entry to the right side
225 >>> d.appendleft('f') # add a new entry to the left side
226 >>> d # show the representation of the deque
227 deque(['f', 'g', 'h', 'i', 'j'])
228
229 >>> d.pop() # return and remove the rightmost item
230 'j'
231 >>> d.popleft() # return and remove the leftmost item
232 'f'
233 >>> list(d) # list the contents of the deque
234 ['g', 'h', 'i']
235 >>> d[0] # peek at leftmost item
236 'g'
237 >>> d[-1] # peek at rightmost item
238 'i'
239
240 >>> list(reversed(d)) # list the contents of a deque in reverse
241 ['i', 'h', 'g']
242 >>> 'h' in d # search the deque
243 True
244 >>> d.extend('jkl') # add multiple elements at once
245 >>> d
246 deque(['g', 'h', 'i', 'j', 'k', 'l'])
247 >>> d.rotate(1) # right rotation
248 >>> d
249 deque(['l', 'g', 'h', 'i', 'j', 'k'])
250 >>> d.rotate(-1) # left rotation
251 >>> d
252 deque(['g', 'h', 'i', 'j', 'k', 'l'])
253
254 >>> deque(reversed(d)) # make a new deque in reverse order
255 deque(['l', 'k', 'j', 'i', 'h', 'g'])
256 >>> d.clear() # empty the deque
257 >>> d.pop() # cannot pop from an empty deque
258 Traceback (most recent call last):
259 File "<pyshell#6>", line 1, in -toplevel-
260 d.pop()
261 IndexError: pop from an empty deque
262
263 >>> d.extendleft('abc') # extendleft() reverses the input order
264 >>> d
265 deque(['c', 'b', 'a'])
266
267
268.. _deque-recipes:
269
Georg Brandl9afde1c2007-11-01 20:32:30 +0000270:class:`deque` Recipes
271^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000272
273This section shows various approaches to working with deques.
274
275The :meth:`rotate` method provides a way to implement :class:`deque` slicing and
276deletion. For example, a pure python implementation of ``del d[n]`` relies on
277the :meth:`rotate` method to position elements to be popped::
278
279 def delete_nth(d, n):
280 d.rotate(-n)
281 d.popleft()
282 d.rotate(n)
283
284To implement :class:`deque` slicing, use a similar approach applying
285:meth:`rotate` to bring a target element to the left side of the deque. Remove
286old entries with :meth:`popleft`, add new entries with :meth:`extend`, and then
287reverse the rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000288With minor variations on that approach, it is easy to implement Forth style
289stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``,
290``rot``, and ``roll``.
291
Georg Brandl116aa622007-08-15 14:28:22 +0000292Multi-pass data reduction algorithms can be succinctly expressed and efficiently
293coded by extracting elements with multiple calls to :meth:`popleft`, applying
Georg Brandl9afde1c2007-11-01 20:32:30 +0000294a reduction function, and calling :meth:`append` to add the result back to the
295deque.
Georg Brandl116aa622007-08-15 14:28:22 +0000296
297For example, building a balanced binary tree of nested lists entails reducing
298two adjacent nodes into one by grouping them in a list::
299
300 >>> def maketree(iterable):
301 ... d = deque(iterable)
302 ... while len(d) > 1:
303 ... pair = [d.popleft(), d.popleft()]
304 ... d.append(pair)
305 ... return list(d)
306 ...
Georg Brandl6911e3c2007-09-04 07:15:32 +0000307 >>> print(maketree('abcdefgh'))
Georg Brandl116aa622007-08-15 14:28:22 +0000308 [[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
309
Georg Brandl9afde1c2007-11-01 20:32:30 +0000310Bounded length deques provide functionality similar to the ``tail`` filter
311in Unix::
Georg Brandl116aa622007-08-15 14:28:22 +0000312
Georg Brandl9afde1c2007-11-01 20:32:30 +0000313 def tail(filename, n=10):
314 'Return the last n lines of a file'
315 return deque(open(filename), n)
Georg Brandl116aa622007-08-15 14:28:22 +0000316
317.. _defaultdict-objects:
318
319:class:`defaultdict` objects
320----------------------------
321
322
323.. class:: defaultdict([default_factory[, ...]])
324
325 Returns a new dictionary-like object. :class:`defaultdict` is a subclass of the
326 builtin :class:`dict` class. It overrides one method and adds one writable
327 instance variable. The remaining functionality is the same as for the
328 :class:`dict` class and is not documented here.
329
330 The first argument provides the initial value for the :attr:`default_factory`
331 attribute; it defaults to ``None``. All remaining arguments are treated the same
332 as if they were passed to the :class:`dict` constructor, including keyword
333 arguments.
334
Georg Brandl116aa622007-08-15 14:28:22 +0000335
336:class:`defaultdict` objects support the following method in addition to the
337standard :class:`dict` operations:
338
Georg Brandl116aa622007-08-15 14:28:22 +0000339.. method:: defaultdict.__missing__(key)
340
341 If the :attr:`default_factory` attribute is ``None``, this raises an
342 :exc:`KeyError` exception with the *key* as argument.
343
344 If :attr:`default_factory` is not ``None``, it is called without arguments to
345 provide a default value for the given *key*, this value is inserted in the
346 dictionary for the *key*, and returned.
347
348 If calling :attr:`default_factory` raises an exception this exception is
349 propagated unchanged.
350
351 This method is called by the :meth:`__getitem__` method of the :class:`dict`
352 class when the requested key is not found; whatever it returns or raises is then
353 returned or raised by :meth:`__getitem__`.
354
355:class:`defaultdict` objects support the following instance variable:
356
357
358.. attribute:: defaultdict.default_factory
359
360 This attribute is used by the :meth:`__missing__` method; it is initialized from
361 the first argument to the constructor, if present, or to ``None``, if absent.
362
363
364.. _defaultdict-examples:
365
366:class:`defaultdict` Examples
367^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
368
369Using :class:`list` as the :attr:`default_factory`, it is easy to group a
370sequence of key-value pairs into a dictionary of lists::
371
372 >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
373 >>> d = defaultdict(list)
374 >>> for k, v in s:
375 ... d[k].append(v)
376 ...
377 >>> d.items()
378 [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
379
380When each key is encountered for the first time, it is not already in the
381mapping; so an entry is automatically created using the :attr:`default_factory`
382function which returns an empty :class:`list`. The :meth:`list.append`
383operation then attaches the value to the new list. When keys are encountered
384again, the look-up proceeds normally (returning the list for that key) and the
385:meth:`list.append` operation adds another value to the list. This technique is
386simpler and faster than an equivalent technique using :meth:`dict.setdefault`::
387
388 >>> d = {}
389 >>> for k, v in s:
390 ... d.setdefault(k, []).append(v)
391 ...
392 >>> d.items()
393 [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
394
395Setting the :attr:`default_factory` to :class:`int` makes the
396:class:`defaultdict` useful for counting (like a bag or multiset in other
397languages)::
398
399 >>> s = 'mississippi'
400 >>> d = defaultdict(int)
401 >>> for k in s:
402 ... d[k] += 1
403 ...
404 >>> d.items()
405 [('i', 4), ('p', 2), ('s', 4), ('m', 1)]
406
407When a letter is first encountered, it is missing from the mapping, so the
408:attr:`default_factory` function calls :func:`int` to supply a default count of
409zero. The increment operation then builds up the count for each letter.
410
411The function :func:`int` which always returns zero is just a special case of
412constant functions. A faster and more flexible way to create constant functions
413is to use a lambda function which can supply any constant value (not just
414zero)::
415
416 >>> def constant_factory(value):
417 ... return lambda: value
418 >>> d = defaultdict(constant_factory('<missing>'))
419 >>> d.update(name='John', action='ran')
420 >>> '%(name)s %(action)s to %(object)s' % d
421 'John ran to <missing>'
422
423Setting the :attr:`default_factory` to :class:`set` makes the
424:class:`defaultdict` useful for building a dictionary of sets::
425
426 >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
427 >>> d = defaultdict(set)
428 >>> for k, v in s:
429 ... d[k].add(v)
430 ...
431 >>> d.items()
432 [('blue', set([2, 4])), ('red', set([1, 3]))]
433
434
435.. _named-tuple-factory:
436
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000437:func:`namedtuple` Factory Function for Tuples with Named Fields
Christian Heimes790c8232008-01-07 21:14:23 +0000438----------------------------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000439
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000440Named tuples assign meaning to each position in a tuple and allow for more readable,
441self-documenting code. They can be used wherever regular tuples are used, and
442they add the ability to access fields by name instead of position index.
Georg Brandl116aa622007-08-15 14:28:22 +0000443
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000444.. function:: namedtuple(typename, fieldnames, [verbose])
Georg Brandl116aa622007-08-15 14:28:22 +0000445
446 Returns a new tuple subclass named *typename*. The new subclass is used to
447 create tuple-like objects that have fields accessable by attribute lookup as
448 well as being indexable and iterable. Instances of the subclass also have a
449 helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__`
450 method which lists the tuple contents in a ``name=value`` format.
451
Georg Brandl9afde1c2007-11-01 20:32:30 +0000452 The *fieldnames* are a single string with each fieldname separated by whitespace
Christian Heimes25bb7832008-01-11 16:17:00 +0000453 and/or commas, for example ``'x y'`` or ``'x, y'``. Alternatively, *fieldnames*
454 can be a sequence of strings such as ``['x', 'y']``.
Georg Brandl9afde1c2007-11-01 20:32:30 +0000455
456 Any valid Python identifier may be used for a fieldname except for names
Christian Heimes0449f632007-12-15 01:27:15 +0000457 starting with an underscore. Valid identifiers consist of letters, digits,
458 and underscores but do not start with a digit or underscore and cannot be
Georg Brandlf6945182008-02-01 11:56:49 +0000459 a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*,
Georg Brandl9afde1c2007-11-01 20:32:30 +0000460 or *raise*.
Georg Brandl116aa622007-08-15 14:28:22 +0000461
Christian Heimes25bb7832008-01-11 16:17:00 +0000462 If *verbose* is true, the class definition is printed just before being built.
Georg Brandl116aa622007-08-15 14:28:22 +0000463
Georg Brandl9afde1c2007-11-01 20:32:30 +0000464 Named tuple instances do not have per-instance dictionaries, so they are
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000465 lightweight and require no more memory than regular tuples.
Georg Brandl116aa622007-08-15 14:28:22 +0000466
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000467Example::
Georg Brandl116aa622007-08-15 14:28:22 +0000468
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000469 >>> Point = namedtuple('Point', 'x y', verbose=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000470 class Point(tuple):
471 'Point(x, y)'
Christian Heimes0449f632007-12-15 01:27:15 +0000472
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000473 __slots__ = ()
Christian Heimes0449f632007-12-15 01:27:15 +0000474
Christian Heimesfaf2f632008-01-06 16:59:19 +0000475 _fields = ('x', 'y')
476
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000477 def __new__(cls, x, y):
478 return tuple.__new__(cls, (x, y))
Christian Heimes0449f632007-12-15 01:27:15 +0000479
Christian Heimesfaf2f632008-01-06 16:59:19 +0000480 @classmethod
481 def _make(cls, iterable):
482 'Make a new Point object from a sequence or iterable'
483 result = tuple.__new__(cls, iterable)
484 if len(result) != 2:
485 raise TypeError('Expected 2 arguments, got %d' % len(result))
486 return result
Christian Heimes99170a52007-12-19 02:07:34 +0000487
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000488 def __repr__(self):
489 return 'Point(x=%r, y=%r)' % self
Christian Heimes0449f632007-12-15 01:27:15 +0000490
Christian Heimes99170a52007-12-19 02:07:34 +0000491 def _asdict(t):
Christian Heimes0449f632007-12-15 01:27:15 +0000492 'Return a new dict which maps field names to their values'
Christian Heimes99170a52007-12-19 02:07:34 +0000493 return {'x': t[0], 'y': t[1]}
Christian Heimes0449f632007-12-15 01:27:15 +0000494
495 def _replace(self, **kwds):
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000496 'Return a new Point object replacing specified fields with new values'
Christian Heimesfaf2f632008-01-06 16:59:19 +0000497 result = self._make(map(kwds.pop, ('x', 'y'), self))
498 if kwds:
499 raise ValueError('Got unexpected field names: %r' % kwds.keys())
500 return result
Christian Heimes0449f632007-12-15 01:27:15 +0000501
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000502 x = property(itemgetter(0))
503 y = property(itemgetter(1))
Georg Brandl116aa622007-08-15 14:28:22 +0000504
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000505 >>> p = Point(11, y=22) # instantiate with positional or keyword arguments
Christian Heimes99170a52007-12-19 02:07:34 +0000506 >>> p[0] + p[1] # indexable like the plain tuple (11, 22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000507 33
508 >>> x, y = p # unpack like a regular tuple
509 >>> x, y
510 (11, 22)
511 >>> p.x + p.y # fields also accessable by name
512 33
513 >>> p # readable __repr__ with a name=value style
514 Point(x=11, y=22)
Georg Brandl116aa622007-08-15 14:28:22 +0000515
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000516Named tuples are especially useful for assigning field names to result tuples returned
517by the :mod:`csv` or :mod:`sqlite3` modules::
518
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000519 EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
Georg Brandl9afde1c2007-11-01 20:32:30 +0000520
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000521 import csv
Christian Heimesfaf2f632008-01-06 16:59:19 +0000522 for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000523 print(emp.name, emp.title)
524
Georg Brandl9afde1c2007-11-01 20:32:30 +0000525 import sqlite3
526 conn = sqlite3.connect('/companydata')
527 cursor = conn.cursor()
528 cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
Christian Heimesfaf2f632008-01-06 16:59:19 +0000529 for emp in map(EmployeeRecord._make, cursor.fetchall()):
Christian Heimes00412232008-01-10 16:02:19 +0000530 print(emp.name, emp.title)
Georg Brandl9afde1c2007-11-01 20:32:30 +0000531
Christian Heimes99170a52007-12-19 02:07:34 +0000532In addition to the methods inherited from tuples, named tuples support
Christian Heimes2380ac72008-01-09 00:17:24 +0000533three additional methods and one attribute. To prevent conflicts with
534field names, the method and attribute names start with an underscore.
Christian Heimes99170a52007-12-19 02:07:34 +0000535
Christian Heimes790c8232008-01-07 21:14:23 +0000536.. method:: somenamedtuple._make(iterable)
Christian Heimes99170a52007-12-19 02:07:34 +0000537
Christian Heimesfaf2f632008-01-06 16:59:19 +0000538 Class method that makes a new instance from an existing sequence or iterable.
Christian Heimes99170a52007-12-19 02:07:34 +0000539
540::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000541
Christian Heimesfaf2f632008-01-06 16:59:19 +0000542 >>> t = [11, 22]
543 >>> Point._make(t)
544 Point(x=11, y=22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000545
Christian Heimes790c8232008-01-07 21:14:23 +0000546.. method:: somenamedtuple._asdict()
Georg Brandl9afde1c2007-11-01 20:32:30 +0000547
548 Return a new dict which maps field names to their corresponding values:
549
550::
551
Christian Heimes0449f632007-12-15 01:27:15 +0000552 >>> p._asdict()
Georg Brandl9afde1c2007-11-01 20:32:30 +0000553 {'x': 11, 'y': 22}
554
Christian Heimes790c8232008-01-07 21:14:23 +0000555.. method:: somenamedtuple._replace(kwargs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000556
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000557 Return a new instance of the named tuple replacing specified fields with new values:
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000558
559::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000560
561 >>> p = Point(x=11, y=22)
Christian Heimes0449f632007-12-15 01:27:15 +0000562 >>> p._replace(x=33)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563 Point(x=33, y=22)
564
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000565 >>> for partnum, record in inventory.items():
Christian Heimes454f37b2008-01-10 00:10:02 +0000566 ... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000567
Christian Heimes790c8232008-01-07 21:14:23 +0000568.. attribute:: somenamedtuple._fields
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000569
Christian Heimes2380ac72008-01-09 00:17:24 +0000570 Tuple of strings listing the field names. Useful for introspection
Georg Brandl9afde1c2007-11-01 20:32:30 +0000571 and for creating new named tuple types from existing named tuples.
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000572
573::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000574
Christian Heimes0449f632007-12-15 01:27:15 +0000575 >>> p._fields # view the field names
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000576 ('x', 'y')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000577
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000578 >>> Color = namedtuple('Color', 'red green blue')
Christian Heimes0449f632007-12-15 01:27:15 +0000579 >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000580 >>> Pixel(11, 22, 128, 255, 0)
Christian Heimes454f37b2008-01-10 00:10:02 +0000581 Pixel(x=11, y=22, red=128, green=255, blue=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000582
Christian Heimes0449f632007-12-15 01:27:15 +0000583To retrieve a field whose name is stored in a string, use the :func:`getattr`
Christian Heimes790c8232008-01-07 21:14:23 +0000584function::
Christian Heimes0449f632007-12-15 01:27:15 +0000585
586 >>> getattr(p, 'x')
587 11
588
Christian Heimes25bb7832008-01-11 16:17:00 +0000589To convert a dictionary to a named tuple, use the double-star-operator [#]_::
Christian Heimes99170a52007-12-19 02:07:34 +0000590
591 >>> d = {'x': 11, 'y': 22}
592 >>> Point(**d)
593 Point(x=11, y=22)
594
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000595Since a named tuple is a regular Python class, it is easy to add or change
Christian Heimes043d6f62008-01-07 17:19:16 +0000596functionality with a subclass. Here is how to add a calculated field and
597a fixed-width print format::
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000598
Christian Heimes043d6f62008-01-07 17:19:16 +0000599 >>> class Point(namedtuple('Point', 'x y')):
Christian Heimes25bb7832008-01-11 16:17:00 +0000600 ... __slots__ = ()
Christian Heimes454f37b2008-01-10 00:10:02 +0000601 ... @property
602 ... def hypot(self):
603 ... return (self.x ** 2 + self.y ** 2) ** 0.5
604 ... def __str__(self):
Christian Heimes25bb7832008-01-11 16:17:00 +0000605 ... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000606
Christian Heimes25bb7832008-01-11 16:17:00 +0000607 >>> for p in Point(3, 4), Point(14, 5/7.):
Christian Heimes00412232008-01-10 16:02:19 +0000608 ... print(p)
Christian Heimes790c8232008-01-07 21:14:23 +0000609
Christian Heimes25bb7832008-01-11 16:17:00 +0000610 Point: x= 3.000 y= 4.000 hypot= 5.000
611 Point: x=14.000 y= 0.714 hypot=14.018
Christian Heimes043d6f62008-01-07 17:19:16 +0000612
Christian Heimesaf98da12008-01-27 15:18:18 +0000613The subclass shown above sets ``__slots__`` to an empty tuple. This keeps
Christian Heimes679db4a2008-01-18 09:56:22 +0000614keep memory requirements low by preventing the creation of instance dictionaries.
615
Christian Heimes2380ac72008-01-09 00:17:24 +0000616
617Subclassing is not useful for adding new, stored fields. Instead, simply
618create a new named tuple type from the :attr:`_fields` attribute::
619
Christian Heimes25bb7832008-01-11 16:17:00 +0000620 >>> Point3D = namedtuple('Point3D', Point._fields + ('z',))
Christian Heimes2380ac72008-01-09 00:17:24 +0000621
622Default values can be implemented by using :meth:`_replace` to
Christian Heimes790c8232008-01-07 21:14:23 +0000623customize a prototype instance::
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000624
625 >>> Account = namedtuple('Account', 'owner balance transaction_count')
Christian Heimes587c2bf2008-01-19 16:21:02 +0000626 >>> default_account = Account('<owner name>', 0.0, 0)
627 >>> johns_account = default_account._replace(owner='John')
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000628
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000629.. rubric:: Footnotes
630
Christian Heimes99170a52007-12-19 02:07:34 +0000631.. [#] For information on the double-star-operator see
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000632 :ref:`tut-unpacking-arguments` and :ref:`calls`.
Raymond Hettingere4c96ad2008-02-06 01:23:58 +0000633
634
635
636:class:`UserDict` objects
Mark Summerfield8f2d0062008-02-06 13:30:44 +0000637-------------------------
Raymond Hettingere4c96ad2008-02-06 01:23:58 +0000638
639The class, :class:`UserDict` acts as a wrapper around dictionary objects.
640The need for this class has been partially supplanted by the ability to
641subclass directly from :class:`dict`; however, this class can be easier
642to work with because the underlying dictionary is accessible as an
643attribute.
644
645.. class:: UserDict([initialdata])
646
647 Class that simulates a dictionary. The instance's contents are kept in a
648 regular dictionary, which is accessible via the :attr:`data` attribute of
649 :class:`UserDict` instances. If *initialdata* is provided, :attr:`data` is
650 initialized with its contents; note that a reference to *initialdata* will not
651 be kept, allowing it be used for other purposes.
652
653In addition to supporting the methods and operations of mappings,
Raymond Hettingerebcee3f2008-02-06 19:54:00 +0000654:class:`UserDict` instances provide the following attribute:
Raymond Hettingere4c96ad2008-02-06 01:23:58 +0000655
656.. attribute:: UserDict.data
657
658 A real dictionary used to store the contents of the :class:`UserDict` class.