blob: 628dbf54280f00a88deb144a372d75100122371b [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
11.. versionadded:: 2.4
12
13This module implements high-performance container datatypes. Currently,
14there are two datatypes, :class:`deque` and :class:`defaultdict`, and
Raymond Hettingereeeb9c42007-11-15 02:44:53 +000015one datatype factory function, :func:`namedtuple`. Python already
Georg Brandl8ec7f652007-08-15 14:28:01 +000016includes built-in containers, :class:`dict`, :class:`list`,
17:class:`set`, and :class:`tuple`. In addition, the optional :mod:`bsddb`
18module has a :meth:`bsddb.btopen` method that can be used to create in-memory
19or file based ordered dictionaries with string keys.
20
21Future editions of the standard library may include balanced trees and
22ordered dictionaries.
23
24.. versionchanged:: 2.5
25 Added :class:`defaultdict`.
26
27.. versionchanged:: 2.6
Raymond Hettingereeeb9c42007-11-15 02:44:53 +000028 Added :func:`namedtuple`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000029
30
31.. _deque-objects:
32
33:class:`deque` objects
34----------------------
35
36
Raymond Hettingera7fc4b12007-10-05 02:47:07 +000037.. class:: deque([iterable[, maxlen]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000038
39 Returns a new deque object initialized left-to-right (using :meth:`append`) with
40 data from *iterable*. If *iterable* is not specified, the new deque is empty.
41
42 Deques are a generalization of stacks and queues (the name is pronounced "deck"
43 and is short for "double-ended queue"). Deques support thread-safe, memory
44 efficient appends and pops from either side of the deque with approximately the
45 same O(1) performance in either direction.
46
47 Though :class:`list` objects support similar operations, they are optimized for
48 fast fixed-length operations and incur O(n) memory movement costs for
49 ``pop(0)`` and ``insert(0, v)`` operations which change both the size and
50 position of the underlying data representation.
51
52 .. versionadded:: 2.4
53
Raymond Hettinger68995862007-10-10 00:26:46 +000054 If *maxlen* is not specified or is *None*, deques may grow to an
Raymond Hettingera7fc4b12007-10-05 02:47:07 +000055 arbitrary length. Otherwise, the deque is bounded to the specified maximum
56 length. Once a bounded length deque is full, when new items are added, a
57 corresponding number of items are discarded from the opposite end. Bounded
58 length deques provide functionality similar to the ``tail`` filter in
59 Unix. They are also useful for tracking transactions and other pools of data
60 where only the most recent activity is of interest.
61
62 .. versionchanged:: 2.6
Georg Brandlb19be572007-12-29 10:57:00 +000063 Added *maxlen* parameter.
Raymond Hettingera7fc4b12007-10-05 02:47:07 +000064
Georg Brandl8ec7f652007-08-15 14:28:01 +000065Deque objects support the following methods:
66
67
68.. method:: deque.append(x)
69
70 Add *x* to the right side of the deque.
71
72
73.. method:: deque.appendleft(x)
74
75 Add *x* to the left side of the deque.
76
77
78.. method:: deque.clear()
79
80 Remove all elements from the deque leaving it with length 0.
81
82
83.. method:: deque.extend(iterable)
84
85 Extend the right side of the deque by appending elements from the iterable
86 argument.
87
88
89.. method:: deque.extendleft(iterable)
90
91 Extend the left side of the deque by appending elements from *iterable*. Note,
92 the series of left appends results in reversing the order of elements in the
93 iterable argument.
94
95
96.. method:: deque.pop()
97
98 Remove and return an element from the right side of the deque. If no elements
99 are present, raises an :exc:`IndexError`.
100
101
102.. method:: deque.popleft()
103
104 Remove and return an element from the left side of the deque. If no elements are
105 present, raises an :exc:`IndexError`.
106
107
108.. method:: deque.remove(value)
109
110 Removed the first occurrence of *value*. If not found, raises a
111 :exc:`ValueError`.
112
113 .. versionadded:: 2.5
114
115
116.. method:: deque.rotate(n)
117
118 Rotate the deque *n* steps to the right. If *n* is negative, rotate to the
119 left. Rotating one step to the right is equivalent to:
120 ``d.appendleft(d.pop())``.
121
122In addition to the above, deques support iteration, pickling, ``len(d)``,
123``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with
124the :keyword:`in` operator, and subscript references such as ``d[-1]``.
125
126Example::
127
128 >>> from collections import deque
129 >>> d = deque('ghi') # make a new deque with three items
130 >>> for elem in d: # iterate over the deque's elements
131 ... print elem.upper()
132 G
133 H
134 I
135
136 >>> d.append('j') # add a new entry to the right side
137 >>> d.appendleft('f') # add a new entry to the left side
138 >>> d # show the representation of the deque
139 deque(['f', 'g', 'h', 'i', 'j'])
140
141 >>> d.pop() # return and remove the rightmost item
142 'j'
143 >>> d.popleft() # return and remove the leftmost item
144 'f'
145 >>> list(d) # list the contents of the deque
146 ['g', 'h', 'i']
147 >>> d[0] # peek at leftmost item
148 'g'
149 >>> d[-1] # peek at rightmost item
150 'i'
151
152 >>> list(reversed(d)) # list the contents of a deque in reverse
153 ['i', 'h', 'g']
154 >>> 'h' in d # search the deque
155 True
156 >>> d.extend('jkl') # add multiple elements at once
157 >>> d
158 deque(['g', 'h', 'i', 'j', 'k', 'l'])
159 >>> d.rotate(1) # right rotation
160 >>> d
161 deque(['l', 'g', 'h', 'i', 'j', 'k'])
162 >>> d.rotate(-1) # left rotation
163 >>> d
164 deque(['g', 'h', 'i', 'j', 'k', 'l'])
165
166 >>> deque(reversed(d)) # make a new deque in reverse order
167 deque(['l', 'k', 'j', 'i', 'h', 'g'])
168 >>> d.clear() # empty the deque
169 >>> d.pop() # cannot pop from an empty deque
170 Traceback (most recent call last):
171 File "<pyshell#6>", line 1, in -toplevel-
172 d.pop()
173 IndexError: pop from an empty deque
174
175 >>> d.extendleft('abc') # extendleft() reverses the input order
176 >>> d
177 deque(['c', 'b', 'a'])
178
179
180.. _deque-recipes:
181
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000182:class:`deque` Recipes
183^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000184
185This section shows various approaches to working with deques.
186
187The :meth:`rotate` method provides a way to implement :class:`deque` slicing and
188deletion. For example, a pure python implementation of ``del d[n]`` relies on
189the :meth:`rotate` method to position elements to be popped::
190
191 def delete_nth(d, n):
192 d.rotate(-n)
193 d.popleft()
194 d.rotate(n)
195
196To implement :class:`deque` slicing, use a similar approach applying
197:meth:`rotate` to bring a target element to the left side of the deque. Remove
198old entries with :meth:`popleft`, add new entries with :meth:`extend`, and then
199reverse the rotation.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000200With minor variations on that approach, it is easy to implement Forth style
201stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``,
202``rot``, and ``roll``.
203
Georg Brandl8ec7f652007-08-15 14:28:01 +0000204Multi-pass data reduction algorithms can be succinctly expressed and efficiently
205coded by extracting elements with multiple calls to :meth:`popleft`, applying
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000206a reduction function, and calling :meth:`append` to add the result back to the
207deque.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000208
209For example, building a balanced binary tree of nested lists entails reducing
210two adjacent nodes into one by grouping them in a list::
211
212 >>> def maketree(iterable):
213 ... d = deque(iterable)
214 ... while len(d) > 1:
215 ... pair = [d.popleft(), d.popleft()]
216 ... d.append(pair)
217 ... return list(d)
218 ...
219 >>> print maketree('abcdefgh')
220 [[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
221
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000222Bounded length deques provide functionality similar to the ``tail`` filter
223in Unix::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000224
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000225 def tail(filename, n=10):
226 'Return the last n lines of a file'
227 return deque(open(filename), n)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000228
229.. _defaultdict-objects:
230
231:class:`defaultdict` objects
232----------------------------
233
234
235.. class:: defaultdict([default_factory[, ...]])
236
237 Returns a new dictionary-like object. :class:`defaultdict` is a subclass of the
238 builtin :class:`dict` class. It overrides one method and adds one writable
239 instance variable. The remaining functionality is the same as for the
240 :class:`dict` class and is not documented here.
241
242 The first argument provides the initial value for the :attr:`default_factory`
243 attribute; it defaults to ``None``. All remaining arguments are treated the same
244 as if they were passed to the :class:`dict` constructor, including keyword
245 arguments.
246
247 .. versionadded:: 2.5
248
249:class:`defaultdict` objects support the following method in addition to the
250standard :class:`dict` operations:
251
252
253.. method:: defaultdict.__missing__(key)
254
255 If the :attr:`default_factory` attribute is ``None``, this raises an
256 :exc:`KeyError` exception with the *key* as argument.
257
258 If :attr:`default_factory` is not ``None``, it is called without arguments to
259 provide a default value for the given *key*, this value is inserted in the
260 dictionary for the *key*, and returned.
261
262 If calling :attr:`default_factory` raises an exception this exception is
263 propagated unchanged.
264
265 This method is called by the :meth:`__getitem__` method of the :class:`dict`
266 class when the requested key is not found; whatever it returns or raises is then
267 returned or raised by :meth:`__getitem__`.
268
269:class:`defaultdict` objects support the following instance variable:
270
271
272.. attribute:: defaultdict.default_factory
273
274 This attribute is used by the :meth:`__missing__` method; it is initialized from
275 the first argument to the constructor, if present, or to ``None``, if absent.
276
277
278.. _defaultdict-examples:
279
280:class:`defaultdict` Examples
281^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
282
283Using :class:`list` as the :attr:`default_factory`, it is easy to group a
284sequence of key-value pairs into a dictionary of lists::
285
286 >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
287 >>> d = defaultdict(list)
288 >>> for k, v in s:
289 ... d[k].append(v)
290 ...
291 >>> d.items()
292 [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
293
294When each key is encountered for the first time, it is not already in the
295mapping; so an entry is automatically created using the :attr:`default_factory`
296function which returns an empty :class:`list`. The :meth:`list.append`
297operation then attaches the value to the new list. When keys are encountered
298again, the look-up proceeds normally (returning the list for that key) and the
299:meth:`list.append` operation adds another value to the list. This technique is
300simpler and faster than an equivalent technique using :meth:`dict.setdefault`::
301
302 >>> d = {}
303 >>> for k, v in s:
304 ... d.setdefault(k, []).append(v)
305 ...
306 >>> d.items()
307 [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
308
309Setting the :attr:`default_factory` to :class:`int` makes the
310:class:`defaultdict` useful for counting (like a bag or multiset in other
311languages)::
312
313 >>> s = 'mississippi'
314 >>> d = defaultdict(int)
315 >>> for k in s:
316 ... d[k] += 1
317 ...
318 >>> d.items()
319 [('i', 4), ('p', 2), ('s', 4), ('m', 1)]
320
321When a letter is first encountered, it is missing from the mapping, so the
322:attr:`default_factory` function calls :func:`int` to supply a default count of
323zero. The increment operation then builds up the count for each letter.
324
325The function :func:`int` which always returns zero is just a special case of
326constant functions. A faster and more flexible way to create constant functions
327is to use :func:`itertools.repeat` which can supply any constant value (not just
328zero)::
329
330 >>> def constant_factory(value):
331 ... return itertools.repeat(value).next
332 >>> d = defaultdict(constant_factory('<missing>'))
333 >>> d.update(name='John', action='ran')
334 >>> '%(name)s %(action)s to %(object)s' % d
335 'John ran to <missing>'
336
337Setting the :attr:`default_factory` to :class:`set` makes the
338:class:`defaultdict` useful for building a dictionary of sets::
339
340 >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
341 >>> d = defaultdict(set)
342 >>> for k, v in s:
343 ... d[k].add(v)
344 ...
345 >>> d.items()
346 [('blue', set([2, 4])), ('red', set([1, 3]))]
347
348
349.. _named-tuple-factory:
350
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000351:func:`namedtuple` Factory Function for Tuples with Named Fields
Raymond Hettingera48a2992007-10-08 21:26:58 +0000352-----------------------------------------------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +0000353
Raymond Hettingercbab5942007-09-18 22:18:02 +0000354Named tuples assign meaning to each position in a tuple and allow for more readable,
355self-documenting code. They can be used wherever regular tuples are used, and
356they add the ability to access fields by name instead of position index.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000357
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000358.. function:: namedtuple(typename, fieldnames, [verbose])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000359
360 Returns a new tuple subclass named *typename*. The new subclass is used to
361 create tuple-like objects that have fields accessable by attribute lookup as
362 well as being indexable and iterable. Instances of the subclass also have a
363 helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__`
364 method which lists the tuple contents in a ``name=value`` format.
365
Raymond Hettingera48a2992007-10-08 21:26:58 +0000366 The *fieldnames* are a single string with each fieldname separated by whitespace
367 and/or commas (for example 'x y' or 'x, y'). Alternatively, the *fieldnames*
Raymond Hettingerabfd8df2007-10-16 21:28:32 +0000368 can be specified as a list of strings (such as ['x', 'y']).
369
370 Any valid Python identifier may be used for a fieldname except for names
Raymond Hettinger42da8742007-12-14 02:49:47 +0000371 starting with an underscore. Valid identifiers consist of letters, digits,
372 and underscores but do not start with a digit or underscore and cannot be
Raymond Hettingerabfd8df2007-10-16 21:28:32 +0000373 a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, *print*,
374 or *raise*.
Raymond Hettingercbab5942007-09-18 22:18:02 +0000375
Raymond Hettinger7268e9d2007-09-20 03:03:43 +0000376 If *verbose* is true, will print the class definition.
Raymond Hettingercbab5942007-09-18 22:18:02 +0000377
Raymond Hettingera48a2992007-10-08 21:26:58 +0000378 Named tuple instances do not have per-instance dictionaries, so they are
Raymond Hettinger7268e9d2007-09-20 03:03:43 +0000379 lightweight and require no more memory than regular tuples.
Raymond Hettingercbab5942007-09-18 22:18:02 +0000380
Georg Brandl8ec7f652007-08-15 14:28:01 +0000381 .. versionadded:: 2.6
382
Raymond Hettingercbab5942007-09-18 22:18:02 +0000383Example::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000384
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000385 >>> Point = namedtuple('Point', 'x y', verbose=True)
Raymond Hettingercbab5942007-09-18 22:18:02 +0000386 class Point(tuple):
387 'Point(x, y)'
Raymond Hettinger48eca672007-12-14 18:08:20 +0000388
Raymond Hettingercbab5942007-09-18 22:18:02 +0000389 __slots__ = ()
Raymond Hettinger48eca672007-12-14 18:08:20 +0000390
Raymond Hettingere0734e72008-01-04 03:22:53 +0000391 _fields = ('x', 'y')
392
Raymond Hettingercbab5942007-09-18 22:18:02 +0000393 def __new__(cls, x, y):
394 return tuple.__new__(cls, (x, y))
Raymond Hettinger48eca672007-12-14 18:08:20 +0000395
Raymond Hettinger85dfcf32007-12-18 23:51:15 +0000396 _cast = classmethod(tuple.__new__)
397
Raymond Hettingercbab5942007-09-18 22:18:02 +0000398 def __repr__(self):
399 return 'Point(x=%r, y=%r)' % self
Raymond Hettinger48eca672007-12-14 18:08:20 +0000400
Raymond Hettinger8777bca2007-12-18 22:21:27 +0000401 def _asdict(t):
Raymond Hettinger48eca672007-12-14 18:08:20 +0000402 'Return a new dict which maps field names to their values'
Raymond Hettinger8777bca2007-12-18 22:21:27 +0000403 return {'x': t[0], 'y': t[1]}
Raymond Hettinger48eca672007-12-14 18:08:20 +0000404
Raymond Hettinger42da8742007-12-14 02:49:47 +0000405 def _replace(self, **kwds):
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000406 'Return a new Point object replacing specified fields with new values'
Raymond Hettingere0734e72008-01-04 03:22:53 +0000407 return self.__class__._cast(map(kwds.get, ('x', 'y'), self))
Raymond Hettinger88880b22007-12-18 00:13:45 +0000408
Raymond Hettingercbab5942007-09-18 22:18:02 +0000409 x = property(itemgetter(0))
410 y = property(itemgetter(1))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000411
Raymond Hettingercbab5942007-09-18 22:18:02 +0000412 >>> p = Point(11, y=22) # instantiate with positional or keyword arguments
Raymond Hettinger88880b22007-12-18 00:13:45 +0000413 >>> p[0] + p[1] # indexable like the plain tuple (11, 22)
Raymond Hettingercbab5942007-09-18 22:18:02 +0000414 33
415 >>> x, y = p # unpack like a regular tuple
416 >>> x, y
417 (11, 22)
418 >>> p.x + p.y # fields also accessable by name
419 33
420 >>> p # readable __repr__ with a name=value style
421 Point(x=11, y=22)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000422
Raymond Hettingercbab5942007-09-18 22:18:02 +0000423Named tuples are especially useful for assigning field names to result tuples returned
424by the :mod:`csv` or :mod:`sqlite3` modules::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000425
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000426 EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
Raymond Hettingera48a2992007-10-08 21:26:58 +0000427
Raymond Hettingercbab5942007-09-18 22:18:02 +0000428 import csv
Raymond Hettinger85dfcf32007-12-18 23:51:15 +0000429 for emp in map(EmployeeRecord._cast, csv.reader(open("employees.csv", "rb"))):
Raymond Hettingercbab5942007-09-18 22:18:02 +0000430 print emp.name, emp.title
Georg Brandl8ec7f652007-08-15 14:28:01 +0000431
Raymond Hettingera48a2992007-10-08 21:26:58 +0000432 import sqlite3
433 conn = sqlite3.connect('/companydata')
434 cursor = conn.cursor()
435 cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
Raymond Hettinger85dfcf32007-12-18 23:51:15 +0000436 for emp in map(EmployeeRecord._cast, cursor.fetchall()):
Raymond Hettingera48a2992007-10-08 21:26:58 +0000437 print emp.name, emp.title
438
Raymond Hettinger85dfcf32007-12-18 23:51:15 +0000439In addition to the methods inherited from tuples, named tuples support
Raymond Hettingere0734e72008-01-04 03:22:53 +0000440three additonal methods and one attribute.
Raymond Hettinger85dfcf32007-12-18 23:51:15 +0000441
442.. method:: namedtuple._cast(iterable)
443
Raymond Hettingere0734e72008-01-04 03:22:53 +0000444 Class method returning a new instance taking the positional arguments from the
445 *iterable*. Useful for casting existing sequences and iterables to named tuples.
446
447 This fast constructor does not check the length of the inputs. To achieve the
448 same effect with length checking, use the star-operator instead.
Raymond Hettinger85dfcf32007-12-18 23:51:15 +0000449
450::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000451
Raymond Hettingercbab5942007-09-18 22:18:02 +0000452 >>> t = [11, 22]
Raymond Hettingere0734e72008-01-04 03:22:53 +0000453 >>> Point._cast(t) # fast conversion
454 Point(x=11, y=22)
455 >>> Point(*t) # slow conversion with length checking
Raymond Hettingercbab5942007-09-18 22:18:02 +0000456 Point(x=11, y=22)
Raymond Hettinger2b03d452007-09-18 03:33:19 +0000457
Raymond Hettinger42da8742007-12-14 02:49:47 +0000458.. method:: somenamedtuple._asdict()
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000459
460 Return a new dict which maps field names to their corresponding values:
461
462::
463
Raymond Hettinger42da8742007-12-14 02:49:47 +0000464 >>> p._asdict()
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000465 {'x': 11, 'y': 22}
466
Raymond Hettinger42da8742007-12-14 02:49:47 +0000467.. method:: somenamedtuple._replace(kwargs)
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000468
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000469 Return a new instance of the named tuple replacing specified fields with new values:
Raymond Hettinger7268e9d2007-09-20 03:03:43 +0000470
471::
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000472
Raymond Hettingercbab5942007-09-18 22:18:02 +0000473 >>> p = Point(x=11, y=22)
Raymond Hettinger42da8742007-12-14 02:49:47 +0000474 >>> p._replace(x=33)
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000475 Point(x=33, y=22)
476
Raymond Hettinger7c3738e2007-11-15 03:16:09 +0000477 >>> for partnum, record in inventory.items():
Raymond Hettinger42da8742007-12-14 02:49:47 +0000478 ... inventory[partnum] = record._replace(price=newprices[partnum], updated=time.now())
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000479
Raymond Hettinger42da8742007-12-14 02:49:47 +0000480.. attribute:: somenamedtuple._fields
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000481
Raymond Hettingere0734e72008-01-04 03:22:53 +0000482 Tuple of strings listing the field names. This is useful for introspection
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000483 and for creating new named tuple types from existing named tuples.
Raymond Hettinger7268e9d2007-09-20 03:03:43 +0000484
485::
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000486
Raymond Hettinger42da8742007-12-14 02:49:47 +0000487 >>> p._fields # view the field names
Raymond Hettingercbab5942007-09-18 22:18:02 +0000488 ('x', 'y')
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000489
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000490 >>> Color = namedtuple('Color', 'red green blue')
Raymond Hettinger42da8742007-12-14 02:49:47 +0000491 >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
Raymond Hettingercbab5942007-09-18 22:18:02 +0000492 >>> Pixel(11, 22, 128, 255, 0)
493 Pixel(x=11, y=22, red=128, green=255, blue=0)'
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000494
Raymond Hettingere846f382007-12-14 21:51:50 +0000495To retrieve a field whose name is stored in a string, use the :func:`getattr`
496function:
497
498::
499
500 >>> getattr(p, 'x')
501 11
502
Raymond Hettinger85dfcf32007-12-18 23:51:15 +0000503When casting a dictionary to a named tuple, use the double-star-operator [#]_::
504
505 >>> d = {'x': 11, 'y': 22}
506 >>> Point(**d)
507 Point(x=11, y=22)
508
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000509Since a named tuple is a regular Python class, it is easy to add or change
510functionality. For example, the display format can be changed by overriding
511the :meth:`__repr__` method:
512
513::
514
515 >>> Point = namedtuple('Point', 'x y')
516 >>> Point.__repr__ = lambda self: 'Point(%.3f, %.3f)' % self
Raymond Hettingere846f382007-12-14 21:51:50 +0000517 >>> Point(x=11, y=22)
518 Point(11.000, 22.000)
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000519
Raymond Hettingerbc693492007-11-15 22:39:34 +0000520Default values can be implemented by starting with a prototype instance
Raymond Hettinger42da8742007-12-14 02:49:47 +0000521and customizing it with :meth:`_replace`:
Raymond Hettingerbc693492007-11-15 22:39:34 +0000522
523::
524
525 >>> Account = namedtuple('Account', 'owner balance transaction_count')
526 >>> model_account = Account('<owner name>', 0.0, 0)
Raymond Hettinger42da8742007-12-14 02:49:47 +0000527 >>> johns_account = model_account._replace(owner='John')
Raymond Hettingerbc693492007-11-15 22:39:34 +0000528
Mark Summerfield7f626f42007-08-30 15:03:03 +0000529.. rubric:: Footnotes
530
Raymond Hettinger85dfcf32007-12-18 23:51:15 +0000531.. [#] For information on the double-star-operator see
Mark Summerfield7f626f42007-08-30 15:03:03 +0000532 :ref:`tut-unpacking-arguments` and :ref:`calls`.