Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | |
| 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 | |
| 13 | This module implements high-performance container datatypes. Currently, |
| 14 | there are two datatypes, :class:`deque` and :class:`defaultdict`, and |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame^] | 15 | one datatype factory function, :func:`namedtuple`. Python already |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 16 | includes built-in containers, :class:`dict`, :class:`list`, |
| 17 | :class:`set`, and :class:`tuple`. In addition, the optional :mod:`bsddb` |
| 18 | module has a :meth:`bsddb.btopen` method that can be used to create in-memory |
| 19 | or file based ordered dictionaries with string keys. |
| 20 | |
| 21 | Future editions of the standard library may include balanced trees and |
| 22 | ordered dictionaries. |
| 23 | |
| 24 | .. versionchanged:: 2.5 |
| 25 | Added :class:`defaultdict`. |
| 26 | |
| 27 | .. versionchanged:: 2.6 |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame^] | 28 | Added :func:`namedtuple`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 29 | |
| 30 | |
| 31 | .. _deque-objects: |
| 32 | |
| 33 | :class:`deque` objects |
| 34 | ---------------------- |
| 35 | |
| 36 | |
Raymond Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 37 | .. class:: deque([iterable[, maxlen]]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 38 | |
| 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 Hettinger | 6899586 | 2007-10-10 00:26:46 +0000 | [diff] [blame] | 54 | If *maxlen* is not specified or is *None*, deques may grow to an |
Raymond Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 55 | 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 Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 65 | Deque 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 | |
| 122 | In addition to the above, deques support iteration, pickling, ``len(d)``, |
| 123 | ``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with |
| 124 | the :keyword:`in` operator, and subscript references such as ``d[-1]``. |
| 125 | |
| 126 | Example:: |
| 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 Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 182 | :class:`deque` Recipes |
| 183 | ^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 184 | |
| 185 | This section shows various approaches to working with deques. |
| 186 | |
| 187 | The :meth:`rotate` method provides a way to implement :class:`deque` slicing and |
| 188 | deletion. For example, a pure python implementation of ``del d[n]`` relies on |
| 189 | the :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 | |
| 196 | To 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 |
| 198 | old entries with :meth:`popleft`, add new entries with :meth:`extend`, and then |
| 199 | reverse the rotation. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 200 | With minor variations on that approach, it is easy to implement Forth style |
| 201 | stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``, |
| 202 | ``rot``, and ``roll``. |
| 203 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 204 | Multi-pass data reduction algorithms can be succinctly expressed and efficiently |
| 205 | coded by extracting elements with multiple calls to :meth:`popleft`, applying |
Raymond Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 206 | a reduction function, and calling :meth:`append` to add the result back to the |
| 207 | deque. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 208 | |
| 209 | For example, building a balanced binary tree of nested lists entails reducing |
| 210 | two 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 Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 222 | Bounded length deques provide functionality similar to the ``tail`` filter |
| 223 | in Unix:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 224 | |
Raymond Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 225 | def tail(filename, n=10): |
| 226 | 'Return the last n lines of a file' |
| 227 | return deque(open(filename), n) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 228 | |
| 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 |
| 250 | standard :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 | |
| 283 | Using :class:`list` as the :attr:`default_factory`, it is easy to group a |
| 284 | sequence 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 | |
| 294 | When each key is encountered for the first time, it is not already in the |
| 295 | mapping; so an entry is automatically created using the :attr:`default_factory` |
| 296 | function which returns an empty :class:`list`. The :meth:`list.append` |
| 297 | operation then attaches the value to the new list. When keys are encountered |
| 298 | again, 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 |
| 300 | simpler 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 | |
| 309 | Setting the :attr:`default_factory` to :class:`int` makes the |
| 310 | :class:`defaultdict` useful for counting (like a bag or multiset in other |
| 311 | languages):: |
| 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 | |
| 321 | When 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 |
| 323 | zero. The increment operation then builds up the count for each letter. |
| 324 | |
| 325 | The function :func:`int` which always returns zero is just a special case of |
| 326 | constant functions. A faster and more flexible way to create constant functions |
| 327 | is to use :func:`itertools.repeat` which can supply any constant value (not just |
| 328 | zero):: |
| 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 | |
| 337 | Setting 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 Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame^] | 351 | :func:`namedtuple` Factory Function for Tuples with Named Fields |
Raymond Hettinger | a48a299 | 2007-10-08 21:26:58 +0000 | [diff] [blame] | 352 | ----------------------------------------------------------------- |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 353 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 354 | Named tuples assign meaning to each position in a tuple and allow for more readable, |
| 355 | self-documenting code. They can be used wherever regular tuples are used, and |
| 356 | they add the ability to access fields by name instead of position index. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 357 | |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame^] | 358 | .. function:: namedtuple(typename, fieldnames, [verbose]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 359 | |
| 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 Hettinger | a48a299 | 2007-10-08 21:26:58 +0000 | [diff] [blame] | 366 | 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 Hettinger | abfd8df | 2007-10-16 21:28:32 +0000 | [diff] [blame] | 368 | 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 |
| 371 | starting and ending with double underscores. Valid identifiers consist of |
| 372 | letters, digits, and underscores but do not start with a digit and cannot be |
| 373 | a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, *print*, |
| 374 | or *raise*. |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 375 | |
Raymond Hettinger | 7268e9d | 2007-09-20 03:03:43 +0000 | [diff] [blame] | 376 | If *verbose* is true, will print the class definition. |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 377 | |
Raymond Hettinger | a48a299 | 2007-10-08 21:26:58 +0000 | [diff] [blame] | 378 | Named tuple instances do not have per-instance dictionaries, so they are |
Raymond Hettinger | 7268e9d | 2007-09-20 03:03:43 +0000 | [diff] [blame] | 379 | lightweight and require no more memory than regular tuples. |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 380 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 381 | .. versionadded:: 2.6 |
| 382 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 383 | Example:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 384 | |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame^] | 385 | >>> Point = namedtuple('Point', 'x y', verbose=True) |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 386 | class Point(tuple): |
| 387 | 'Point(x, y)' |
| 388 | __slots__ = () |
| 389 | __fields__ = ('x', 'y') |
| 390 | def __new__(cls, x, y): |
| 391 | return tuple.__new__(cls, (x, y)) |
| 392 | def __repr__(self): |
| 393 | return 'Point(x=%r, y=%r)' % self |
Raymond Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 394 | def __asdict__(self): |
| 395 | 'Return a new dict mapping field names to their values' |
| 396 | return dict(zip(('x', 'y'), self)) |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 397 | def __replace__(self, field, value): |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame^] | 398 | 'Return a new Point object replacing specified fields with new values' |
| 399 | return Point(**dict(self.__asdict__().items() + kwds.items())) |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 400 | x = property(itemgetter(0)) |
| 401 | y = property(itemgetter(1)) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 402 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 403 | >>> p = Point(11, y=22) # instantiate with positional or keyword arguments |
| 404 | >>> p[0] + p[1] # indexable like the regular tuple (11, 22) |
| 405 | 33 |
| 406 | >>> x, y = p # unpack like a regular tuple |
| 407 | >>> x, y |
| 408 | (11, 22) |
| 409 | >>> p.x + p.y # fields also accessable by name |
| 410 | 33 |
| 411 | >>> p # readable __repr__ with a name=value style |
| 412 | Point(x=11, y=22) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 413 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 414 | Named tuples are especially useful for assigning field names to result tuples returned |
| 415 | by the :mod:`csv` or :mod:`sqlite3` modules:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 416 | |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame^] | 417 | EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade') |
Raymond Hettinger | a48a299 | 2007-10-08 21:26:58 +0000 | [diff] [blame] | 418 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 419 | from itertools import starmap |
| 420 | import csv |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 421 | for emp in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))): |
| 422 | print emp.name, emp.title |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 423 | |
Raymond Hettinger | a48a299 | 2007-10-08 21:26:58 +0000 | [diff] [blame] | 424 | import sqlite3 |
| 425 | conn = sqlite3.connect('/companydata') |
| 426 | cursor = conn.cursor() |
| 427 | cursor.execute('SELECT name, age, title, department, paygrade FROM employees') |
| 428 | for emp in starmap(EmployeeRecord, cursor.fetchall()): |
| 429 | print emp.name, emp.title |
| 430 | |
| 431 | When casting a single record to a named tuple, use the star-operator [#]_ to unpack |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 432 | the values:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 433 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 434 | >>> t = [11, 22] |
| 435 | >>> Point(*t) # the star-operator unpacks any iterable object |
| 436 | Point(x=11, y=22) |
Raymond Hettinger | 2b03d45 | 2007-09-18 03:33:19 +0000 | [diff] [blame] | 437 | |
Raymond Hettinger | a48a299 | 2007-10-08 21:26:58 +0000 | [diff] [blame] | 438 | When casting a dictionary to a named tuple, use the double-star-operator:: |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 439 | |
Raymond Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 440 | >>> d = {'x': 11, 'y': 22} |
| 441 | >>> Point(**d) |
| 442 | Point(x=11, y=22) |
| 443 | |
| 444 | In addition to the methods inherited from tuples, named tuples support |
Raymond Hettinger | a48a299 | 2007-10-08 21:26:58 +0000 | [diff] [blame] | 445 | two additonal methods and a read-only attribute. |
Raymond Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 446 | |
| 447 | .. method:: somenamedtuple.__asdict__() |
| 448 | |
| 449 | Return a new dict which maps field names to their corresponding values: |
| 450 | |
| 451 | :: |
| 452 | |
| 453 | >>> p.__asdict__() |
| 454 | {'x': 11, 'y': 22} |
| 455 | |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame^] | 456 | .. method:: somenamedtuple.__replace__(kwargs) |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 457 | |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame^] | 458 | Return a new instance of the named tuple replacing specified fields with new values: |
Raymond Hettinger | 7268e9d | 2007-09-20 03:03:43 +0000 | [diff] [blame] | 459 | |
| 460 | :: |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 461 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 462 | >>> p = Point(x=11, y=22) |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame^] | 463 | >>> p.__replace__(x=33) |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 464 | Point(x=33, y=22) |
| 465 | |
| 466 | >>> for recordnum, record in inventory: |
| 467 | ... inventory[recordnum] = record.replace('total', record.price * record.quantity) |
| 468 | |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 469 | .. attribute:: somenamedtuple.__fields__ |
| 470 | |
Raymond Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 471 | Return a tuple of strings listing the field names. This is useful for introspection |
| 472 | and for creating new named tuple types from existing named tuples. |
Raymond Hettinger | 7268e9d | 2007-09-20 03:03:43 +0000 | [diff] [blame] | 473 | |
| 474 | :: |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 475 | |
Raymond Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 476 | >>> p.__fields__ # view the field names |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 477 | ('x', 'y') |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 478 | |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame^] | 479 | >>> Color = namedtuple('Color', 'red green blue') |
| 480 | >>> Pixel = namedtuple('Pixel', Point.__fields__ + Color.__fields__) |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 481 | >>> Pixel(11, 22, 128, 255, 0) |
| 482 | Pixel(x=11, y=22, red=128, green=255, blue=0)' |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 483 | |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame^] | 484 | Since a named tuple is a regular Python class, it is easy to add or change |
| 485 | functionality. For example, the display format can be changed by overriding |
| 486 | the :meth:`__repr__` method: |
| 487 | |
| 488 | :: |
| 489 | |
| 490 | >>> Point = namedtuple('Point', 'x y') |
| 491 | >>> Point.__repr__ = lambda self: 'Point(%.3f, %.3f)' % self |
| 492 | >>> Point(x=10, y=20) |
| 493 | Point(10.000, 20.000) |
| 494 | |
Mark Summerfield | 7f626f4 | 2007-08-30 15:03:03 +0000 | [diff] [blame] | 495 | .. rubric:: Footnotes |
| 496 | |
| 497 | .. [#] For information on the star-operator see |
| 498 | :ref:`tut-unpacking-arguments` and :ref:`calls`. |