blob: 66d373d2c086bb79583ed20d3945aac29351bb92 [file] [log] [blame]
Raymond Hettinger53dbe392008-02-12 20:03:09 +00001:mod:`collections` --- Container datatypes
2==========================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: collections
Raymond Hettinger53dbe392008-02-12 20:03:09 +00005 :synopsis: Container datatypes
Georg Brandl116aa622007-08-15 14:28:22 +00006.. moduleauthor:: Raymond Hettinger <python@rcn.com>
7.. sectionauthor:: Raymond Hettinger <python@rcn.com>
8
Christian Heimesfe337bf2008-03-23 21:54:12 +00009.. testsetup:: *
10
11 from collections import *
12 import itertools
13 __name__ = '<doctest>'
Georg Brandl116aa622007-08-15 14:28:22 +000014
Raymond Hettingera6b76ba2010-08-08 00:29:08 +000015This module implements specialized container datatypes providing alternatives to
16Python's general purpose built-in containers, :class:`dict`, :class:`list`,
17:class:`set`, and :class:`tuple`.
Christian Heimes0bd4e112008-02-12 22:59:25 +000018
Raymond Hettingera6b76ba2010-08-08 00:29:08 +000019===================== ====================================================================
20:func:`namedtuple` factory function for creating tuple subclasses with named fields
21:class:`deque` list-like container with fast appends and pops on either end
22:class:`Counter` dict subclass for counting hashable objects
23:class:`OrderedDict` dict subclass that remembers the order entries were added
24:class:`defaultdict` dict subclass that calls a factory function to supply missing values
25:class:`UserDict` wrapper around dictionary objects for easier dict subclassing
26:class:`UserList` wrapper around list objects for easier list subclassing
27:class:`UserString` wrapper around string objects for easier string subclassing
28===================== ====================================================================
Georg Brandl116aa622007-08-15 14:28:22 +000029
Raymond Hettingera6b76ba2010-08-08 00:29:08 +000030In addition to the concrete container classes, the collections module provides
31ABCs (abstract base classes) that can be used to test whether a class provides a
32particular interface, for example, whether it is hashable or a mapping.
Mark Summerfield08898b42007-09-05 08:43:04 +000033
34
Raymond Hettingerb8baf632009-01-14 02:20:07 +000035:class:`Counter` objects
36------------------------
37
38A counter tool is provided to support convenient and rapid tallies.
39For example::
40
Raymond Hettinger1c62dc92009-02-04 11:41:45 +000041 >>> # Tally occurrences of words in a list
Raymond Hettingerb8baf632009-01-14 02:20:07 +000042 >>> cnt = Counter()
Raymond Hettinger670eaec2009-01-21 23:14:07 +000043 >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
Raymond Hettingerb8baf632009-01-14 02:20:07 +000044 ... cnt[word] += 1
45 >>> cnt
46 Counter({'blue': 3, 'red': 2, 'green': 1})
47
Raymond Hettinger1c62dc92009-02-04 11:41:45 +000048 >>> # Find the ten most common words in Hamlet
Raymond Hettingerb8baf632009-01-14 02:20:07 +000049 >>> import re
50 >>> words = re.findall('\w+', open('hamlet.txt').read().lower())
Raymond Hettinger0bae6622009-01-20 13:00:59 +000051 >>> Counter(words).most_common(10)
Raymond Hettingerb8baf632009-01-14 02:20:07 +000052 [('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
53 ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
54
55.. class:: Counter([iterable-or-mapping])
56
Raymond Hettinger670eaec2009-01-21 23:14:07 +000057 A :class:`Counter` is a :class:`dict` subclass for counting hashable objects.
Raymond Hettingerb8baf632009-01-14 02:20:07 +000058 It is an unordered collection where elements are stored as dictionary keys
59 and their counts are stored as dictionary values. Counts are allowed to be
60 any integer value including zero or negative counts. The :class:`Counter`
61 class is similar to bags or multisets in other languages.
62
63 Elements are counted from an *iterable* or initialized from another
Benjamin Peterson25c95f12009-05-08 20:42:26 +000064 *mapping* (or counter):
Raymond Hettingerb8baf632009-01-14 02:20:07 +000065
Raymond Hettinger73662a52009-01-27 02:38:22 +000066 >>> c = Counter() # a new, empty counter
67 >>> c = Counter('gallahad') # a new counter from an iterable
68 >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping
69 >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args
Raymond Hettingerb8baf632009-01-14 02:20:07 +000070
Raymond Hettinger670eaec2009-01-21 23:14:07 +000071 Counter objects have a dictionary interface except that they return a zero
Benjamin Peterson25c95f12009-05-08 20:42:26 +000072 count for missing items instead of raising a :exc:`KeyError`:
Raymond Hettingerb8baf632009-01-14 02:20:07 +000073
Raymond Hettinger94adc8e2009-01-22 05:27:37 +000074 >>> c = Counter(['eggs', 'ham'])
Raymond Hettingerb8baf632009-01-14 02:20:07 +000075 >>> c['bacon'] # count of a missing element is zero
76 0
77
Raymond Hettinger94adc8e2009-01-22 05:27:37 +000078 Setting a count to zero does not remove an element from a counter.
79 Use ``del`` to remove it entirely:
Raymond Hettingerb8baf632009-01-14 02:20:07 +000080
Raymond Hettinger94adc8e2009-01-22 05:27:37 +000081 >>> c['sausage'] = 0 # counter entry with a zero count
82 >>> del c['sausage'] # del actually removes the entry
Raymond Hettingerb8baf632009-01-14 02:20:07 +000083
Benjamin Petersond45bf582009-03-02 21:44:54 +000084 .. versionadded:: 3.1
Raymond Hettingerb8baf632009-01-14 02:20:07 +000085
86
Ezio Melotti0be8b1c2010-04-04 06:53:44 +000087 Counter objects support three methods beyond those available for all
Raymond Hettingerb8baf632009-01-14 02:20:07 +000088 dictionaries:
89
90 .. method:: elements()
91
Raymond Hettinger670eaec2009-01-21 23:14:07 +000092 Return an iterator over elements repeating each as many times as its
93 count. Elements are returned in arbitrary order. If an element's count
94 is less than one, :meth:`elements` will ignore it.
Raymond Hettingerb8baf632009-01-14 02:20:07 +000095
Raymond Hettinger0bae6622009-01-20 13:00:59 +000096 >>> c = Counter(a=4, b=2, c=0, d=-2)
Raymond Hettingerb8baf632009-01-14 02:20:07 +000097 >>> list(c.elements())
98 ['a', 'a', 'a', 'a', 'b', 'b']
99
100 .. method:: most_common([n])
101
Raymond Hettinger73662a52009-01-27 02:38:22 +0000102 Return a list of the *n* most common elements and their counts from the
Raymond Hettingerd04fa312009-02-04 19:45:13 +0000103 most common to the least. If *n* is not specified, :func:`most_common`
Raymond Hettinger73662a52009-01-27 02:38:22 +0000104 returns *all* elements in the counter. Elements with equal counts are
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000105 ordered arbitrarily:
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000106
107 >>> Counter('abracadabra').most_common(3)
108 [('a', 5), ('r', 2), ('b', 2)]
109
Raymond Hettinger9c01e442010-04-03 10:32:58 +0000110 .. method:: subtract([iterable-or-mapping])
111
112 Elements are subtracted from an *iterable* or from another *mapping*
113 (or counter). Like :meth:`dict.update` but subtracts counts instead
114 of replacing them. Both inputs and outputs may be zero or negative.
115
116 >>> c = Counter(a=4, b=2, c=0, d=-2)
117 >>> d = Counter(a=1, b=2, c=3, d=4)
118 >>> c.subtract(d)
119 Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
120
Ezio Melotti0be8b1c2010-04-04 06:53:44 +0000121 .. versionadded:: 3.2
122
Raymond Hettinger670eaec2009-01-21 23:14:07 +0000123 The usual dictionary methods are available for :class:`Counter` objects
124 except for two which work differently for counters.
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000125
126 .. method:: fromkeys(iterable)
127
Raymond Hettinger73662a52009-01-27 02:38:22 +0000128 This class method is not implemented for :class:`Counter` objects.
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000129
130 .. method:: update([iterable-or-mapping])
131
Raymond Hettinger73662a52009-01-27 02:38:22 +0000132 Elements are counted from an *iterable* or added-in from another
133 *mapping* (or counter). Like :meth:`dict.update` but adds counts
134 instead of replacing them. Also, the *iterable* is expected to be a
135 sequence of elements, not a sequence of ``(key, value)`` pairs.
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000136
137Common patterns for working with :class:`Counter` objects::
138
Raymond Hettinger73662a52009-01-27 02:38:22 +0000139 sum(c.values()) # total of all counts
140 c.clear() # reset all counts
141 list(c) # list unique elements
142 set(c) # convert to a set
143 dict(c) # convert to a regular dictionary
144 c.items() # convert to a list of (elem, cnt) pairs
145 Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs
146 c.most_common()[:-n:-1] # n least common elements
147 c += Counter() # remove zero and negative counts
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000148
Raymond Hettinger72a95cc2009-02-25 22:51:40 +0000149Several mathematical operations are provided for combining :class:`Counter`
150objects to produce multisets (counters that have counts greater than zero).
151Addition and subtraction combine counters by adding or subtracting the counts
152of corresponding elements. Intersection and union return the minimum and
153maximum of corresponding counts. Each operation can accept inputs with signed
154counts, but the output will exclude results with counts of zero or less.
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000155
Raymond Hettingere0d1b9f2009-01-21 20:36:27 +0000156 >>> c = Counter(a=3, b=1)
157 >>> d = Counter(a=1, b=2)
Raymond Hettinger73662a52009-01-27 02:38:22 +0000158 >>> c + d # add two counters together: c[x] + d[x]
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000159 Counter({'a': 4, 'b': 3})
Raymond Hettinger73662a52009-01-27 02:38:22 +0000160 >>> c - d # subtract (keeping only positive counts)
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000161 Counter({'a': 2})
Raymond Hettinger73662a52009-01-27 02:38:22 +0000162 >>> c & d # intersection: min(c[x], d[x])
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000163 Counter({'a': 1, 'b': 1})
Raymond Hettinger73662a52009-01-27 02:38:22 +0000164 >>> c | d # union: max(c[x], d[x])
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000165 Counter({'a': 3, 'b': 2})
166
Raymond Hettinger22f18852010-04-12 21:45:14 +0000167.. note::
168
169 Counters were primarily designed to work with positive integers to represent
170 running counts; however, care was taken to not unnecessarily preclude use
171 cases needing other types or negative values. To help with those use cases,
172 this section documents the minimum range and type restrictions.
173
174 * The :class:`Counter` class itself is a dictionary subclass with no
175 restrictions on its keys and values. The values are intended to be numbers
176 representing counts, but you *could* store anything in the value field.
177
178 * The :meth:`most_common` method requires only that the values be orderable.
179
180 * For in-place operations such as ``c[key] += 1``, the value type need only
181 support addition and subtraction. So fractions, floats, and decimals would
182 work and negative values are supported. The same is also true for
183 :meth:`update` and :meth:`subtract` which allow negative and zero values
184 for both inputs and outputs.
185
186 * The multiset methods are designed only for use cases with positive values.
187 The inputs may be negative or zero, but only outputs with positive values
188 are created. There are no type restrictions, but the value type needs to
189 support support addition, subtraction, and comparison.
190
191 * The :meth:`elements` method requires integer counts. It ignores zero and
192 negative counts.
193
Raymond Hettingerb14043c2009-01-20 23:44:31 +0000194.. seealso::
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000195
Raymond Hettinger94adc8e2009-01-22 05:27:37 +0000196 * `Counter class <http://code.activestate.com/recipes/576611/>`_
197 adapted for Python 2.5 and an early `Bag recipe
198 <http://code.activestate.com/recipes/259174/>`_ for Python 2.4.
199
Raymond Hettingerb14043c2009-01-20 23:44:31 +0000200 * `Bag class <http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html>`_
201 in Smalltalk.
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000202
Raymond Hettingerb14043c2009-01-20 23:44:31 +0000203 * Wikipedia entry for `Multisets <http://en.wikipedia.org/wiki/Multiset>`_\.
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000204
Raymond Hettingerb14043c2009-01-20 23:44:31 +0000205 * `C++ multisets <http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm>`_
Raymond Hettinger94adc8e2009-01-22 05:27:37 +0000206 tutorial with examples.
Raymond Hettingerb14043c2009-01-20 23:44:31 +0000207
Raymond Hettinger94adc8e2009-01-22 05:27:37 +0000208 * For mathematical operations on multisets and their use cases, see
Raymond Hettingerb14043c2009-01-20 23:44:31 +0000209 *Knuth, Donald. The Art of Computer Programming Volume II,
210 Section 4.6.3, Exercise 19*\.
211
Raymond Hettinger670eaec2009-01-21 23:14:07 +0000212 * To enumerate all distinct multisets of a given size over a given set of
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000213 elements, see :func:`itertools.combinations_with_replacement`.
Raymond Hettingerb14043c2009-01-20 23:44:31 +0000214
Raymond Hettinger94adc8e2009-01-22 05:27:37 +0000215 map(Counter, combinations_with_replacement('ABC', 2)) --> AA AB AC BB BC CC
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000216
217
Georg Brandl116aa622007-08-15 14:28:22 +0000218:class:`deque` objects
219----------------------
220
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000221.. class:: deque([iterable, [maxlen]])
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223 Returns a new deque object initialized left-to-right (using :meth:`append`) with
224 data from *iterable*. If *iterable* is not specified, the new deque is empty.
225
226 Deques are a generalization of stacks and queues (the name is pronounced "deck"
227 and is short for "double-ended queue"). Deques support thread-safe, memory
228 efficient appends and pops from either side of the deque with approximately the
229 same O(1) performance in either direction.
230
231 Though :class:`list` objects support similar operations, they are optimized for
232 fast fixed-length operations and incur O(n) memory movement costs for
233 ``pop(0)`` and ``insert(0, v)`` operations which change both the size and
234 position of the underlying data representation.
235
Georg Brandl116aa622007-08-15 14:28:22 +0000236
Georg Brandl9afde1c2007-11-01 20:32:30 +0000237 If *maxlen* is not specified or is *None*, deques may grow to an
238 arbitrary length. Otherwise, the deque is bounded to the specified maximum
239 length. Once a bounded length deque is full, when new items are added, a
240 corresponding number of items are discarded from the opposite end. Bounded
241 length deques provide functionality similar to the ``tail`` filter in
242 Unix. They are also useful for tracking transactions and other pools of data
243 where only the most recent activity is of interest.
244
Georg Brandl9afde1c2007-11-01 20:32:30 +0000245
Benjamin Petersone41251e2008-04-25 01:59:09 +0000246 Deque objects support the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000247
Benjamin Petersone41251e2008-04-25 01:59:09 +0000248 .. method:: append(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000249
Benjamin Petersone41251e2008-04-25 01:59:09 +0000250 Add *x* to the right side of the deque.
Georg Brandl116aa622007-08-15 14:28:22 +0000251
252
Benjamin Petersone41251e2008-04-25 01:59:09 +0000253 .. method:: appendleft(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000254
Benjamin Petersone41251e2008-04-25 01:59:09 +0000255 Add *x* to the left side of the deque.
Georg Brandl116aa622007-08-15 14:28:22 +0000256
257
Benjamin Petersone41251e2008-04-25 01:59:09 +0000258 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +0000259
Benjamin Petersone41251e2008-04-25 01:59:09 +0000260 Remove all elements from the deque leaving it with length 0.
Georg Brandl116aa622007-08-15 14:28:22 +0000261
262
Raymond Hettinger44459de2010-04-03 23:20:46 +0000263 .. method:: count(x)
264
265 Count the number of deque elements equal to *x*.
266
267 .. versionadded:: 3.2
268
Benjamin Petersone41251e2008-04-25 01:59:09 +0000269 .. method:: extend(iterable)
Georg Brandl116aa622007-08-15 14:28:22 +0000270
Benjamin Petersone41251e2008-04-25 01:59:09 +0000271 Extend the right side of the deque by appending elements from the iterable
272 argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000273
274
Benjamin Petersone41251e2008-04-25 01:59:09 +0000275 .. method:: extendleft(iterable)
Georg Brandl116aa622007-08-15 14:28:22 +0000276
Benjamin Petersone41251e2008-04-25 01:59:09 +0000277 Extend the left side of the deque by appending elements from *iterable*.
278 Note, the series of left appends results in reversing the order of
279 elements in the iterable argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281
Benjamin Petersone41251e2008-04-25 01:59:09 +0000282 .. method:: pop()
Georg Brandl116aa622007-08-15 14:28:22 +0000283
Benjamin Petersone41251e2008-04-25 01:59:09 +0000284 Remove and return an element from the right side of the deque. If no
285 elements are present, raises an :exc:`IndexError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287
Benjamin Petersone41251e2008-04-25 01:59:09 +0000288 .. method:: popleft()
Georg Brandl116aa622007-08-15 14:28:22 +0000289
Benjamin Petersone41251e2008-04-25 01:59:09 +0000290 Remove and return an element from the left side of the deque. If no
291 elements are present, raises an :exc:`IndexError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000292
293
Benjamin Petersone41251e2008-04-25 01:59:09 +0000294 .. method:: remove(value)
Georg Brandl116aa622007-08-15 14:28:22 +0000295
Benjamin Petersone41251e2008-04-25 01:59:09 +0000296 Removed the first occurrence of *value*. If not found, raises a
297 :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000298
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000299 .. method:: reverse()
300
301 Reverse the elements of the deque in-place and then return ``None``.
302
303 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000304
Benjamin Petersone41251e2008-04-25 01:59:09 +0000305 .. method:: rotate(n)
Georg Brandl116aa622007-08-15 14:28:22 +0000306
Benjamin Petersone41251e2008-04-25 01:59:09 +0000307 Rotate the deque *n* steps to the right. If *n* is negative, rotate to
308 the left. Rotating one step to the right is equivalent to:
309 ``d.appendleft(d.pop())``.
310
Georg Brandl116aa622007-08-15 14:28:22 +0000311
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +0000312 Deque objects also provide one read-only attribute:
313
314 .. attribute:: maxlen
315
316 Maximum size of a deque or *None* if unbounded.
317
Raymond Hettinger150fb9c2009-03-10 22:48:06 +0000318 .. versionadded:: 3.1
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +0000319
320
Georg Brandl116aa622007-08-15 14:28:22 +0000321In addition to the above, deques support iteration, pickling, ``len(d)``,
322``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with
Benjamin Peterson206e3072008-10-19 14:07:49 +0000323the :keyword:`in` operator, and subscript references such as ``d[-1]``. Indexed
324access is O(1) at both ends but slows to O(n) in the middle. For fast random
325access, use lists instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000326
Christian Heimesfe337bf2008-03-23 21:54:12 +0000327Example:
328
329.. doctest::
Georg Brandl116aa622007-08-15 14:28:22 +0000330
331 >>> from collections import deque
332 >>> d = deque('ghi') # make a new deque with three items
333 >>> for elem in d: # iterate over the deque's elements
Neal Norwitz752abd02008-05-13 04:55:24 +0000334 ... print(elem.upper())
Georg Brandl116aa622007-08-15 14:28:22 +0000335 G
336 H
337 I
338
339 >>> d.append('j') # add a new entry to the right side
340 >>> d.appendleft('f') # add a new entry to the left side
341 >>> d # show the representation of the deque
342 deque(['f', 'g', 'h', 'i', 'j'])
343
344 >>> d.pop() # return and remove the rightmost item
345 'j'
346 >>> d.popleft() # return and remove the leftmost item
347 'f'
348 >>> list(d) # list the contents of the deque
349 ['g', 'h', 'i']
350 >>> d[0] # peek at leftmost item
351 'g'
352 >>> d[-1] # peek at rightmost item
353 'i'
354
355 >>> list(reversed(d)) # list the contents of a deque in reverse
356 ['i', 'h', 'g']
357 >>> 'h' in d # search the deque
358 True
359 >>> d.extend('jkl') # add multiple elements at once
360 >>> d
361 deque(['g', 'h', 'i', 'j', 'k', 'l'])
362 >>> d.rotate(1) # right rotation
363 >>> d
364 deque(['l', 'g', 'h', 'i', 'j', 'k'])
365 >>> d.rotate(-1) # left rotation
366 >>> d
367 deque(['g', 'h', 'i', 'j', 'k', 'l'])
368
369 >>> deque(reversed(d)) # make a new deque in reverse order
370 deque(['l', 'k', 'j', 'i', 'h', 'g'])
371 >>> d.clear() # empty the deque
372 >>> d.pop() # cannot pop from an empty deque
373 Traceback (most recent call last):
374 File "<pyshell#6>", line 1, in -toplevel-
375 d.pop()
376 IndexError: pop from an empty deque
377
378 >>> d.extendleft('abc') # extendleft() reverses the input order
379 >>> d
380 deque(['c', 'b', 'a'])
381
382
Georg Brandl9afde1c2007-11-01 20:32:30 +0000383:class:`deque` Recipes
384^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000385
386This section shows various approaches to working with deques.
387
Raymond Hettingerd2ee64d2009-03-31 22:52:48 +0000388Bounded length deques provide functionality similar to the ``tail`` filter
389in Unix::
390
391 def tail(filename, n=10):
392 'Return the last n lines of a file'
393 return deque(open(filename), n)
394
395Another approach to using deques is to maintain a sequence of recently
396added elements by appending to the right and popping to the left::
397
398 def moving_average(iterable, n=3):
399 # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
400 # http://en.wikipedia.org/wiki/Moving_average
401 it = iter(iterable)
Raymond Hettingerd40285a2009-05-22 01:11:26 +0000402 d = deque(itertools.islice(it, n-1))
403 d.appendleft(0)
Raymond Hettingerd2ee64d2009-03-31 22:52:48 +0000404 s = sum(d)
Raymond Hettingerd2ee64d2009-03-31 22:52:48 +0000405 for elem in it:
406 s += elem - d.popleft()
407 d.append(elem)
408 yield s / n
409
Georg Brandl116aa622007-08-15 14:28:22 +0000410The :meth:`rotate` method provides a way to implement :class:`deque` slicing and
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000411deletion. For example, a pure Python implementation of ``del d[n]`` relies on
Georg Brandl116aa622007-08-15 14:28:22 +0000412the :meth:`rotate` method to position elements to be popped::
413
414 def delete_nth(d, n):
415 d.rotate(-n)
416 d.popleft()
417 d.rotate(n)
418
419To implement :class:`deque` slicing, use a similar approach applying
420:meth:`rotate` to bring a target element to the left side of the deque. Remove
421old entries with :meth:`popleft`, add new entries with :meth:`extend`, and then
422reverse the rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000423With minor variations on that approach, it is easy to implement Forth style
424stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``,
425``rot``, and ``roll``.
426
Georg Brandl116aa622007-08-15 14:28:22 +0000427
428:class:`defaultdict` objects
429----------------------------
430
Georg Brandl116aa622007-08-15 14:28:22 +0000431.. class:: defaultdict([default_factory[, ...]])
432
433 Returns a new dictionary-like object. :class:`defaultdict` is a subclass of the
Georg Brandl22b34312009-07-26 14:54:51 +0000434 built-in :class:`dict` class. It overrides one method and adds one writable
Georg Brandl116aa622007-08-15 14:28:22 +0000435 instance variable. The remaining functionality is the same as for the
436 :class:`dict` class and is not documented here.
437
438 The first argument provides the initial value for the :attr:`default_factory`
439 attribute; it defaults to ``None``. All remaining arguments are treated the same
440 as if they were passed to the :class:`dict` constructor, including keyword
441 arguments.
442
Georg Brandl116aa622007-08-15 14:28:22 +0000443
Benjamin Petersone41251e2008-04-25 01:59:09 +0000444 :class:`defaultdict` objects support the following method in addition to the
445 standard :class:`dict` operations:
Georg Brandl116aa622007-08-15 14:28:22 +0000446
Benjamin Petersond319ad52010-07-18 14:27:02 +0000447 .. method:: __missing__(key)
Georg Brandl116aa622007-08-15 14:28:22 +0000448
Benjamin Peterson5478b472008-09-17 22:25:09 +0000449 If the :attr:`default_factory` attribute is ``None``, this raises a
Benjamin Petersone41251e2008-04-25 01:59:09 +0000450 :exc:`KeyError` exception with the *key* as argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000451
Benjamin Petersone41251e2008-04-25 01:59:09 +0000452 If :attr:`default_factory` is not ``None``, it is called without arguments
453 to provide a default value for the given *key*, this value is inserted in
454 the dictionary for the *key*, and returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000455
Benjamin Petersone41251e2008-04-25 01:59:09 +0000456 If calling :attr:`default_factory` raises an exception this exception is
457 propagated unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +0000458
Benjamin Petersone41251e2008-04-25 01:59:09 +0000459 This method is called by the :meth:`__getitem__` method of the
460 :class:`dict` class when the requested key is not found; whatever it
461 returns or raises is then returned or raised by :meth:`__getitem__`.
Georg Brandl116aa622007-08-15 14:28:22 +0000462
463
Benjamin Petersone41251e2008-04-25 01:59:09 +0000464 :class:`defaultdict` objects support the following instance variable:
Georg Brandl116aa622007-08-15 14:28:22 +0000465
Benjamin Petersone41251e2008-04-25 01:59:09 +0000466
Benjamin Petersond319ad52010-07-18 14:27:02 +0000467 .. attribute:: default_factory
Benjamin Petersone41251e2008-04-25 01:59:09 +0000468
469 This attribute is used by the :meth:`__missing__` method; it is
470 initialized from the first argument to the constructor, if present, or to
471 ``None``, if absent.
Georg Brandl116aa622007-08-15 14:28:22 +0000472
473
Georg Brandl116aa622007-08-15 14:28:22 +0000474:class:`defaultdict` Examples
475^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
476
477Using :class:`list` as the :attr:`default_factory`, it is easy to group a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000478sequence of key-value pairs into a dictionary of lists:
Georg Brandl116aa622007-08-15 14:28:22 +0000479
480 >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
481 >>> d = defaultdict(list)
482 >>> for k, v in s:
483 ... d[k].append(v)
484 ...
Ezio Melottic53a8942009-09-12 01:52:05 +0000485 >>> list(d.items())
Georg Brandl116aa622007-08-15 14:28:22 +0000486 [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
487
488When each key is encountered for the first time, it is not already in the
489mapping; so an entry is automatically created using the :attr:`default_factory`
490function which returns an empty :class:`list`. The :meth:`list.append`
491operation then attaches the value to the new list. When keys are encountered
492again, the look-up proceeds normally (returning the list for that key) and the
493:meth:`list.append` operation adds another value to the list. This technique is
Christian Heimesfe337bf2008-03-23 21:54:12 +0000494simpler and faster than an equivalent technique using :meth:`dict.setdefault`:
Georg Brandl116aa622007-08-15 14:28:22 +0000495
496 >>> d = {}
497 >>> for k, v in s:
498 ... d.setdefault(k, []).append(v)
499 ...
Ezio Melottic53a8942009-09-12 01:52:05 +0000500 >>> list(d.items())
Georg Brandl116aa622007-08-15 14:28:22 +0000501 [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
502
503Setting the :attr:`default_factory` to :class:`int` makes the
504:class:`defaultdict` useful for counting (like a bag or multiset in other
Christian Heimesfe337bf2008-03-23 21:54:12 +0000505languages):
Georg Brandl116aa622007-08-15 14:28:22 +0000506
507 >>> s = 'mississippi'
508 >>> d = defaultdict(int)
509 >>> for k in s:
510 ... d[k] += 1
511 ...
Ezio Melottic53a8942009-09-12 01:52:05 +0000512 >>> list(d.items())
Georg Brandl116aa622007-08-15 14:28:22 +0000513 [('i', 4), ('p', 2), ('s', 4), ('m', 1)]
514
515When a letter is first encountered, it is missing from the mapping, so the
516:attr:`default_factory` function calls :func:`int` to supply a default count of
517zero. The increment operation then builds up the count for each letter.
518
519The function :func:`int` which always returns zero is just a special case of
520constant functions. A faster and more flexible way to create constant functions
521is to use a lambda function which can supply any constant value (not just
Christian Heimesfe337bf2008-03-23 21:54:12 +0000522zero):
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524 >>> def constant_factory(value):
525 ... return lambda: value
526 >>> d = defaultdict(constant_factory('<missing>'))
527 >>> d.update(name='John', action='ran')
528 >>> '%(name)s %(action)s to %(object)s' % d
529 'John ran to <missing>'
530
531Setting the :attr:`default_factory` to :class:`set` makes the
Christian Heimesfe337bf2008-03-23 21:54:12 +0000532:class:`defaultdict` useful for building a dictionary of sets:
Georg Brandl116aa622007-08-15 14:28:22 +0000533
534 >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
535 >>> d = defaultdict(set)
536 >>> for k, v in s:
537 ... d[k].add(v)
538 ...
Ezio Melottic53a8942009-09-12 01:52:05 +0000539 >>> list(d.items())
Georg Brandl116aa622007-08-15 14:28:22 +0000540 [('blue', set([2, 4])), ('red', set([1, 3]))]
541
542
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000543:func:`namedtuple` Factory Function for Tuples with Named Fields
Christian Heimes790c8232008-01-07 21:14:23 +0000544----------------------------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000545
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546Named tuples assign meaning to each position in a tuple and allow for more readable,
547self-documenting code. They can be used wherever regular tuples are used, and
548they add the ability to access fields by name instead of position index.
Georg Brandl116aa622007-08-15 14:28:22 +0000549
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000550.. function:: namedtuple(typename, field_names, verbose=False, rename=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000551
552 Returns a new tuple subclass named *typename*. The new subclass is used to
Christian Heimesc3f30c42008-02-22 16:37:40 +0000553 create tuple-like objects that have fields accessible by attribute lookup as
Georg Brandl116aa622007-08-15 14:28:22 +0000554 well as being indexable and iterable. Instances of the subclass also have a
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000555 helpful docstring (with typename and field_names) and a helpful :meth:`__repr__`
Georg Brandl116aa622007-08-15 14:28:22 +0000556 method which lists the tuple contents in a ``name=value`` format.
557
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000558 The *field_names* are a single string with each fieldname separated by whitespace
559 and/or commas, for example ``'x y'`` or ``'x, y'``. Alternatively, *field_names*
Christian Heimes25bb7832008-01-11 16:17:00 +0000560 can be a sequence of strings such as ``['x', 'y']``.
Georg Brandl9afde1c2007-11-01 20:32:30 +0000561
562 Any valid Python identifier may be used for a fieldname except for names
Christian Heimes0449f632007-12-15 01:27:15 +0000563 starting with an underscore. Valid identifiers consist of letters, digits,
564 and underscores but do not start with a digit or underscore and cannot be
Georg Brandlf6945182008-02-01 11:56:49 +0000565 a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*,
Georg Brandl9afde1c2007-11-01 20:32:30 +0000566 or *raise*.
Georg Brandl116aa622007-08-15 14:28:22 +0000567
Benjamin Petersona86f2c02009-02-10 02:41:10 +0000568 If *rename* is true, invalid fieldnames are automatically replaced
569 with positional names. For example, ``['abc', 'def', 'ghi', 'abc']`` is
Raymond Hettinger85737b82009-04-02 22:37:59 +0000570 converted to ``['abc', '_1', 'ghi', '_3']``, eliminating the keyword
Benjamin Petersona86f2c02009-02-10 02:41:10 +0000571 ``def`` and the duplicate fieldname ``abc``.
572
Christian Heimes25bb7832008-01-11 16:17:00 +0000573 If *verbose* is true, the class definition is printed just before being built.
Georg Brandl116aa622007-08-15 14:28:22 +0000574
Georg Brandl9afde1c2007-11-01 20:32:30 +0000575 Named tuple instances do not have per-instance dictionaries, so they are
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000576 lightweight and require no more memory than regular tuples.
Georg Brandl116aa622007-08-15 14:28:22 +0000577
Raymond Hettingerb62ad242009-03-02 22:16:43 +0000578 .. versionchanged:: 3.1
Benjamin Petersona86f2c02009-02-10 02:41:10 +0000579 added support for *rename*.
580
Christian Heimesfe337bf2008-03-23 21:54:12 +0000581Example:
582
583.. doctest::
584 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000585
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000586 >>> Point = namedtuple('Point', 'x y', verbose=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000587 class Point(tuple):
588 'Point(x, y)'
Christian Heimesfe337bf2008-03-23 21:54:12 +0000589 <BLANKLINE>
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000590 __slots__ = ()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000591 <BLANKLINE>
Christian Heimesfaf2f632008-01-06 16:59:19 +0000592 _fields = ('x', 'y')
Christian Heimesfe337bf2008-03-23 21:54:12 +0000593 <BLANKLINE>
Raymond Hettinger089ba7f2009-05-27 00:38:24 +0000594 def __new__(_cls, x, y):
Raymond Hettinger7b0d3c62010-04-02 18:54:02 +0000595 'Create a new instance of Point(x, y)'
Raymond Hettinger089ba7f2009-05-27 00:38:24 +0000596 return _tuple.__new__(_cls, (x, y))
Christian Heimesfe337bf2008-03-23 21:54:12 +0000597 <BLANKLINE>
Christian Heimesfaf2f632008-01-06 16:59:19 +0000598 @classmethod
Christian Heimesfe337bf2008-03-23 21:54:12 +0000599 def _make(cls, iterable, new=tuple.__new__, len=len):
Christian Heimesfaf2f632008-01-06 16:59:19 +0000600 'Make a new Point object from a sequence or iterable'
Christian Heimesfe337bf2008-03-23 21:54:12 +0000601 result = new(cls, iterable)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000602 if len(result) != 2:
603 raise TypeError('Expected 2 arguments, got %d' % len(result))
604 return result
Christian Heimesfe337bf2008-03-23 21:54:12 +0000605 <BLANKLINE>
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000606 def __repr__(self):
Raymond Hettinger7b0d3c62010-04-02 18:54:02 +0000607 'Return a nicely formatted representation string'
Raymond Hettingerd331ce92010-08-08 01:13:42 +0000608 return self.__class__.__name__ + '(x=%r, y=%r)' % self
Christian Heimesfe337bf2008-03-23 21:54:12 +0000609 <BLANKLINE>
Raymond Hettingera4f52b12009-03-02 22:28:31 +0000610 def _asdict(self):
611 'Return a new OrderedDict which maps field names to their values'
612 return OrderedDict(zip(self._fields, self))
Christian Heimesfe337bf2008-03-23 21:54:12 +0000613 <BLANKLINE>
Raymond Hettinger089ba7f2009-05-27 00:38:24 +0000614 def _replace(_self, **kwds):
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000615 'Return a new Point object replacing specified fields with new values'
Raymond Hettinger089ba7f2009-05-27 00:38:24 +0000616 result = _self._make(map(kwds.pop, ('x', 'y'), _self))
Christian Heimesfaf2f632008-01-06 16:59:19 +0000617 if kwds:
Ezio Melotti8f7649e2009-09-13 04:48:45 +0000618 raise ValueError('Got unexpected field names: %r' % list(kwds.keys()))
Christian Heimesfaf2f632008-01-06 16:59:19 +0000619 return result
Georg Brandl48310cd2009-01-03 21:18:54 +0000620 <BLANKLINE>
621 def __getnewargs__(self):
Raymond Hettinger7b0d3c62010-04-02 18:54:02 +0000622 'Return self as a plain tuple. Used by copy and pickle.'
Benjamin Peterson41181742008-07-02 20:22:54 +0000623 return tuple(self)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000624 <BLANKLINE>
Raymond Hettinger7b0d3c62010-04-02 18:54:02 +0000625 x = _property(_itemgetter(0), doc='Alias for field number 0')
626 y = _property(_itemgetter(1), doc='Alias for field number 1')
Georg Brandl116aa622007-08-15 14:28:22 +0000627
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000628 >>> p = Point(11, y=22) # instantiate with positional or keyword arguments
Christian Heimes99170a52007-12-19 02:07:34 +0000629 >>> p[0] + p[1] # indexable like the plain tuple (11, 22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000630 33
631 >>> x, y = p # unpack like a regular tuple
632 >>> x, y
633 (11, 22)
Christian Heimesc3f30c42008-02-22 16:37:40 +0000634 >>> p.x + p.y # fields also accessible by name
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000635 33
636 >>> p # readable __repr__ with a name=value style
637 Point(x=11, y=22)
Georg Brandl116aa622007-08-15 14:28:22 +0000638
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000639Named tuples are especially useful for assigning field names to result tuples returned
640by the :mod:`csv` or :mod:`sqlite3` modules::
641
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000642 EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
Georg Brandl9afde1c2007-11-01 20:32:30 +0000643
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000644 import csv
Christian Heimesfaf2f632008-01-06 16:59:19 +0000645 for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000646 print(emp.name, emp.title)
647
Georg Brandl9afde1c2007-11-01 20:32:30 +0000648 import sqlite3
649 conn = sqlite3.connect('/companydata')
650 cursor = conn.cursor()
651 cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
Christian Heimesfaf2f632008-01-06 16:59:19 +0000652 for emp in map(EmployeeRecord._make, cursor.fetchall()):
Christian Heimes00412232008-01-10 16:02:19 +0000653 print(emp.name, emp.title)
Georg Brandl9afde1c2007-11-01 20:32:30 +0000654
Christian Heimes99170a52007-12-19 02:07:34 +0000655In addition to the methods inherited from tuples, named tuples support
Christian Heimes2380ac72008-01-09 00:17:24 +0000656three additional methods and one attribute. To prevent conflicts with
657field names, the method and attribute names start with an underscore.
Christian Heimes99170a52007-12-19 02:07:34 +0000658
Benjamin Peterson0b9fb802010-07-18 14:23:36 +0000659.. classmethod:: somenamedtuple._make(iterable)
Christian Heimes99170a52007-12-19 02:07:34 +0000660
Christian Heimesfaf2f632008-01-06 16:59:19 +0000661 Class method that makes a new instance from an existing sequence or iterable.
Christian Heimes99170a52007-12-19 02:07:34 +0000662
Christian Heimesfe337bf2008-03-23 21:54:12 +0000663.. doctest::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000664
Christian Heimesfaf2f632008-01-06 16:59:19 +0000665 >>> t = [11, 22]
666 >>> Point._make(t)
667 Point(x=11, y=22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000668
Christian Heimes790c8232008-01-07 21:14:23 +0000669.. method:: somenamedtuple._asdict()
Georg Brandl9afde1c2007-11-01 20:32:30 +0000670
Raymond Hettingera4f52b12009-03-02 22:28:31 +0000671 Return a new :class:`OrderedDict` which maps field names to their corresponding
672 values::
Georg Brandl9afde1c2007-11-01 20:32:30 +0000673
Christian Heimes0449f632007-12-15 01:27:15 +0000674 >>> p._asdict()
Raymond Hettingera4f52b12009-03-02 22:28:31 +0000675 OrderedDict([('x', 11), ('y', 22)])
676
Raymond Hettingera88e4da2009-03-03 05:12:27 +0000677 .. versionchanged:: 3.1
Raymond Hettingera4f52b12009-03-02 22:28:31 +0000678 Returns an :class:`OrderedDict` instead of a regular :class:`dict`.
Christian Heimesfe337bf2008-03-23 21:54:12 +0000679
Christian Heimes790c8232008-01-07 21:14:23 +0000680.. method:: somenamedtuple._replace(kwargs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000681
Christian Heimesfe337bf2008-03-23 21:54:12 +0000682 Return a new instance of the named tuple replacing specified fields with new
683 values:
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000684
685::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000686
687 >>> p = Point(x=11, y=22)
Christian Heimes0449f632007-12-15 01:27:15 +0000688 >>> p._replace(x=33)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689 Point(x=33, y=22)
690
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000691 >>> for partnum, record in inventory.items():
Christian Heimes454f37b2008-01-10 00:10:02 +0000692 ... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000693
Christian Heimes790c8232008-01-07 21:14:23 +0000694.. attribute:: somenamedtuple._fields
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000695
Christian Heimes2380ac72008-01-09 00:17:24 +0000696 Tuple of strings listing the field names. Useful for introspection
Georg Brandl9afde1c2007-11-01 20:32:30 +0000697 and for creating new named tuple types from existing named tuples.
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000698
Christian Heimesfe337bf2008-03-23 21:54:12 +0000699.. doctest::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000700
Christian Heimes0449f632007-12-15 01:27:15 +0000701 >>> p._fields # view the field names
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000702 ('x', 'y')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000703
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000704 >>> Color = namedtuple('Color', 'red green blue')
Christian Heimes0449f632007-12-15 01:27:15 +0000705 >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000706 >>> Pixel(11, 22, 128, 255, 0)
Christian Heimes454f37b2008-01-10 00:10:02 +0000707 Pixel(x=11, y=22, red=128, green=255, blue=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000708
Christian Heimes0449f632007-12-15 01:27:15 +0000709To retrieve a field whose name is stored in a string, use the :func:`getattr`
Christian Heimesfe337bf2008-03-23 21:54:12 +0000710function:
Christian Heimes0449f632007-12-15 01:27:15 +0000711
712 >>> getattr(p, 'x')
713 11
714
Raymond Hettinger651453a2009-02-11 00:20:02 +0000715To convert a dictionary to a named tuple, use the double-star-operator
716(as described in :ref:`tut-unpacking-arguments`):
Christian Heimes99170a52007-12-19 02:07:34 +0000717
718 >>> d = {'x': 11, 'y': 22}
719 >>> Point(**d)
720 Point(x=11, y=22)
721
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000722Since a named tuple is a regular Python class, it is easy to add or change
Christian Heimes043d6f62008-01-07 17:19:16 +0000723functionality with a subclass. Here is how to add a calculated field and
Christian Heimesfe337bf2008-03-23 21:54:12 +0000724a fixed-width print format:
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000725
Christian Heimes043d6f62008-01-07 17:19:16 +0000726 >>> class Point(namedtuple('Point', 'x y')):
Christian Heimes25bb7832008-01-11 16:17:00 +0000727 ... __slots__ = ()
Christian Heimes454f37b2008-01-10 00:10:02 +0000728 ... @property
729 ... def hypot(self):
730 ... return (self.x ** 2 + self.y ** 2) ** 0.5
731 ... def __str__(self):
Christian Heimes25bb7832008-01-11 16:17:00 +0000732 ... 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 +0000733
Georg Brandl0df79792008-10-04 18:33:26 +0000734 >>> for p in Point(3, 4), Point(14, 5/7):
Christian Heimes00412232008-01-10 16:02:19 +0000735 ... print(p)
Christian Heimes25bb7832008-01-11 16:17:00 +0000736 Point: x= 3.000 y= 4.000 hypot= 5.000
737 Point: x=14.000 y= 0.714 hypot=14.018
Christian Heimes043d6f62008-01-07 17:19:16 +0000738
Georg Brandlaf5c2382009-12-28 08:02:38 +0000739The subclass shown above sets ``__slots__`` to an empty tuple. This helps
Christian Heimes679db4a2008-01-18 09:56:22 +0000740keep memory requirements low by preventing the creation of instance dictionaries.
741
Christian Heimes2380ac72008-01-09 00:17:24 +0000742
743Subclassing is not useful for adding new, stored fields. Instead, simply
Christian Heimesfe337bf2008-03-23 21:54:12 +0000744create a new named tuple type from the :attr:`_fields` attribute:
Christian Heimes2380ac72008-01-09 00:17:24 +0000745
Christian Heimes25bb7832008-01-11 16:17:00 +0000746 >>> Point3D = namedtuple('Point3D', Point._fields + ('z',))
Christian Heimes2380ac72008-01-09 00:17:24 +0000747
748Default values can be implemented by using :meth:`_replace` to
Christian Heimesfe337bf2008-03-23 21:54:12 +0000749customize a prototype instance:
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000750
751 >>> Account = namedtuple('Account', 'owner balance transaction_count')
Christian Heimes587c2bf2008-01-19 16:21:02 +0000752 >>> default_account = Account('<owner name>', 0.0, 0)
753 >>> johns_account = default_account._replace(owner='John')
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000754
Christian Heimese4ca8152008-05-08 17:18:53 +0000755Enumerated constants can be implemented with named tuples, but it is simpler
756and more efficient to use a simple class declaration:
757
758 >>> Status = namedtuple('Status', 'open pending closed')._make(range(3))
759 >>> Status.open, Status.pending, Status.closed
760 (0, 1, 2)
761 >>> class Status:
762 ... open, pending, closed = range(3)
763
Raymond Hettinger651453a2009-02-11 00:20:02 +0000764.. seealso::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000765
Raymond Hettinger651453a2009-02-11 00:20:02 +0000766 `Named tuple recipe <http://code.activestate.com/recipes/500261/>`_
767 adapted for Python 2.4.
Raymond Hettingere4c96ad2008-02-06 01:23:58 +0000768
769
Raymond Hettinger2d32f632009-03-02 21:24:57 +0000770:class:`OrderedDict` objects
771----------------------------
772
773Ordered dictionaries are just like regular dictionaries but they remember the
774order that items were inserted. When iterating over an ordered dictionary,
775the items are returned in the order their keys were first added.
776
777.. class:: OrderedDict([items])
778
779 Return an instance of a dict subclass, supporting the usual :class:`dict`
780 methods. An *OrderedDict* is a dict that remembers the order that keys
781 were first inserted. If a new entry overwrites an existing entry, the
782 original insertion position is left unchanged. Deleting an entry and
783 reinserting it will move it to the end.
784
Benjamin Petersond45bf582009-03-02 21:44:54 +0000785 .. versionadded:: 3.1
Raymond Hettinger2d32f632009-03-02 21:24:57 +0000786
Benjamin Petersond319ad52010-07-18 14:27:02 +0000787 .. method:: popitem(last=True)
Raymond Hettingerdc879f02009-03-19 20:30:56 +0000788
Benjamin Petersond319ad52010-07-18 14:27:02 +0000789 The :meth:`popitem` method for ordered dictionaries returns and removes a
790 (key, value) pair. The pairs are returned in LIFO order if *last* is true
791 or FIFO order if false.
Raymond Hettinger2d32f632009-03-02 21:24:57 +0000792
Raymond Hettingere9091502009-05-19 17:40:07 +0000793In addition to the usual mapping methods, ordered dictionaries also support
794reverse iteration using :func:`reversed`.
795
Raymond Hettinger2d32f632009-03-02 21:24:57 +0000796Equality tests between :class:`OrderedDict` objects are order-sensitive
797and are implemented as ``list(od1.items())==list(od2.items())``.
798Equality tests between :class:`OrderedDict` objects and other
799:class:`Mapping` objects are order-insensitive like regular dictionaries.
800This allows :class:`OrderedDict` objects to be substituted anywhere a
801regular dictionary is used.
802
Raymond Hettinger36180782009-04-09 22:34:23 +0000803The :class:`OrderedDict` constructor and :meth:`update` method both accept
804keyword arguments, but their order is lost because Python's function call
805semantics pass-in keyword arguments using a regular unordered dictionary.
806
Raymond Hettingerdc879f02009-03-19 20:30:56 +0000807.. seealso::
808
809 `Equivalent OrderedDict recipe <http://code.activestate.com/recipes/576693/>`_
810 that runs on Python 2.4 or later.
811
Raymond Hettinger0e312012009-11-10 18:35:46 +0000812Since an ordered dictionary remembers its insertion order, it can be used
813in conjuction with sorting to make a sorted dictionary::
814
815 >>> # regular unsorted dictionary
816 >>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
817
818 >>> # dictionary sorted by key
819 >>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
820 OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
821
822 >>> # dictionary sorted by value
823 >>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
824 OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
825
826 >>> # dictionary sorted by length of the key string
827 >>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
828 OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
829
830The new sorted dictionaries maintain their sort order when entries
831are deleted. But when new keys are added, the keys are appended
832to the end and the sort is not maintained.
833
Raymond Hettinger4821ef82010-07-31 10:14:41 +0000834It is also straight-forward to create an ordered dictionary variant
835that the remembers the order the keys were *last* inserted.
836If a new entry overwrites an existing entry, the
837original insertion position is changed and moved to the end::
838
839 class LastUpdatedOrderedDict(OrderedDict):
840 'Store items is the order the keys were last added'
841 def __setitem__(self, key, value):
842 if key in self:
843 del self[key]
844 OrderedDict.__setitem__(self, key, value)
845
Raymond Hettingere4c96ad2008-02-06 01:23:58 +0000846
847:class:`UserDict` objects
Mark Summerfield8f2d0062008-02-06 13:30:44 +0000848-------------------------
Raymond Hettingere4c96ad2008-02-06 01:23:58 +0000849
Georg Brandl48310cd2009-01-03 21:18:54 +0000850The class, :class:`UserDict` acts as a wrapper around dictionary objects.
851The need for this class has been partially supplanted by the ability to
Raymond Hettingere4c96ad2008-02-06 01:23:58 +0000852subclass directly from :class:`dict`; however, this class can be easier
853to work with because the underlying dictionary is accessible as an
854attribute.
855
856.. class:: UserDict([initialdata])
857
858 Class that simulates a dictionary. The instance's contents are kept in a
859 regular dictionary, which is accessible via the :attr:`data` attribute of
860 :class:`UserDict` instances. If *initialdata* is provided, :attr:`data` is
861 initialized with its contents; note that a reference to *initialdata* will not
862 be kept, allowing it be used for other purposes.
863
Benjamin Petersond319ad52010-07-18 14:27:02 +0000864 In addition to supporting the methods and operations of mappings,
865 :class:`UserDict` instances provide the following attribute:
Raymond Hettingere4c96ad2008-02-06 01:23:58 +0000866
Benjamin Petersond319ad52010-07-18 14:27:02 +0000867 .. attribute:: data
Raymond Hettingere4c96ad2008-02-06 01:23:58 +0000868
Benjamin Petersond319ad52010-07-18 14:27:02 +0000869 A real dictionary used to store the contents of the :class:`UserDict`
870 class.
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000871
872
873
874:class:`UserList` objects
875-------------------------
876
877This class acts as a wrapper around list objects. It is a useful base class
Georg Brandl48310cd2009-01-03 21:18:54 +0000878for your own list-like classes which can inherit from them and override
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000879existing methods or add new ones. In this way, one can add new behaviors to
880lists.
881
Georg Brandl48310cd2009-01-03 21:18:54 +0000882The need for this class has been partially supplanted by the ability to
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000883subclass directly from :class:`list`; however, this class can be easier
884to work with because the underlying list is accessible as an attribute.
885
886.. class:: UserList([list])
887
888 Class that simulates a list. The instance's contents are kept in a regular
889 list, which is accessible via the :attr:`data` attribute of :class:`UserList`
890 instances. The instance's contents are initially set to a copy of *list*,
891 defaulting to the empty list ``[]``. *list* can be any iterable, for
892 example a real Python list or a :class:`UserList` object.
893
Benjamin Petersond319ad52010-07-18 14:27:02 +0000894 In addition to supporting the methods and operations of mutable sequences,
895 :class:`UserList` instances provide the following attribute:
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000896
Benjamin Petersond319ad52010-07-18 14:27:02 +0000897 .. attribute:: data
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000898
Benjamin Petersond319ad52010-07-18 14:27:02 +0000899 A real :class:`list` object used to store the contents of the
900 :class:`UserList` class.
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000901
902**Subclassing requirements:** Subclasses of :class:`UserList` are expect to
903offer a constructor which can be called with either no arguments or one
904argument. List operations which return a new sequence attempt to create an
905instance of the actual implementation class. To do so, it assumes that the
906constructor can be called with a single parameter, which is a sequence object
907used as a data source.
908
909If a derived class does not wish to comply with this requirement, all of the
910special methods supported by this class will need to be overridden; please
911consult the sources for information about the methods which need to be provided
912in that case.
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000913
914:class:`UserString` objects
Christian Heimesc3f30c42008-02-22 16:37:40 +0000915---------------------------
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000916
Georg Brandl48310cd2009-01-03 21:18:54 +0000917The class, :class:`UserString` acts as a wrapper around string objects.
918The need for this class has been partially supplanted by the ability to
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000919subclass directly from :class:`str`; however, this class can be easier
920to work with because the underlying string is accessible as an
921attribute.
922
923.. class:: UserString([sequence])
924
925 Class that simulates a string or a Unicode string object. The instance's
Georg Brandl48310cd2009-01-03 21:18:54 +0000926 content is kept in a regular string object, which is accessible via the
927 :attr:`data` attribute of :class:`UserString` instances. The instance's
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000928 contents are initially set to a copy of *sequence*. The *sequence* can
929 be an instance of :class:`bytes`, :class:`str`, :class:`UserString` (or a
930 subclass) or an arbitrary sequence which can be converted into a string using
931 the built-in :func:`str` function.
Raymond Hettingera6b76ba2010-08-08 00:29:08 +0000932
933
934ABCs - abstract base classes
935----------------------------
936
937The collections module offers the following ABCs:
938
939========================= ===================== ====================== ====================================================
940ABC Inherits Abstract Methods Mixin Methods
941========================= ===================== ====================== ====================================================
942:class:`Container` ``__contains__``
943:class:`Hashable` ``__hash__``
944:class:`Iterable` ``__iter__``
945:class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__``
946:class:`Sized` ``__len__``
947:class:`Callable` ``__call__``
948
949:class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``. ``__iter__``, ``__reversed__``.
950 :class:`Iterable`, ``index``, and ``count``
951 :class:`Container`
952
953:class:`MutableSequence` :class:`Sequence` ``__setitem__`` Inherited Sequence methods and
954 ``__delitem__``, ``append``, ``reverse``, ``extend``, ``pop``,
955 and ``insert`` ``remove``, and ``__iadd__``
956
957:class:`Set` :class:`Sized`, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
958 :class:`Iterable`, ``__gt__``, ``__ge__``, ``__and__``, ``__or__``
959 :class:`Container` ``__sub__``, ``__xor__``, and ``isdisjoint``
960
961:class:`MutableSet` :class:`Set` ``add`` and Inherited Set methods and
962 ``discard`` ``clear``, ``pop``, ``remove``, ``__ior__``,
963 ``__iand__``, ``__ixor__``, and ``__isub__``
964
965:class:`Mapping` :class:`Sized`, ``__getitem__`` ``__contains__``, ``keys``, ``items``, ``values``,
966 :class:`Iterable`, ``get``, ``__eq__``, and ``__ne__``
967 :class:`Container`
968
969:class:`MutableMapping` :class:`Mapping` ``__setitem__`` and Inherited Mapping methods and
970 ``__delitem__`` ``pop``, ``popitem``, ``clear``, ``update``,
971 and ``setdefault``
972
973
974:class:`MappingView` :class:`Sized` ``__len__``
975:class:`KeysView` :class:`MappingView`, ``__contains__``,
976 :class:`Set` ``__iter__``
977:class:`ItemsView` :class:`MappingView`, ``__contains__``,
978 :class:`Set` ``__iter__``
979:class:`ValuesView` :class:`MappingView` ``__contains__``, ``__iter__``
980========================= ===================== ====================== ====================================================
981
982These ABCs allow us to ask classes or instances if they provide
983particular functionality, for example::
984
985 size = None
986 if isinstance(myvar, collections.Sized):
987 size = len(myvar)
988
989Several of the ABCs are also useful as mixins that make it easier to develop
990classes supporting container APIs. For example, to write a class supporting
991the full :class:`Set` API, it only necessary to supply the three underlying
992abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`.
993The ABC supplies the remaining methods such as :meth:`__and__` and
994:meth:`isdisjoint` ::
995
996 class ListBasedSet(collections.Set):
997 ''' Alternate set implementation favoring space over speed
998 and not requiring the set elements to be hashable. '''
999 def __init__(self, iterable):
1000 self.elements = lst = []
1001 for value in iterable:
1002 if value not in lst:
1003 lst.append(value)
1004 def __iter__(self):
1005 return iter(self.elements)
1006 def __contains__(self, value):
1007 return value in self.elements
1008 def __len__(self):
1009 return len(self.elements)
1010
1011 s1 = ListBasedSet('abcdef')
1012 s2 = ListBasedSet('defghi')
1013 overlap = s1 & s2 # The __and__() method is supported automatically
1014
1015Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
1016
1017(1)
1018 Since some set operations create new sets, the default mixin methods need
1019 a way to create new instances from an iterable. The class constructor is
1020 assumed to have a signature in the form ``ClassName(iterable)``.
1021 That assumption is factored-out to an internal classmethod called
1022 :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
1023 If the :class:`Set` mixin is being used in a class with a different
1024 constructor signature, you will need to override :meth:`from_iterable`
1025 with a classmethod that can construct new instances from
1026 an iterable argument.
1027
1028(2)
1029 To override the comparisons (presumably for speed, as the
1030 semantics are fixed), redefine :meth:`__le__` and
1031 then the other operations will automatically follow suit.
1032
1033(3)
1034 The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value
1035 for the set; however, :meth:`__hash__` is not defined because not all sets
1036 are hashable or immutable. To add set hashabilty using mixins,
1037 inherit from both :meth:`Set` and :meth:`Hashable`, then define
1038 ``__hash__ = Set._hash``.
1039
1040.. seealso::
1041
1042 * `OrderedSet recipe <http://code.activestate.com/recipes/576694/>`_ for an
1043 example built on :class:`MutableSet`.
1044
1045 * For more about ABCs, see the :mod:`abc` module and :pep:`3119`.