blob: d218a9be530d7f5e876370645bf2685d01612529 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`collections` --- High-performance container datatypes
3===========================================================
4
5.. module:: collections
6 :synopsis: High-performance datatypes
7.. moduleauthor:: Raymond Hettinger <python@rcn.com>
8.. sectionauthor:: Raymond Hettinger <python@rcn.com>
9
10
Georg Brandl116aa622007-08-15 14:28:22 +000011This module implements high-performance container datatypes. Currently,
12there are two datatypes, :class:`deque` and :class:`defaultdict`, and
Guido van Rossum3d392eb2007-11-16 00:35:22 +000013one datatype factory function, :func:`namedtuple`. Python already
Georg Brandl116aa622007-08-15 14:28:22 +000014includes built-in containers, :class:`dict`, :class:`list`,
15:class:`set`, and :class:`tuple`. In addition, the optional :mod:`bsddb`
16module has a :meth:`bsddb.btopen` method that can be used to create in-memory
17or file based ordered dictionaries with string keys.
18
19Future editions of the standard library may include balanced trees and
20ordered dictionaries.
21
Mark Summerfield08898b42007-09-05 08:43:04 +000022In addition to containers, the collections module provides some ABCs
23(abstract base classes) that can be used to test whether
24a class provides a particular interface, for example, is it hashable or
25a mapping. The ABCs provided include those in the following table:
26
27===================================== ========================================
28ABC Notes
29===================================== ========================================
30:class:`collections.Container` Defines ``__contains__()``
31:class:`collections.Hashable` Defines ``__hash__()``
32:class:`collections.Iterable` Defines ``__iter__()``
33:class:`collections.Iterator` Derived from :class:`Iterable` and in
34 addition defines ``__next__()``
Raymond Hettingere4c96ad2008-02-06 01:23:58 +000035:class:`collections.Sized` Defines ``__len__()``
Mark Summerfield08898b42007-09-05 08:43:04 +000036:class:`collections.Mapping` Derived from :class:`Container`,
37 :class:`Iterable`,
38 and :class:`Sized`, and in addition
39 defines ``__getitem__()``, ``get()``,
40 ``__contains__()``, ``__len__()``,
Raymond Hettingere4c96ad2008-02-06 01:23:58 +000041 ``__eq__()``, ``__ne__()``,
Mark Summerfield08898b42007-09-05 08:43:04 +000042 ``__iter__()``, ``keys()``,
43 ``items()``, and ``values()``
44:class:`collections.MutableMapping` Derived from :class:`Mapping`
Mark Summerfield08898b42007-09-05 08:43:04 +000045:class:`collections.Sequence` Derived from :class:`Container`,
46 :class:`Iterable`, and :class:`Sized`,
47 and in addition defines
Raymond Hettingere4c96ad2008-02-06 01:23:58 +000048 ``__getitem__()`
49:class:`collections.MutableSequence` Derived from :class:`Sequence`
50:class:`collections.Set` Derived from :class:`Container`, :class:`Iterable`, :class:`Sized`.
51 add in addition defines
52 ``__le__()``, ``__lt__()``, ``__eq__()``,
53 ``__and__()``, ``__or__()``, ``__sub__()``,
54 ``__xor__()``, and ``isdisjoint()``,
55:class:`collections.MutableSet` Derived from :class:`Set` and in
56 addition defines ``add()``,
57 ``clear()``, ``discard()``, ``pop()``,
58 ``remove()``, ``__ior__()``, ``__iand__()``,
59 ``__ixor__()``, and ``__isub__()``
60
Mark Summerfield08898b42007-09-05 08:43:04 +000061===================================== ========================================
62
Georg Brandl84df79b2008-01-05 19:25:53 +000063.. XXX Have not included them all and the notes are incomplete
Mark Summerfield08898b42007-09-05 08:43:04 +000064.. Deliberately did one row wide to get a neater output
65
66These ABCs allow us to ask classes or instances if they provide
67particular functionality, for example::
68
69 from collections import Sized
70
71 size = None
72 if isinstance(myvar, Sized):
73 size = len(myvar)
74
75(For more about ABCs, see the :mod:`abc` module and :pep:`3119`.)
76
77
Georg Brandl116aa622007-08-15 14:28:22 +000078
79.. _deque-objects:
80
81:class:`deque` objects
82----------------------
83
84
Georg Brandl9afde1c2007-11-01 20:32:30 +000085.. class:: deque([iterable[, maxlen]])
Georg Brandl116aa622007-08-15 14:28:22 +000086
87 Returns a new deque object initialized left-to-right (using :meth:`append`) with
88 data from *iterable*. If *iterable* is not specified, the new deque is empty.
89
90 Deques are a generalization of stacks and queues (the name is pronounced "deck"
91 and is short for "double-ended queue"). Deques support thread-safe, memory
92 efficient appends and pops from either side of the deque with approximately the
93 same O(1) performance in either direction.
94
95 Though :class:`list` objects support similar operations, they are optimized for
96 fast fixed-length operations and incur O(n) memory movement costs for
97 ``pop(0)`` and ``insert(0, v)`` operations which change both the size and
98 position of the underlying data representation.
99
Georg Brandl116aa622007-08-15 14:28:22 +0000100
Georg Brandl9afde1c2007-11-01 20:32:30 +0000101 If *maxlen* is not specified or is *None*, deques may grow to an
102 arbitrary length. Otherwise, the deque is bounded to the specified maximum
103 length. Once a bounded length deque is full, when new items are added, a
104 corresponding number of items are discarded from the opposite end. Bounded
105 length deques provide functionality similar to the ``tail`` filter in
106 Unix. They are also useful for tracking transactions and other pools of data
107 where only the most recent activity is of interest.
108
Georg Brandl9afde1c2007-11-01 20:32:30 +0000109
Georg Brandl116aa622007-08-15 14:28:22 +0000110Deque objects support the following methods:
111
Georg Brandl116aa622007-08-15 14:28:22 +0000112.. method:: deque.append(x)
113
114 Add *x* to the right side of the deque.
115
116
117.. method:: deque.appendleft(x)
118
119 Add *x* to the left side of the deque.
120
121
122.. method:: deque.clear()
123
124 Remove all elements from the deque leaving it with length 0.
125
126
127.. method:: deque.extend(iterable)
128
129 Extend the right side of the deque by appending elements from the iterable
130 argument.
131
132
133.. method:: deque.extendleft(iterable)
134
135 Extend the left side of the deque by appending elements from *iterable*. Note,
136 the series of left appends results in reversing the order of elements in the
137 iterable argument.
138
139
140.. method:: deque.pop()
141
142 Remove and return an element from the right side of the deque. If no elements
143 are present, raises an :exc:`IndexError`.
144
145
146.. method:: deque.popleft()
147
148 Remove and return an element from the left side of the deque. If no elements are
149 present, raises an :exc:`IndexError`.
150
151
152.. method:: deque.remove(value)
153
154 Removed the first occurrence of *value*. If not found, raises a
155 :exc:`ValueError`.
156
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158.. method:: deque.rotate(n)
159
160 Rotate the deque *n* steps to the right. If *n* is negative, rotate to the
161 left. Rotating one step to the right is equivalent to:
162 ``d.appendleft(d.pop())``.
163
164In addition to the above, deques support iteration, pickling, ``len(d)``,
165``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with
166the :keyword:`in` operator, and subscript references such as ``d[-1]``.
167
168Example::
169
170 >>> from collections import deque
171 >>> d = deque('ghi') # make a new deque with three items
172 >>> for elem in d: # iterate over the deque's elements
Georg Brandl6911e3c2007-09-04 07:15:32 +0000173 ... print(elem.upper())
Georg Brandl116aa622007-08-15 14:28:22 +0000174 G
175 H
176 I
177
178 >>> d.append('j') # add a new entry to the right side
179 >>> d.appendleft('f') # add a new entry to the left side
180 >>> d # show the representation of the deque
181 deque(['f', 'g', 'h', 'i', 'j'])
182
183 >>> d.pop() # return and remove the rightmost item
184 'j'
185 >>> d.popleft() # return and remove the leftmost item
186 'f'
187 >>> list(d) # list the contents of the deque
188 ['g', 'h', 'i']
189 >>> d[0] # peek at leftmost item
190 'g'
191 >>> d[-1] # peek at rightmost item
192 'i'
193
194 >>> list(reversed(d)) # list the contents of a deque in reverse
195 ['i', 'h', 'g']
196 >>> 'h' in d # search the deque
197 True
198 >>> d.extend('jkl') # add multiple elements at once
199 >>> d
200 deque(['g', 'h', 'i', 'j', 'k', 'l'])
201 >>> d.rotate(1) # right rotation
202 >>> d
203 deque(['l', 'g', 'h', 'i', 'j', 'k'])
204 >>> d.rotate(-1) # left rotation
205 >>> d
206 deque(['g', 'h', 'i', 'j', 'k', 'l'])
207
208 >>> deque(reversed(d)) # make a new deque in reverse order
209 deque(['l', 'k', 'j', 'i', 'h', 'g'])
210 >>> d.clear() # empty the deque
211 >>> d.pop() # cannot pop from an empty deque
212 Traceback (most recent call last):
213 File "<pyshell#6>", line 1, in -toplevel-
214 d.pop()
215 IndexError: pop from an empty deque
216
217 >>> d.extendleft('abc') # extendleft() reverses the input order
218 >>> d
219 deque(['c', 'b', 'a'])
220
221
222.. _deque-recipes:
223
Georg Brandl9afde1c2007-11-01 20:32:30 +0000224:class:`deque` Recipes
225^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000226
227This section shows various approaches to working with deques.
228
229The :meth:`rotate` method provides a way to implement :class:`deque` slicing and
230deletion. For example, a pure python implementation of ``del d[n]`` relies on
231the :meth:`rotate` method to position elements to be popped::
232
233 def delete_nth(d, n):
234 d.rotate(-n)
235 d.popleft()
236 d.rotate(n)
237
238To implement :class:`deque` slicing, use a similar approach applying
239:meth:`rotate` to bring a target element to the left side of the deque. Remove
240old entries with :meth:`popleft`, add new entries with :meth:`extend`, and then
241reverse the rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000242With minor variations on that approach, it is easy to implement Forth style
243stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``,
244``rot``, and ``roll``.
245
Georg Brandl116aa622007-08-15 14:28:22 +0000246Multi-pass data reduction algorithms can be succinctly expressed and efficiently
247coded by extracting elements with multiple calls to :meth:`popleft`, applying
Georg Brandl9afde1c2007-11-01 20:32:30 +0000248a reduction function, and calling :meth:`append` to add the result back to the
249deque.
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251For example, building a balanced binary tree of nested lists entails reducing
252two adjacent nodes into one by grouping them in a list::
253
254 >>> def maketree(iterable):
255 ... d = deque(iterable)
256 ... while len(d) > 1:
257 ... pair = [d.popleft(), d.popleft()]
258 ... d.append(pair)
259 ... return list(d)
260 ...
Georg Brandl6911e3c2007-09-04 07:15:32 +0000261 >>> print(maketree('abcdefgh'))
Georg Brandl116aa622007-08-15 14:28:22 +0000262 [[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
263
Georg Brandl9afde1c2007-11-01 20:32:30 +0000264Bounded length deques provide functionality similar to the ``tail`` filter
265in Unix::
Georg Brandl116aa622007-08-15 14:28:22 +0000266
Georg Brandl9afde1c2007-11-01 20:32:30 +0000267 def tail(filename, n=10):
268 'Return the last n lines of a file'
269 return deque(open(filename), n)
Georg Brandl116aa622007-08-15 14:28:22 +0000270
271.. _defaultdict-objects:
272
273:class:`defaultdict` objects
274----------------------------
275
276
277.. class:: defaultdict([default_factory[, ...]])
278
279 Returns a new dictionary-like object. :class:`defaultdict` is a subclass of the
280 builtin :class:`dict` class. It overrides one method and adds one writable
281 instance variable. The remaining functionality is the same as for the
282 :class:`dict` class and is not documented here.
283
284 The first argument provides the initial value for the :attr:`default_factory`
285 attribute; it defaults to ``None``. All remaining arguments are treated the same
286 as if they were passed to the :class:`dict` constructor, including keyword
287 arguments.
288
Georg Brandl116aa622007-08-15 14:28:22 +0000289
290:class:`defaultdict` objects support the following method in addition to the
291standard :class:`dict` operations:
292
Georg Brandl116aa622007-08-15 14:28:22 +0000293.. method:: defaultdict.__missing__(key)
294
295 If the :attr:`default_factory` attribute is ``None``, this raises an
296 :exc:`KeyError` exception with the *key* as argument.
297
298 If :attr:`default_factory` is not ``None``, it is called without arguments to
299 provide a default value for the given *key*, this value is inserted in the
300 dictionary for the *key*, and returned.
301
302 If calling :attr:`default_factory` raises an exception this exception is
303 propagated unchanged.
304
305 This method is called by the :meth:`__getitem__` method of the :class:`dict`
306 class when the requested key is not found; whatever it returns or raises is then
307 returned or raised by :meth:`__getitem__`.
308
309:class:`defaultdict` objects support the following instance variable:
310
311
312.. attribute:: defaultdict.default_factory
313
314 This attribute is used by the :meth:`__missing__` method; it is initialized from
315 the first argument to the constructor, if present, or to ``None``, if absent.
316
317
318.. _defaultdict-examples:
319
320:class:`defaultdict` Examples
321^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
322
323Using :class:`list` as the :attr:`default_factory`, it is easy to group a
324sequence of key-value pairs into a dictionary of lists::
325
326 >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
327 >>> d = defaultdict(list)
328 >>> for k, v in s:
329 ... d[k].append(v)
330 ...
331 >>> d.items()
332 [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
333
334When each key is encountered for the first time, it is not already in the
335mapping; so an entry is automatically created using the :attr:`default_factory`
336function which returns an empty :class:`list`. The :meth:`list.append`
337operation then attaches the value to the new list. When keys are encountered
338again, the look-up proceeds normally (returning the list for that key) and the
339:meth:`list.append` operation adds another value to the list. This technique is
340simpler and faster than an equivalent technique using :meth:`dict.setdefault`::
341
342 >>> d = {}
343 >>> for k, v in s:
344 ... d.setdefault(k, []).append(v)
345 ...
346 >>> d.items()
347 [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
348
349Setting the :attr:`default_factory` to :class:`int` makes the
350:class:`defaultdict` useful for counting (like a bag or multiset in other
351languages)::
352
353 >>> s = 'mississippi'
354 >>> d = defaultdict(int)
355 >>> for k in s:
356 ... d[k] += 1
357 ...
358 >>> d.items()
359 [('i', 4), ('p', 2), ('s', 4), ('m', 1)]
360
361When a letter is first encountered, it is missing from the mapping, so the
362:attr:`default_factory` function calls :func:`int` to supply a default count of
363zero. The increment operation then builds up the count for each letter.
364
365The function :func:`int` which always returns zero is just a special case of
366constant functions. A faster and more flexible way to create constant functions
367is to use a lambda function which can supply any constant value (not just
368zero)::
369
370 >>> def constant_factory(value):
371 ... return lambda: value
372 >>> d = defaultdict(constant_factory('<missing>'))
373 >>> d.update(name='John', action='ran')
374 >>> '%(name)s %(action)s to %(object)s' % d
375 'John ran to <missing>'
376
377Setting the :attr:`default_factory` to :class:`set` makes the
378:class:`defaultdict` useful for building a dictionary of sets::
379
380 >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
381 >>> d = defaultdict(set)
382 >>> for k, v in s:
383 ... d[k].add(v)
384 ...
385 >>> d.items()
386 [('blue', set([2, 4])), ('red', set([1, 3]))]
387
388
389.. _named-tuple-factory:
390
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000391:func:`namedtuple` Factory Function for Tuples with Named Fields
Christian Heimes790c8232008-01-07 21:14:23 +0000392----------------------------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000393
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000394Named tuples assign meaning to each position in a tuple and allow for more readable,
395self-documenting code. They can be used wherever regular tuples are used, and
396they add the ability to access fields by name instead of position index.
Georg Brandl116aa622007-08-15 14:28:22 +0000397
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000398.. function:: namedtuple(typename, fieldnames, [verbose])
Georg Brandl116aa622007-08-15 14:28:22 +0000399
400 Returns a new tuple subclass named *typename*. The new subclass is used to
401 create tuple-like objects that have fields accessable by attribute lookup as
402 well as being indexable and iterable. Instances of the subclass also have a
403 helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__`
404 method which lists the tuple contents in a ``name=value`` format.
405
Georg Brandl9afde1c2007-11-01 20:32:30 +0000406 The *fieldnames* are a single string with each fieldname separated by whitespace
Christian Heimes25bb7832008-01-11 16:17:00 +0000407 and/or commas, for example ``'x y'`` or ``'x, y'``. Alternatively, *fieldnames*
408 can be a sequence of strings such as ``['x', 'y']``.
Georg Brandl9afde1c2007-11-01 20:32:30 +0000409
410 Any valid Python identifier may be used for a fieldname except for names
Christian Heimes0449f632007-12-15 01:27:15 +0000411 starting with an underscore. Valid identifiers consist of letters, digits,
412 and underscores but do not start with a digit or underscore and cannot be
Georg Brandlf6945182008-02-01 11:56:49 +0000413 a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*,
Georg Brandl9afde1c2007-11-01 20:32:30 +0000414 or *raise*.
Georg Brandl116aa622007-08-15 14:28:22 +0000415
Christian Heimes25bb7832008-01-11 16:17:00 +0000416 If *verbose* is true, the class definition is printed just before being built.
Georg Brandl116aa622007-08-15 14:28:22 +0000417
Georg Brandl9afde1c2007-11-01 20:32:30 +0000418 Named tuple instances do not have per-instance dictionaries, so they are
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000419 lightweight and require no more memory than regular tuples.
Georg Brandl116aa622007-08-15 14:28:22 +0000420
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000421Example::
Georg Brandl116aa622007-08-15 14:28:22 +0000422
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000423 >>> Point = namedtuple('Point', 'x y', verbose=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000424 class Point(tuple):
425 'Point(x, y)'
Christian Heimes0449f632007-12-15 01:27:15 +0000426
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000427 __slots__ = ()
Christian Heimes0449f632007-12-15 01:27:15 +0000428
Christian Heimesfaf2f632008-01-06 16:59:19 +0000429 _fields = ('x', 'y')
430
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000431 def __new__(cls, x, y):
432 return tuple.__new__(cls, (x, y))
Christian Heimes0449f632007-12-15 01:27:15 +0000433
Christian Heimesfaf2f632008-01-06 16:59:19 +0000434 @classmethod
435 def _make(cls, iterable):
436 'Make a new Point object from a sequence or iterable'
437 result = tuple.__new__(cls, iterable)
438 if len(result) != 2:
439 raise TypeError('Expected 2 arguments, got %d' % len(result))
440 return result
Christian Heimes99170a52007-12-19 02:07:34 +0000441
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000442 def __repr__(self):
443 return 'Point(x=%r, y=%r)' % self
Christian Heimes0449f632007-12-15 01:27:15 +0000444
Christian Heimes99170a52007-12-19 02:07:34 +0000445 def _asdict(t):
Christian Heimes0449f632007-12-15 01:27:15 +0000446 'Return a new dict which maps field names to their values'
Christian Heimes99170a52007-12-19 02:07:34 +0000447 return {'x': t[0], 'y': t[1]}
Christian Heimes0449f632007-12-15 01:27:15 +0000448
449 def _replace(self, **kwds):
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000450 'Return a new Point object replacing specified fields with new values'
Christian Heimesfaf2f632008-01-06 16:59:19 +0000451 result = self._make(map(kwds.pop, ('x', 'y'), self))
452 if kwds:
453 raise ValueError('Got unexpected field names: %r' % kwds.keys())
454 return result
Christian Heimes0449f632007-12-15 01:27:15 +0000455
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000456 x = property(itemgetter(0))
457 y = property(itemgetter(1))
Georg Brandl116aa622007-08-15 14:28:22 +0000458
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000459 >>> p = Point(11, y=22) # instantiate with positional or keyword arguments
Christian Heimes99170a52007-12-19 02:07:34 +0000460 >>> p[0] + p[1] # indexable like the plain tuple (11, 22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000461 33
462 >>> x, y = p # unpack like a regular tuple
463 >>> x, y
464 (11, 22)
465 >>> p.x + p.y # fields also accessable by name
466 33
467 >>> p # readable __repr__ with a name=value style
468 Point(x=11, y=22)
Georg Brandl116aa622007-08-15 14:28:22 +0000469
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000470Named tuples are especially useful for assigning field names to result tuples returned
471by the :mod:`csv` or :mod:`sqlite3` modules::
472
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000473 EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
Georg Brandl9afde1c2007-11-01 20:32:30 +0000474
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000475 import csv
Christian Heimesfaf2f632008-01-06 16:59:19 +0000476 for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000477 print(emp.name, emp.title)
478
Georg Brandl9afde1c2007-11-01 20:32:30 +0000479 import sqlite3
480 conn = sqlite3.connect('/companydata')
481 cursor = conn.cursor()
482 cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
Christian Heimesfaf2f632008-01-06 16:59:19 +0000483 for emp in map(EmployeeRecord._make, cursor.fetchall()):
Christian Heimes00412232008-01-10 16:02:19 +0000484 print(emp.name, emp.title)
Georg Brandl9afde1c2007-11-01 20:32:30 +0000485
Christian Heimes99170a52007-12-19 02:07:34 +0000486In addition to the methods inherited from tuples, named tuples support
Christian Heimes2380ac72008-01-09 00:17:24 +0000487three additional methods and one attribute. To prevent conflicts with
488field names, the method and attribute names start with an underscore.
Christian Heimes99170a52007-12-19 02:07:34 +0000489
Christian Heimes790c8232008-01-07 21:14:23 +0000490.. method:: somenamedtuple._make(iterable)
Christian Heimes99170a52007-12-19 02:07:34 +0000491
Christian Heimesfaf2f632008-01-06 16:59:19 +0000492 Class method that makes a new instance from an existing sequence or iterable.
Christian Heimes99170a52007-12-19 02:07:34 +0000493
494::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000495
Christian Heimesfaf2f632008-01-06 16:59:19 +0000496 >>> t = [11, 22]
497 >>> Point._make(t)
498 Point(x=11, y=22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000499
Christian Heimes790c8232008-01-07 21:14:23 +0000500.. method:: somenamedtuple._asdict()
Georg Brandl9afde1c2007-11-01 20:32:30 +0000501
502 Return a new dict which maps field names to their corresponding values:
503
504::
505
Christian Heimes0449f632007-12-15 01:27:15 +0000506 >>> p._asdict()
Georg Brandl9afde1c2007-11-01 20:32:30 +0000507 {'x': 11, 'y': 22}
508
Christian Heimes790c8232008-01-07 21:14:23 +0000509.. method:: somenamedtuple._replace(kwargs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000511 Return a new instance of the named tuple replacing specified fields with new values:
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000512
513::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000514
515 >>> p = Point(x=11, y=22)
Christian Heimes0449f632007-12-15 01:27:15 +0000516 >>> p._replace(x=33)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000517 Point(x=33, y=22)
518
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000519 >>> for partnum, record in inventory.items():
Christian Heimes454f37b2008-01-10 00:10:02 +0000520 ... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000521
Christian Heimes790c8232008-01-07 21:14:23 +0000522.. attribute:: somenamedtuple._fields
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000523
Christian Heimes2380ac72008-01-09 00:17:24 +0000524 Tuple of strings listing the field names. Useful for introspection
Georg Brandl9afde1c2007-11-01 20:32:30 +0000525 and for creating new named tuple types from existing named tuples.
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000526
527::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000528
Christian Heimes0449f632007-12-15 01:27:15 +0000529 >>> p._fields # view the field names
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000530 ('x', 'y')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000531
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000532 >>> Color = namedtuple('Color', 'red green blue')
Christian Heimes0449f632007-12-15 01:27:15 +0000533 >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000534 >>> Pixel(11, 22, 128, 255, 0)
Christian Heimes454f37b2008-01-10 00:10:02 +0000535 Pixel(x=11, y=22, red=128, green=255, blue=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000536
Christian Heimes0449f632007-12-15 01:27:15 +0000537To retrieve a field whose name is stored in a string, use the :func:`getattr`
Christian Heimes790c8232008-01-07 21:14:23 +0000538function::
Christian Heimes0449f632007-12-15 01:27:15 +0000539
540 >>> getattr(p, 'x')
541 11
542
Christian Heimes25bb7832008-01-11 16:17:00 +0000543To convert a dictionary to a named tuple, use the double-star-operator [#]_::
Christian Heimes99170a52007-12-19 02:07:34 +0000544
545 >>> d = {'x': 11, 'y': 22}
546 >>> Point(**d)
547 Point(x=11, y=22)
548
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000549Since a named tuple is a regular Python class, it is easy to add or change
Christian Heimes043d6f62008-01-07 17:19:16 +0000550functionality with a subclass. Here is how to add a calculated field and
551a fixed-width print format::
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000552
Christian Heimes043d6f62008-01-07 17:19:16 +0000553 >>> class Point(namedtuple('Point', 'x y')):
Christian Heimes25bb7832008-01-11 16:17:00 +0000554 ... __slots__ = ()
Christian Heimes454f37b2008-01-10 00:10:02 +0000555 ... @property
556 ... def hypot(self):
557 ... return (self.x ** 2 + self.y ** 2) ** 0.5
558 ... def __str__(self):
Christian Heimes25bb7832008-01-11 16:17:00 +0000559 ... 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 +0000560
Christian Heimes25bb7832008-01-11 16:17:00 +0000561 >>> for p in Point(3, 4), Point(14, 5/7.):
Christian Heimes00412232008-01-10 16:02:19 +0000562 ... print(p)
Christian Heimes790c8232008-01-07 21:14:23 +0000563
Christian Heimes25bb7832008-01-11 16:17:00 +0000564 Point: x= 3.000 y= 4.000 hypot= 5.000
565 Point: x=14.000 y= 0.714 hypot=14.018
Christian Heimes043d6f62008-01-07 17:19:16 +0000566
Christian Heimesaf98da12008-01-27 15:18:18 +0000567The subclass shown above sets ``__slots__`` to an empty tuple. This keeps
Christian Heimes679db4a2008-01-18 09:56:22 +0000568keep memory requirements low by preventing the creation of instance dictionaries.
569
Christian Heimes2380ac72008-01-09 00:17:24 +0000570
571Subclassing is not useful for adding new, stored fields. Instead, simply
572create a new named tuple type from the :attr:`_fields` attribute::
573
Christian Heimes25bb7832008-01-11 16:17:00 +0000574 >>> Point3D = namedtuple('Point3D', Point._fields + ('z',))
Christian Heimes2380ac72008-01-09 00:17:24 +0000575
576Default values can be implemented by using :meth:`_replace` to
Christian Heimes790c8232008-01-07 21:14:23 +0000577customize a prototype instance::
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000578
579 >>> Account = namedtuple('Account', 'owner balance transaction_count')
Christian Heimes587c2bf2008-01-19 16:21:02 +0000580 >>> default_account = Account('<owner name>', 0.0, 0)
581 >>> johns_account = default_account._replace(owner='John')
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000582
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000583.. rubric:: Footnotes
584
Christian Heimes99170a52007-12-19 02:07:34 +0000585.. [#] For information on the double-star-operator see
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000586 :ref:`tut-unpacking-arguments` and :ref:`calls`.
Raymond Hettingere4c96ad2008-02-06 01:23:58 +0000587
588
589
590:class:`UserDict` objects
591----------------------
592
593The class, :class:`UserDict` acts as a wrapper around dictionary objects.
594The need for this class has been partially supplanted by the ability to
595subclass directly from :class:`dict`; however, this class can be easier
596to work with because the underlying dictionary is accessible as an
597attribute.
598
599.. class:: UserDict([initialdata])
600
601 Class that simulates a dictionary. The instance's contents are kept in a
602 regular dictionary, which is accessible via the :attr:`data` attribute of
603 :class:`UserDict` instances. If *initialdata* is provided, :attr:`data` is
604 initialized with its contents; note that a reference to *initialdata* will not
605 be kept, allowing it be used for other purposes.
606
607In addition to supporting the methods and operations of mappings,
608:class:`UserDict` and :class:`IterableUserDict` instances
609provide the following attribute:
610
611.. attribute:: UserDict.data
612
613 A real dictionary used to store the contents of the :class:`UserDict` class.