blob: d5f4283f8a92fd092ac2bded17ee830baf34d62e [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
63 Added *maxlen*
64
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 Hettinger42da8742007-12-14 02:49:47 +0000391 _fields = ('x', 'y')
Raymond Hettinger48eca672007-12-14 18:08:20 +0000392
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 Hettingercbab5942007-09-18 22:18:02 +0000396 def __repr__(self):
397 return 'Point(x=%r, y=%r)' % self
Raymond Hettinger48eca672007-12-14 18:08:20 +0000398
Raymond Hettinger42da8742007-12-14 02:49:47 +0000399 def _asdict(self):
Raymond Hettinger48eca672007-12-14 18:08:20 +0000400 'Return a new dict which maps field names to their values'
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000401 return dict(zip(('x', 'y'), self))
Raymond Hettinger48eca672007-12-14 18:08:20 +0000402
Raymond Hettinger42da8742007-12-14 02:49:47 +0000403 def _replace(self, **kwds):
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000404 'Return a new Point object replacing specified fields with new values'
Raymond Hettinger04a9a0e2007-12-13 22:55:52 +0000405 return Point(**dict(zip(('x', 'y'), self), **kwds))
Raymond Hettinger48eca672007-12-14 18:08:20 +0000406
Raymond Hettingercbab5942007-09-18 22:18:02 +0000407 x = property(itemgetter(0))
408 y = property(itemgetter(1))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000409
Raymond Hettingercbab5942007-09-18 22:18:02 +0000410 >>> p = Point(11, y=22) # instantiate with positional or keyword arguments
411 >>> p[0] + p[1] # indexable like the regular tuple (11, 22)
412 33
413 >>> x, y = p # unpack like a regular tuple
414 >>> x, y
415 (11, 22)
416 >>> p.x + p.y # fields also accessable by name
417 33
418 >>> p # readable __repr__ with a name=value style
419 Point(x=11, y=22)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000420
Raymond Hettingercbab5942007-09-18 22:18:02 +0000421Named tuples are especially useful for assigning field names to result tuples returned
422by the :mod:`csv` or :mod:`sqlite3` modules::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000423
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000424 EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
Raymond Hettingera48a2992007-10-08 21:26:58 +0000425
Raymond Hettingercbab5942007-09-18 22:18:02 +0000426 from itertools import starmap
427 import csv
Raymond Hettingercbab5942007-09-18 22:18:02 +0000428 for emp in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))):
429 print emp.name, emp.title
Georg Brandl8ec7f652007-08-15 14:28:01 +0000430
Raymond Hettingera48a2992007-10-08 21:26:58 +0000431 import sqlite3
432 conn = sqlite3.connect('/companydata')
433 cursor = conn.cursor()
434 cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
435 for emp in starmap(EmployeeRecord, cursor.fetchall()):
436 print emp.name, emp.title
437
438When casting a single record to a named tuple, use the star-operator [#]_ to unpack
Raymond Hettingercbab5942007-09-18 22:18:02 +0000439the values::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000440
Raymond Hettingercbab5942007-09-18 22:18:02 +0000441 >>> t = [11, 22]
442 >>> Point(*t) # the star-operator unpacks any iterable object
443 Point(x=11, y=22)
Raymond Hettinger2b03d452007-09-18 03:33:19 +0000444
Raymond Hettingera48a2992007-10-08 21:26:58 +0000445When casting a dictionary to a named tuple, use the double-star-operator::
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000446
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000447 >>> d = {'x': 11, 'y': 22}
448 >>> Point(**d)
449 Point(x=11, y=22)
450
451In addition to the methods inherited from tuples, named tuples support
Raymond Hettingera48a2992007-10-08 21:26:58 +0000452two additonal methods and a read-only attribute.
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000453
Raymond Hettinger42da8742007-12-14 02:49:47 +0000454.. method:: somenamedtuple._asdict()
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000455
456 Return a new dict which maps field names to their corresponding values:
457
458::
459
Raymond Hettinger42da8742007-12-14 02:49:47 +0000460 >>> p._asdict()
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000461 {'x': 11, 'y': 22}
462
Raymond Hettinger42da8742007-12-14 02:49:47 +0000463.. method:: somenamedtuple._replace(kwargs)
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000464
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000465 Return a new instance of the named tuple replacing specified fields with new values:
Raymond Hettinger7268e9d2007-09-20 03:03:43 +0000466
467::
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000468
Raymond Hettingercbab5942007-09-18 22:18:02 +0000469 >>> p = Point(x=11, y=22)
Raymond Hettinger42da8742007-12-14 02:49:47 +0000470 >>> p._replace(x=33)
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000471 Point(x=33, y=22)
472
Raymond Hettinger7c3738e2007-11-15 03:16:09 +0000473 >>> for partnum, record in inventory.items():
Raymond Hettinger42da8742007-12-14 02:49:47 +0000474 ... inventory[partnum] = record._replace(price=newprices[partnum], updated=time.now())
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000475
Raymond Hettinger42da8742007-12-14 02:49:47 +0000476.. attribute:: somenamedtuple._fields
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000477
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000478 Return a tuple of strings listing the field names. This is useful for introspection
479 and for creating new named tuple types from existing named tuples.
Raymond Hettinger7268e9d2007-09-20 03:03:43 +0000480
481::
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000482
Raymond Hettinger42da8742007-12-14 02:49:47 +0000483 >>> p._fields # view the field names
Raymond Hettingercbab5942007-09-18 22:18:02 +0000484 ('x', 'y')
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000485
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000486 >>> Color = namedtuple('Color', 'red green blue')
Raymond Hettinger42da8742007-12-14 02:49:47 +0000487 >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
Raymond Hettingercbab5942007-09-18 22:18:02 +0000488 >>> Pixel(11, 22, 128, 255, 0)
489 Pixel(x=11, y=22, red=128, green=255, blue=0)'
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000490
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000491Since a named tuple is a regular Python class, it is easy to add or change
492functionality. For example, the display format can be changed by overriding
493the :meth:`__repr__` method:
494
495::
496
497 >>> Point = namedtuple('Point', 'x y')
498 >>> Point.__repr__ = lambda self: 'Point(%.3f, %.3f)' % self
499 >>> Point(x=10, y=20)
500 Point(10.000, 20.000)
501
Raymond Hettingerbc693492007-11-15 22:39:34 +0000502Default values can be implemented by starting with a prototype instance
Raymond Hettinger42da8742007-12-14 02:49:47 +0000503and customizing it with :meth:`_replace`:
Raymond Hettingerbc693492007-11-15 22:39:34 +0000504
505::
506
507 >>> Account = namedtuple('Account', 'owner balance transaction_count')
508 >>> model_account = Account('<owner name>', 0.0, 0)
Raymond Hettinger42da8742007-12-14 02:49:47 +0000509 >>> johns_account = model_account._replace(owner='John')
Raymond Hettingerbc693492007-11-15 22:39:34 +0000510
Mark Summerfield7f626f42007-08-30 15:03:03 +0000511.. rubric:: Footnotes
512
513.. [#] For information on the star-operator see
514 :ref:`tut-unpacking-arguments` and :ref:`calls`.