blob: e18dfcfc34488127a91be85811302c8e61e13b70 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
Raymond Hettinger53dbe392008-02-12 20:03:09 +00002:mod:`collections` --- Container datatypes
3==========================================
Georg Brandl116aa622007-08-15 14:28:22 +00004
5.. module:: collections
Raymond Hettinger53dbe392008-02-12 20:03:09 +00006 :synopsis: Container datatypes
Georg Brandl116aa622007-08-15 14:28:22 +00007.. 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
Christian Heimes0bd4e112008-02-12 22:59:25 +000015Besides the containers provided here, the optional :mod:`bsddb`
16module offers the ability to create in-memory or file based ordered
17dictionaries with string keys using the :meth:`bsddb.btopen` method.
18
19In addition to containers, the collections module provides some ABCs
20(abstract base classes) that can be used to test whether a class
21provides a particular interface, for example, is it hashable or
22a mapping.
23
Raymond Hettingerebcee3f2008-02-06 19:54:00 +000024The specialized containers provided in this module provide alternatives
25to Python's general purpose built-in containers, :class:`dict`,
26:class:`list`, :class:`set`, and :class:`tuple`.
Raymond Hettingerebcee3f2008-02-06 19:54:00 +000027Besides the containers provided here, the optional :mod:`bsddb`
28module offers the ability to create in-memory or file based ordered
29dictionaries with string keys using the :meth:`bsddb.btopen` method.
Georg Brandl116aa622007-08-15 14:28:22 +000030
Mark Summerfield08898b42007-09-05 08:43:04 +000031In addition to containers, the collections module provides some ABCs
Raymond Hettingerebcee3f2008-02-06 19:54:00 +000032(abstract base classes) that can be used to test whether a class
33provides a particular interface, for example, is it hashable or
34a mapping.
35
36ABCs - abstract base classes
37----------------------------
38
39The collections module offers the following ABCs:
Mark Summerfield08898b42007-09-05 08:43:04 +000040
Raymond Hettinger409fb2c2008-02-09 02:17:06 +000041========================= ==================== ====================== ====================================================
42ABC Inherits Abstract Methods Mixin Methods
43========================= ==================== ====================== ====================================================
44:class:`Container` ``__contains__``
45:class:`Hashable` ``__hash__``
46:class:`Iterable` ``__iter__``
47:class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__``
48:class:`Sized` ``__len__``
49
50:class:`Mapping` :class:`Sized`, ``__getitem__``, ``__contains__``, ``keys``, ``items``, ``values``,
51 :class:`Iterable`, ``__len__``. and ``get``, ``__eq__``, and ``__ne__``
52 :class:`Container` ``__iter__``
53
54:class:`MutableMapping` :class:`Mapping` ``__getitem__`` Inherited Mapping methods and
55 ``__setitem__``, ``pop``, ``popitem``, ``clear``, ``update``,
56 ``__delitem__``, and ``setdefault``
57 ``__iter__``, and
58 ``__len__``
59
60:class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``. ``__iter__``, ``__reversed__``.
61 :class:`Iterable`, and ``__len__`` ``index``, and ``count``
62 :class:`Container`
63
64:class:`MutableSequnce` :class:`Sequence` ``__getitem__`` Inherited Sequence methods and
65 ``__delitem__``, ``append``, ``reverse``, ``extend``, ``pop``,
66 ``insert``, ``remove``, and ``__iadd__``
67 and ``__len__``
68
Raymond Hettinger0dbdab22008-02-09 03:48:16 +000069:class:`Set` :class:`Sized`, ``__len__``, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
Raymond Hettinger409fb2c2008-02-09 02:17:06 +000070 :class:`Iterable`, ``__iter__``, and ``__gt__``, ``__ge__``, ``__and__``, ``__or__``
71 :class:`Container` ``__contains__`` ``__sub__``, ``__xor__``, and ``isdisjoint``
72
73:class:`MutableSet` :class:`Set` ``add`` and Inherited Set methods and
74 ``discard`` ``clear``, ``pop``, ``remove``, ``__ior__``,
75 ``__iand__``, ``__ixor__``, and ``__isub__``
76========================= ==================== ====================== ====================================================
Mark Summerfield08898b42007-09-05 08:43:04 +000077
Mark Summerfield08898b42007-09-05 08:43:04 +000078These ABCs allow us to ask classes or instances if they provide
79particular functionality, for example::
80
Mark Summerfield08898b42007-09-05 08:43:04 +000081 size = None
Raymond Hettingerebcee3f2008-02-06 19:54:00 +000082 if isinstance(myvar, collections.Sized):
Mark Summerfield08898b42007-09-05 08:43:04 +000083 size = len(myvar)
84
Raymond Hettingerebcee3f2008-02-06 19:54:00 +000085Several of the ABCs are also useful as mixins that make it easier to develop
86classes supporting container APIs. For example, to write a class supporting
87the full :class:`Set` API, it only necessary to supply the three underlying
88abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`.
89The ABC supplies the remaining methods such as :meth:`__and__` and
90:meth:`isdisjoint` ::
91
92 class ListBasedSet(collections.Set):
Raymond Hettingerc1b6a4a2008-02-08 23:46:23 +000093 ''' Alternate set implementation favoring space over speed
94 and not requiring the set elements to be hashable. '''
Raymond Hettingerebcee3f2008-02-06 19:54:00 +000095 def __init__(self, iterable):
Raymond Hettingerc1b6a4a2008-02-08 23:46:23 +000096 self.elements = lst = []
97 for value in iterable:
98 if value not in lst:
99 lst.append(value)
Raymond Hettingerebcee3f2008-02-06 19:54:00 +0000100 def __iter__(self):
101 return iter(self.elements)
102 def __contains__(self, value):
103 return value in self.elements
104 def __len__(self):
105 return len(self.elements)
106
107 s1 = ListBasedSet('abcdef')
108 s2 = ListBasedSet('defghi')
109 overlap = s1 & s2 # The __and__() method is supported automatically
110
Raymond Hettinger7aebb642008-02-09 03:25:08 +0000111Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
112
113(1)
114 Since some set operations create new sets, the default mixin methods need
115 a way to create new instances from an iterable. The class constructor is
116 assumed to have a signature in the form ``ClassName(iterable)``.
117 That assumption is factored-out to a singleinternal classmethod called
118 :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
119 If the :class:`Set` mixin is being used in a class with a different
120 constructor signature, you will need to override :meth:`from_iterable`
121 with a classmethod that can construct new instances from
122 an iterable argument.
123
124(2)
125 To override the comparisons (presumably for speed, as the
126 semantics are fixed), redefine :meth:`__le__` and
127 then the other operations will automatically follow suit.
Raymond Hettingerebcee3f2008-02-06 19:54:00 +0000128
Raymond Hettinger0dbdab22008-02-09 03:48:16 +0000129(3)
130 The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value
131 for the set; however, :meth:`__hash__` is not defined because not all sets
132 are hashable or immutable. To add set hashabilty using mixins,
133 inherit from both :meth:`Set` and :meth:`Hashable`, then define
134 ``__hash__ = Set._hash``.
135
Mark Summerfield08898b42007-09-05 08:43:04 +0000136(For more about ABCs, see the :mod:`abc` module and :pep:`3119`.)
137
138
Georg Brandl116aa622007-08-15 14:28:22 +0000139.. _deque-objects:
140
141:class:`deque` objects
142----------------------
143
144
Georg Brandl9afde1c2007-11-01 20:32:30 +0000145.. class:: deque([iterable[, maxlen]])
Georg Brandl116aa622007-08-15 14:28:22 +0000146
147 Returns a new deque object initialized left-to-right (using :meth:`append`) with
148 data from *iterable*. If *iterable* is not specified, the new deque is empty.
149
150 Deques are a generalization of stacks and queues (the name is pronounced "deck"
151 and is short for "double-ended queue"). Deques support thread-safe, memory
152 efficient appends and pops from either side of the deque with approximately the
153 same O(1) performance in either direction.
154
155 Though :class:`list` objects support similar operations, they are optimized for
156 fast fixed-length operations and incur O(n) memory movement costs for
157 ``pop(0)`` and ``insert(0, v)`` operations which change both the size and
158 position of the underlying data representation.
159
Georg Brandl116aa622007-08-15 14:28:22 +0000160
Georg Brandl9afde1c2007-11-01 20:32:30 +0000161 If *maxlen* is not specified or is *None*, deques may grow to an
162 arbitrary length. Otherwise, the deque is bounded to the specified maximum
163 length. Once a bounded length deque is full, when new items are added, a
164 corresponding number of items are discarded from the opposite end. Bounded
165 length deques provide functionality similar to the ``tail`` filter in
166 Unix. They are also useful for tracking transactions and other pools of data
167 where only the most recent activity is of interest.
168
Georg Brandl9afde1c2007-11-01 20:32:30 +0000169
Georg Brandl116aa622007-08-15 14:28:22 +0000170Deque objects support the following methods:
171
Georg Brandl116aa622007-08-15 14:28:22 +0000172.. method:: deque.append(x)
173
174 Add *x* to the right side of the deque.
175
176
177.. method:: deque.appendleft(x)
178
179 Add *x* to the left side of the deque.
180
181
182.. method:: deque.clear()
183
184 Remove all elements from the deque leaving it with length 0.
185
186
187.. method:: deque.extend(iterable)
188
189 Extend the right side of the deque by appending elements from the iterable
190 argument.
191
192
193.. method:: deque.extendleft(iterable)
194
195 Extend the left side of the deque by appending elements from *iterable*. Note,
196 the series of left appends results in reversing the order of elements in the
197 iterable argument.
198
199
200.. method:: deque.pop()
201
202 Remove and return an element from the right side of the deque. If no elements
203 are present, raises an :exc:`IndexError`.
204
205
206.. method:: deque.popleft()
207
208 Remove and return an element from the left side of the deque. If no elements are
209 present, raises an :exc:`IndexError`.
210
211
212.. method:: deque.remove(value)
213
214 Removed the first occurrence of *value*. If not found, raises a
215 :exc:`ValueError`.
216
Georg Brandl116aa622007-08-15 14:28:22 +0000217
218.. method:: deque.rotate(n)
219
220 Rotate the deque *n* steps to the right. If *n* is negative, rotate to the
221 left. Rotating one step to the right is equivalent to:
222 ``d.appendleft(d.pop())``.
223
224In addition to the above, deques support iteration, pickling, ``len(d)``,
225``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with
226the :keyword:`in` operator, and subscript references such as ``d[-1]``.
227
228Example::
229
230 >>> from collections import deque
231 >>> d = deque('ghi') # make a new deque with three items
232 >>> for elem in d: # iterate over the deque's elements
Georg Brandl6911e3c2007-09-04 07:15:32 +0000233 ... print(elem.upper())
Georg Brandl116aa622007-08-15 14:28:22 +0000234 G
235 H
236 I
237
238 >>> d.append('j') # add a new entry to the right side
239 >>> d.appendleft('f') # add a new entry to the left side
240 >>> d # show the representation of the deque
241 deque(['f', 'g', 'h', 'i', 'j'])
242
243 >>> d.pop() # return and remove the rightmost item
244 'j'
245 >>> d.popleft() # return and remove the leftmost item
246 'f'
247 >>> list(d) # list the contents of the deque
248 ['g', 'h', 'i']
249 >>> d[0] # peek at leftmost item
250 'g'
251 >>> d[-1] # peek at rightmost item
252 'i'
253
254 >>> list(reversed(d)) # list the contents of a deque in reverse
255 ['i', 'h', 'g']
256 >>> 'h' in d # search the deque
257 True
258 >>> d.extend('jkl') # add multiple elements at once
259 >>> d
260 deque(['g', 'h', 'i', 'j', 'k', 'l'])
261 >>> d.rotate(1) # right rotation
262 >>> d
263 deque(['l', 'g', 'h', 'i', 'j', 'k'])
264 >>> d.rotate(-1) # left rotation
265 >>> d
266 deque(['g', 'h', 'i', 'j', 'k', 'l'])
267
268 >>> deque(reversed(d)) # make a new deque in reverse order
269 deque(['l', 'k', 'j', 'i', 'h', 'g'])
270 >>> d.clear() # empty the deque
271 >>> d.pop() # cannot pop from an empty deque
272 Traceback (most recent call last):
273 File "<pyshell#6>", line 1, in -toplevel-
274 d.pop()
275 IndexError: pop from an empty deque
276
277 >>> d.extendleft('abc') # extendleft() reverses the input order
278 >>> d
279 deque(['c', 'b', 'a'])
280
281
282.. _deque-recipes:
283
Georg Brandl9afde1c2007-11-01 20:32:30 +0000284:class:`deque` Recipes
285^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287This section shows various approaches to working with deques.
288
289The :meth:`rotate` method provides a way to implement :class:`deque` slicing and
290deletion. For example, a pure python implementation of ``del d[n]`` relies on
291the :meth:`rotate` method to position elements to be popped::
292
293 def delete_nth(d, n):
294 d.rotate(-n)
295 d.popleft()
296 d.rotate(n)
297
298To implement :class:`deque` slicing, use a similar approach applying
299:meth:`rotate` to bring a target element to the left side of the deque. Remove
300old entries with :meth:`popleft`, add new entries with :meth:`extend`, and then
301reverse the rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000302With minor variations on that approach, it is easy to implement Forth style
303stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``,
304``rot``, and ``roll``.
305
Georg Brandl116aa622007-08-15 14:28:22 +0000306Multi-pass data reduction algorithms can be succinctly expressed and efficiently
307coded by extracting elements with multiple calls to :meth:`popleft`, applying
Georg Brandl9afde1c2007-11-01 20:32:30 +0000308a reduction function, and calling :meth:`append` to add the result back to the
309deque.
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311For example, building a balanced binary tree of nested lists entails reducing
312two adjacent nodes into one by grouping them in a list::
313
314 >>> def maketree(iterable):
315 ... d = deque(iterable)
316 ... while len(d) > 1:
317 ... pair = [d.popleft(), d.popleft()]
318 ... d.append(pair)
319 ... return list(d)
320 ...
Georg Brandl6911e3c2007-09-04 07:15:32 +0000321 >>> print(maketree('abcdefgh'))
Georg Brandl116aa622007-08-15 14:28:22 +0000322 [[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
323
Georg Brandl9afde1c2007-11-01 20:32:30 +0000324Bounded length deques provide functionality similar to the ``tail`` filter
325in Unix::
Georg Brandl116aa622007-08-15 14:28:22 +0000326
Georg Brandl9afde1c2007-11-01 20:32:30 +0000327 def tail(filename, n=10):
328 'Return the last n lines of a file'
329 return deque(open(filename), n)
Georg Brandl116aa622007-08-15 14:28:22 +0000330
331.. _defaultdict-objects:
332
333:class:`defaultdict` objects
334----------------------------
335
336
337.. class:: defaultdict([default_factory[, ...]])
338
339 Returns a new dictionary-like object. :class:`defaultdict` is a subclass of the
340 builtin :class:`dict` class. It overrides one method and adds one writable
341 instance variable. The remaining functionality is the same as for the
342 :class:`dict` class and is not documented here.
343
344 The first argument provides the initial value for the :attr:`default_factory`
345 attribute; it defaults to ``None``. All remaining arguments are treated the same
346 as if they were passed to the :class:`dict` constructor, including keyword
347 arguments.
348
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350:class:`defaultdict` objects support the following method in addition to the
351standard :class:`dict` operations:
352
Georg Brandl116aa622007-08-15 14:28:22 +0000353.. method:: defaultdict.__missing__(key)
354
355 If the :attr:`default_factory` attribute is ``None``, this raises an
356 :exc:`KeyError` exception with the *key* as argument.
357
358 If :attr:`default_factory` is not ``None``, it is called without arguments to
359 provide a default value for the given *key*, this value is inserted in the
360 dictionary for the *key*, and returned.
361
362 If calling :attr:`default_factory` raises an exception this exception is
363 propagated unchanged.
364
365 This method is called by the :meth:`__getitem__` method of the :class:`dict`
366 class when the requested key is not found; whatever it returns or raises is then
367 returned or raised by :meth:`__getitem__`.
368
369:class:`defaultdict` objects support the following instance variable:
370
371
372.. attribute:: defaultdict.default_factory
373
374 This attribute is used by the :meth:`__missing__` method; it is initialized from
375 the first argument to the constructor, if present, or to ``None``, if absent.
376
377
378.. _defaultdict-examples:
379
380:class:`defaultdict` Examples
381^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
382
383Using :class:`list` as the :attr:`default_factory`, it is easy to group a
384sequence of key-value pairs into a dictionary of lists::
385
386 >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
387 >>> d = defaultdict(list)
388 >>> for k, v in s:
389 ... d[k].append(v)
390 ...
391 >>> d.items()
392 [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
393
394When each key is encountered for the first time, it is not already in the
395mapping; so an entry is automatically created using the :attr:`default_factory`
396function which returns an empty :class:`list`. The :meth:`list.append`
397operation then attaches the value to the new list. When keys are encountered
398again, the look-up proceeds normally (returning the list for that key) and the
399:meth:`list.append` operation adds another value to the list. This technique is
400simpler and faster than an equivalent technique using :meth:`dict.setdefault`::
401
402 >>> d = {}
403 >>> for k, v in s:
404 ... d.setdefault(k, []).append(v)
405 ...
406 >>> d.items()
407 [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
408
409Setting the :attr:`default_factory` to :class:`int` makes the
410:class:`defaultdict` useful for counting (like a bag or multiset in other
411languages)::
412
413 >>> s = 'mississippi'
414 >>> d = defaultdict(int)
415 >>> for k in s:
416 ... d[k] += 1
417 ...
418 >>> d.items()
419 [('i', 4), ('p', 2), ('s', 4), ('m', 1)]
420
421When a letter is first encountered, it is missing from the mapping, so the
422:attr:`default_factory` function calls :func:`int` to supply a default count of
423zero. The increment operation then builds up the count for each letter.
424
425The function :func:`int` which always returns zero is just a special case of
426constant functions. A faster and more flexible way to create constant functions
427is to use a lambda function which can supply any constant value (not just
428zero)::
429
430 >>> def constant_factory(value):
431 ... return lambda: value
432 >>> d = defaultdict(constant_factory('<missing>'))
433 >>> d.update(name='John', action='ran')
434 >>> '%(name)s %(action)s to %(object)s' % d
435 'John ran to <missing>'
436
437Setting the :attr:`default_factory` to :class:`set` makes the
438:class:`defaultdict` useful for building a dictionary of sets::
439
440 >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
441 >>> d = defaultdict(set)
442 >>> for k, v in s:
443 ... d[k].add(v)
444 ...
445 >>> d.items()
446 [('blue', set([2, 4])), ('red', set([1, 3]))]
447
448
449.. _named-tuple-factory:
450
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000451:func:`namedtuple` Factory Function for Tuples with Named Fields
Christian Heimes790c8232008-01-07 21:14:23 +0000452----------------------------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000453
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000454Named tuples assign meaning to each position in a tuple and allow for more readable,
455self-documenting code. They can be used wherever regular tuples are used, and
456they add the ability to access fields by name instead of position index.
Georg Brandl116aa622007-08-15 14:28:22 +0000457
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000458.. function:: namedtuple(typename, fieldnames, [verbose])
Georg Brandl116aa622007-08-15 14:28:22 +0000459
460 Returns a new tuple subclass named *typename*. The new subclass is used to
461 create tuple-like objects that have fields accessable by attribute lookup as
462 well as being indexable and iterable. Instances of the subclass also have a
463 helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__`
464 method which lists the tuple contents in a ``name=value`` format.
465
Georg Brandl9afde1c2007-11-01 20:32:30 +0000466 The *fieldnames* are a single string with each fieldname separated by whitespace
Christian Heimes25bb7832008-01-11 16:17:00 +0000467 and/or commas, for example ``'x y'`` or ``'x, y'``. Alternatively, *fieldnames*
468 can be a sequence of strings such as ``['x', 'y']``.
Georg Brandl9afde1c2007-11-01 20:32:30 +0000469
470 Any valid Python identifier may be used for a fieldname except for names
Christian Heimes0449f632007-12-15 01:27:15 +0000471 starting with an underscore. Valid identifiers consist of letters, digits,
472 and underscores but do not start with a digit or underscore and cannot be
Georg Brandlf6945182008-02-01 11:56:49 +0000473 a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*,
Georg Brandl9afde1c2007-11-01 20:32:30 +0000474 or *raise*.
Georg Brandl116aa622007-08-15 14:28:22 +0000475
Christian Heimes25bb7832008-01-11 16:17:00 +0000476 If *verbose* is true, the class definition is printed just before being built.
Georg Brandl116aa622007-08-15 14:28:22 +0000477
Georg Brandl9afde1c2007-11-01 20:32:30 +0000478 Named tuple instances do not have per-instance dictionaries, so they are
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000479 lightweight and require no more memory than regular tuples.
Georg Brandl116aa622007-08-15 14:28:22 +0000480
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000481Example::
Georg Brandl116aa622007-08-15 14:28:22 +0000482
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000483 >>> Point = namedtuple('Point', 'x y', verbose=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000484 class Point(tuple):
485 'Point(x, y)'
Christian Heimes0449f632007-12-15 01:27:15 +0000486
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000487 __slots__ = ()
Christian Heimes0449f632007-12-15 01:27:15 +0000488
Christian Heimesfaf2f632008-01-06 16:59:19 +0000489 _fields = ('x', 'y')
490
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000491 def __new__(cls, x, y):
492 return tuple.__new__(cls, (x, y))
Christian Heimes0449f632007-12-15 01:27:15 +0000493
Christian Heimesfaf2f632008-01-06 16:59:19 +0000494 @classmethod
495 def _make(cls, iterable):
496 'Make a new Point object from a sequence or iterable'
497 result = tuple.__new__(cls, iterable)
498 if len(result) != 2:
499 raise TypeError('Expected 2 arguments, got %d' % len(result))
500 return result
Christian Heimes99170a52007-12-19 02:07:34 +0000501
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000502 def __repr__(self):
503 return 'Point(x=%r, y=%r)' % self
Christian Heimes0449f632007-12-15 01:27:15 +0000504
Christian Heimes99170a52007-12-19 02:07:34 +0000505 def _asdict(t):
Christian Heimes0449f632007-12-15 01:27:15 +0000506 'Return a new dict which maps field names to their values'
Christian Heimes99170a52007-12-19 02:07:34 +0000507 return {'x': t[0], 'y': t[1]}
Christian Heimes0449f632007-12-15 01:27:15 +0000508
509 def _replace(self, **kwds):
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000510 'Return a new Point object replacing specified fields with new values'
Christian Heimesfaf2f632008-01-06 16:59:19 +0000511 result = self._make(map(kwds.pop, ('x', 'y'), self))
512 if kwds:
513 raise ValueError('Got unexpected field names: %r' % kwds.keys())
514 return result
Christian Heimes0449f632007-12-15 01:27:15 +0000515
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000516 x = property(itemgetter(0))
517 y = property(itemgetter(1))
Georg Brandl116aa622007-08-15 14:28:22 +0000518
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000519 >>> p = Point(11, y=22) # instantiate with positional or keyword arguments
Christian Heimes99170a52007-12-19 02:07:34 +0000520 >>> p[0] + p[1] # indexable like the plain tuple (11, 22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000521 33
522 >>> x, y = p # unpack like a regular tuple
523 >>> x, y
524 (11, 22)
525 >>> p.x + p.y # fields also accessable by name
526 33
527 >>> p # readable __repr__ with a name=value style
528 Point(x=11, y=22)
Georg Brandl116aa622007-08-15 14:28:22 +0000529
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000530Named tuples are especially useful for assigning field names to result tuples returned
531by the :mod:`csv` or :mod:`sqlite3` modules::
532
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000533 EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
Georg Brandl9afde1c2007-11-01 20:32:30 +0000534
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000535 import csv
Christian Heimesfaf2f632008-01-06 16:59:19 +0000536 for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537 print(emp.name, emp.title)
538
Georg Brandl9afde1c2007-11-01 20:32:30 +0000539 import sqlite3
540 conn = sqlite3.connect('/companydata')
541 cursor = conn.cursor()
542 cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
Christian Heimesfaf2f632008-01-06 16:59:19 +0000543 for emp in map(EmployeeRecord._make, cursor.fetchall()):
Christian Heimes00412232008-01-10 16:02:19 +0000544 print(emp.name, emp.title)
Georg Brandl9afde1c2007-11-01 20:32:30 +0000545
Christian Heimes99170a52007-12-19 02:07:34 +0000546In addition to the methods inherited from tuples, named tuples support
Christian Heimes2380ac72008-01-09 00:17:24 +0000547three additional methods and one attribute. To prevent conflicts with
548field names, the method and attribute names start with an underscore.
Christian Heimes99170a52007-12-19 02:07:34 +0000549
Christian Heimes790c8232008-01-07 21:14:23 +0000550.. method:: somenamedtuple._make(iterable)
Christian Heimes99170a52007-12-19 02:07:34 +0000551
Christian Heimesfaf2f632008-01-06 16:59:19 +0000552 Class method that makes a new instance from an existing sequence or iterable.
Christian Heimes99170a52007-12-19 02:07:34 +0000553
554::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000555
Christian Heimesfaf2f632008-01-06 16:59:19 +0000556 >>> t = [11, 22]
557 >>> Point._make(t)
558 Point(x=11, y=22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000559
Christian Heimes790c8232008-01-07 21:14:23 +0000560.. method:: somenamedtuple._asdict()
Georg Brandl9afde1c2007-11-01 20:32:30 +0000561
562 Return a new dict which maps field names to their corresponding values:
563
564::
565
Christian Heimes0449f632007-12-15 01:27:15 +0000566 >>> p._asdict()
Georg Brandl9afde1c2007-11-01 20:32:30 +0000567 {'x': 11, 'y': 22}
568
Christian Heimes790c8232008-01-07 21:14:23 +0000569.. method:: somenamedtuple._replace(kwargs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000571 Return a new instance of the named tuple replacing specified fields with new values:
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000572
573::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000574
575 >>> p = Point(x=11, y=22)
Christian Heimes0449f632007-12-15 01:27:15 +0000576 >>> p._replace(x=33)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000577 Point(x=33, y=22)
578
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000579 >>> for partnum, record in inventory.items():
Christian Heimes454f37b2008-01-10 00:10:02 +0000580 ... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000581
Christian Heimes790c8232008-01-07 21:14:23 +0000582.. attribute:: somenamedtuple._fields
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000583
Christian Heimes2380ac72008-01-09 00:17:24 +0000584 Tuple of strings listing the field names. Useful for introspection
Georg Brandl9afde1c2007-11-01 20:32:30 +0000585 and for creating new named tuple types from existing named tuples.
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000586
587::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000588
Christian Heimes0449f632007-12-15 01:27:15 +0000589 >>> p._fields # view the field names
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000590 ('x', 'y')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000591
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000592 >>> Color = namedtuple('Color', 'red green blue')
Christian Heimes0449f632007-12-15 01:27:15 +0000593 >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000594 >>> Pixel(11, 22, 128, 255, 0)
Christian Heimes454f37b2008-01-10 00:10:02 +0000595 Pixel(x=11, y=22, red=128, green=255, blue=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000596
Christian Heimes0449f632007-12-15 01:27:15 +0000597To retrieve a field whose name is stored in a string, use the :func:`getattr`
Christian Heimes790c8232008-01-07 21:14:23 +0000598function::
Christian Heimes0449f632007-12-15 01:27:15 +0000599
600 >>> getattr(p, 'x')
601 11
602
Christian Heimes25bb7832008-01-11 16:17:00 +0000603To convert a dictionary to a named tuple, use the double-star-operator [#]_::
Christian Heimes99170a52007-12-19 02:07:34 +0000604
605 >>> d = {'x': 11, 'y': 22}
606 >>> Point(**d)
607 Point(x=11, y=22)
608
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000609Since a named tuple is a regular Python class, it is easy to add or change
Christian Heimes043d6f62008-01-07 17:19:16 +0000610functionality with a subclass. Here is how to add a calculated field and
611a fixed-width print format::
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000612
Christian Heimes043d6f62008-01-07 17:19:16 +0000613 >>> class Point(namedtuple('Point', 'x y')):
Christian Heimes25bb7832008-01-11 16:17:00 +0000614 ... __slots__ = ()
Christian Heimes454f37b2008-01-10 00:10:02 +0000615 ... @property
616 ... def hypot(self):
617 ... return (self.x ** 2 + self.y ** 2) ** 0.5
618 ... def __str__(self):
Christian Heimes25bb7832008-01-11 16:17:00 +0000619 ... 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 +0000620
Christian Heimes25bb7832008-01-11 16:17:00 +0000621 >>> for p in Point(3, 4), Point(14, 5/7.):
Christian Heimes00412232008-01-10 16:02:19 +0000622 ... print(p)
Christian Heimes790c8232008-01-07 21:14:23 +0000623
Christian Heimes25bb7832008-01-11 16:17:00 +0000624 Point: x= 3.000 y= 4.000 hypot= 5.000
625 Point: x=14.000 y= 0.714 hypot=14.018
Christian Heimes043d6f62008-01-07 17:19:16 +0000626
Christian Heimesaf98da12008-01-27 15:18:18 +0000627The subclass shown above sets ``__slots__`` to an empty tuple. This keeps
Christian Heimes679db4a2008-01-18 09:56:22 +0000628keep memory requirements low by preventing the creation of instance dictionaries.
629
Christian Heimes2380ac72008-01-09 00:17:24 +0000630
631Subclassing is not useful for adding new, stored fields. Instead, simply
632create a new named tuple type from the :attr:`_fields` attribute::
633
Christian Heimes25bb7832008-01-11 16:17:00 +0000634 >>> Point3D = namedtuple('Point3D', Point._fields + ('z',))
Christian Heimes2380ac72008-01-09 00:17:24 +0000635
636Default values can be implemented by using :meth:`_replace` to
Christian Heimes790c8232008-01-07 21:14:23 +0000637customize a prototype instance::
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000638
639 >>> Account = namedtuple('Account', 'owner balance transaction_count')
Christian Heimes587c2bf2008-01-19 16:21:02 +0000640 >>> default_account = Account('<owner name>', 0.0, 0)
641 >>> johns_account = default_account._replace(owner='John')
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000642
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000643.. rubric:: Footnotes
644
Christian Heimes99170a52007-12-19 02:07:34 +0000645.. [#] For information on the double-star-operator see
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000646 :ref:`tut-unpacking-arguments` and :ref:`calls`.
Raymond Hettingere4c96ad2008-02-06 01:23:58 +0000647
648
649
650:class:`UserDict` objects
Mark Summerfield8f2d0062008-02-06 13:30:44 +0000651-------------------------
Raymond Hettingere4c96ad2008-02-06 01:23:58 +0000652
653The class, :class:`UserDict` acts as a wrapper around dictionary objects.
654The need for this class has been partially supplanted by the ability to
655subclass directly from :class:`dict`; however, this class can be easier
656to work with because the underlying dictionary is accessible as an
657attribute.
658
659.. class:: UserDict([initialdata])
660
661 Class that simulates a dictionary. The instance's contents are kept in a
662 regular dictionary, which is accessible via the :attr:`data` attribute of
663 :class:`UserDict` instances. If *initialdata* is provided, :attr:`data` is
664 initialized with its contents; note that a reference to *initialdata* will not
665 be kept, allowing it be used for other purposes.
666
667In addition to supporting the methods and operations of mappings,
Raymond Hettingerebcee3f2008-02-06 19:54:00 +0000668:class:`UserDict` instances provide the following attribute:
Raymond Hettingere4c96ad2008-02-06 01:23:58 +0000669
670.. attribute:: UserDict.data
671
672 A real dictionary used to store the contents of the :class:`UserDict` class.
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000673
674
675
676:class:`UserList` objects
677-------------------------
678
679This class acts as a wrapper around list objects. It is a useful base class
680for your own list-like classes which can inherit from them and override
681existing methods or add new ones. In this way, one can add new behaviors to
682lists.
683
684The need for this class has been partially supplanted by the ability to
685subclass directly from :class:`list`; however, this class can be easier
686to work with because the underlying list is accessible as an attribute.
687
688.. class:: UserList([list])
689
690 Class that simulates a list. The instance's contents are kept in a regular
691 list, which is accessible via the :attr:`data` attribute of :class:`UserList`
692 instances. The instance's contents are initially set to a copy of *list*,
693 defaulting to the empty list ``[]``. *list* can be any iterable, for
694 example a real Python list or a :class:`UserList` object.
695
696In addition to supporting the methods and operations of mutable sequences,
697:class:`UserList` instances provide the following attribute:
698
699.. attribute:: UserList.data
700
701 A real :class:`list` object used to store the contents of the
702 :class:`UserList` class.
703
704**Subclassing requirements:** Subclasses of :class:`UserList` are expect to
705offer a constructor which can be called with either no arguments or one
706argument. List operations which return a new sequence attempt to create an
707instance of the actual implementation class. To do so, it assumes that the
708constructor can be called with a single parameter, which is a sequence object
709used as a data source.
710
711If a derived class does not wish to comply with this requirement, all of the
712special methods supported by this class will need to be overridden; please
713consult the sources for information about the methods which need to be provided
714in that case.