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 |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 63 | Added *maxlen* parameter. |
Raymond Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 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 |
Georg Brandl | b3255ed | 2008-01-07 16:43:47 +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 |
Raymond Hettinger | 15b5e55 | 2008-01-10 23:00:01 +0000 | [diff] [blame^] | 367 | and/or commas, for example ``'x y'`` or ``'x, y'``. Alternatively, *fieldnames* |
| 368 | can be a sequence of strings such as ``['x', 'y']``. |
Raymond Hettinger | abfd8df | 2007-10-16 21:28:32 +0000 | [diff] [blame] | 369 | |
| 370 | Any valid Python identifier may be used for a fieldname except for names |
Raymond Hettinger | 42da874 | 2007-12-14 02:49:47 +0000 | [diff] [blame] | 371 | 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 Hettinger | abfd8df | 2007-10-16 21:28:32 +0000 | [diff] [blame] | 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 | 15b5e55 | 2008-01-10 23:00:01 +0000 | [diff] [blame^] | 376 | If *verbose* is true, the class definition is printed just before being built. |
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)' |
Raymond Hettinger | 48eca67 | 2007-12-14 18:08:20 +0000 | [diff] [blame] | 388 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 389 | __slots__ = () |
Raymond Hettinger | 48eca67 | 2007-12-14 18:08:20 +0000 | [diff] [blame] | 390 | |
Raymond Hettinger | e0734e7 | 2008-01-04 03:22:53 +0000 | [diff] [blame] | 391 | _fields = ('x', 'y') |
| 392 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 393 | def __new__(cls, x, y): |
| 394 | return tuple.__new__(cls, (x, y)) |
Raymond Hettinger | 48eca67 | 2007-12-14 18:08:20 +0000 | [diff] [blame] | 395 | |
Raymond Hettinger | 02740f7 | 2008-01-05 01:35:43 +0000 | [diff] [blame] | 396 | @classmethod |
| 397 | def _make(cls, iterable): |
| 398 | 'Make a new Point object from a sequence or iterable' |
| 399 | result = tuple.__new__(cls, iterable) |
| 400 | if len(result) != 2: |
| 401 | raise TypeError('Expected 2 arguments, got %d' % len(result)) |
| 402 | return result |
Raymond Hettinger | 85dfcf3 | 2007-12-18 23:51:15 +0000 | [diff] [blame] | 403 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 404 | def __repr__(self): |
| 405 | return 'Point(x=%r, y=%r)' % self |
Raymond Hettinger | 48eca67 | 2007-12-14 18:08:20 +0000 | [diff] [blame] | 406 | |
Raymond Hettinger | 8777bca | 2007-12-18 22:21:27 +0000 | [diff] [blame] | 407 | def _asdict(t): |
Raymond Hettinger | 48eca67 | 2007-12-14 18:08:20 +0000 | [diff] [blame] | 408 | 'Return a new dict which maps field names to their values' |
Raymond Hettinger | 8777bca | 2007-12-18 22:21:27 +0000 | [diff] [blame] | 409 | return {'x': t[0], 'y': t[1]} |
Raymond Hettinger | 48eca67 | 2007-12-14 18:08:20 +0000 | [diff] [blame] | 410 | |
Raymond Hettinger | 42da874 | 2007-12-14 02:49:47 +0000 | [diff] [blame] | 411 | def _replace(self, **kwds): |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame] | 412 | 'Return a new Point object replacing specified fields with new values' |
Raymond Hettinger | 1166872 | 2008-01-06 09:02:24 +0000 | [diff] [blame] | 413 | result = self._make(map(kwds.pop, ('x', 'y'), self)) |
Raymond Hettinger | 1b50fd7 | 2008-01-05 02:17:24 +0000 | [diff] [blame] | 414 | if kwds: |
| 415 | raise ValueError('Got unexpected field names: %r' % kwds.keys()) |
| 416 | return result |
Raymond Hettinger | 88880b2 | 2007-12-18 00:13:45 +0000 | [diff] [blame] | 417 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 418 | x = property(itemgetter(0)) |
| 419 | y = property(itemgetter(1)) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 420 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 421 | >>> p = Point(11, y=22) # instantiate with positional or keyword arguments |
Raymond Hettinger | 88880b2 | 2007-12-18 00:13:45 +0000 | [diff] [blame] | 422 | >>> p[0] + p[1] # indexable like the plain tuple (11, 22) |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 423 | 33 |
| 424 | >>> x, y = p # unpack like a regular tuple |
| 425 | >>> x, y |
| 426 | (11, 22) |
| 427 | >>> p.x + p.y # fields also accessable by name |
| 428 | 33 |
| 429 | >>> p # readable __repr__ with a name=value style |
| 430 | Point(x=11, y=22) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 431 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 432 | Named tuples are especially useful for assigning field names to result tuples returned |
| 433 | by the :mod:`csv` or :mod:`sqlite3` modules:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 434 | |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame] | 435 | EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade') |
Raymond Hettinger | a48a299 | 2007-10-08 21:26:58 +0000 | [diff] [blame] | 436 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 437 | import csv |
Raymond Hettinger | 02740f7 | 2008-01-05 01:35:43 +0000 | [diff] [blame] | 438 | for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))): |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 439 | print emp.name, emp.title |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 440 | |
Raymond Hettinger | a48a299 | 2007-10-08 21:26:58 +0000 | [diff] [blame] | 441 | import sqlite3 |
| 442 | conn = sqlite3.connect('/companydata') |
| 443 | cursor = conn.cursor() |
| 444 | cursor.execute('SELECT name, age, title, department, paygrade FROM employees') |
Raymond Hettinger | 02740f7 | 2008-01-05 01:35:43 +0000 | [diff] [blame] | 445 | for emp in map(EmployeeRecord._make, cursor.fetchall()): |
Raymond Hettinger | a48a299 | 2007-10-08 21:26:58 +0000 | [diff] [blame] | 446 | print emp.name, emp.title |
| 447 | |
Raymond Hettinger | 85dfcf3 | 2007-12-18 23:51:15 +0000 | [diff] [blame] | 448 | In addition to the methods inherited from tuples, named tuples support |
Raymond Hettinger | ac5742e | 2008-01-08 02:24:15 +0000 | [diff] [blame] | 449 | three additional methods and one attribute. To prevent conflicts with |
| 450 | field names, the method and attribute names start with an underscore. |
Raymond Hettinger | 85dfcf3 | 2007-12-18 23:51:15 +0000 | [diff] [blame] | 451 | |
Georg Brandl | b3255ed | 2008-01-07 16:43:47 +0000 | [diff] [blame] | 452 | .. method:: somenamedtuple._make(iterable) |
Raymond Hettinger | 85dfcf3 | 2007-12-18 23:51:15 +0000 | [diff] [blame] | 453 | |
Raymond Hettinger | 02740f7 | 2008-01-05 01:35:43 +0000 | [diff] [blame] | 454 | Class method that makes a new instance from an existing sequence or iterable. |
Raymond Hettinger | 85dfcf3 | 2007-12-18 23:51:15 +0000 | [diff] [blame] | 455 | |
| 456 | :: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 457 | |
Raymond Hettinger | 02740f7 | 2008-01-05 01:35:43 +0000 | [diff] [blame] | 458 | >>> t = [11, 22] |
| 459 | >>> Point._make(t) |
| 460 | Point(x=11, y=22) |
Raymond Hettinger | 2b03d45 | 2007-09-18 03:33:19 +0000 | [diff] [blame] | 461 | |
Georg Brandl | b3255ed | 2008-01-07 16:43:47 +0000 | [diff] [blame] | 462 | .. method:: somenamedtuple._asdict() |
Raymond Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 463 | |
| 464 | Return a new dict which maps field names to their corresponding values: |
| 465 | |
| 466 | :: |
| 467 | |
Raymond Hettinger | 42da874 | 2007-12-14 02:49:47 +0000 | [diff] [blame] | 468 | >>> p._asdict() |
Raymond Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 469 | {'x': 11, 'y': 22} |
| 470 | |
Georg Brandl | b3255ed | 2008-01-07 16:43:47 +0000 | [diff] [blame] | 471 | .. method:: somenamedtuple._replace(kwargs) |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 472 | |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame] | 473 | 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] | 474 | |
| 475 | :: |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 476 | |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 477 | >>> p = Point(x=11, y=22) |
Raymond Hettinger | 42da874 | 2007-12-14 02:49:47 +0000 | [diff] [blame] | 478 | >>> p._replace(x=33) |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 479 | Point(x=33, y=22) |
| 480 | |
Raymond Hettinger | 7c3738e | 2007-11-15 03:16:09 +0000 | [diff] [blame] | 481 | >>> for partnum, record in inventory.items(): |
Raymond Hettinger | e11230e | 2008-01-09 03:02:23 +0000 | [diff] [blame] | 482 | ... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now()) |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 483 | |
Georg Brandl | b3255ed | 2008-01-07 16:43:47 +0000 | [diff] [blame] | 484 | .. attribute:: somenamedtuple._fields |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 485 | |
Raymond Hettinger | f6b769b | 2008-01-07 21:33:51 +0000 | [diff] [blame] | 486 | Tuple of strings listing the field names. Useful for introspection |
Raymond Hettinger | a7fc4b1 | 2007-10-05 02:47:07 +0000 | [diff] [blame] | 487 | and for creating new named tuple types from existing named tuples. |
Raymond Hettinger | 7268e9d | 2007-09-20 03:03:43 +0000 | [diff] [blame] | 488 | |
| 489 | :: |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 490 | |
Raymond Hettinger | 42da874 | 2007-12-14 02:49:47 +0000 | [diff] [blame] | 491 | >>> p._fields # view the field names |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 492 | ('x', 'y') |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 493 | |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame] | 494 | >>> Color = namedtuple('Color', 'red green blue') |
Raymond Hettinger | 42da874 | 2007-12-14 02:49:47 +0000 | [diff] [blame] | 495 | >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) |
Raymond Hettinger | cbab594 | 2007-09-18 22:18:02 +0000 | [diff] [blame] | 496 | >>> Pixel(11, 22, 128, 255, 0) |
Raymond Hettinger | dc1854d | 2008-01-09 03:13:20 +0000 | [diff] [blame] | 497 | Pixel(x=11, y=22, red=128, green=255, blue=0) |
Raymond Hettinger | d36a60e | 2007-09-17 00:55:00 +0000 | [diff] [blame] | 498 | |
Raymond Hettinger | e846f38 | 2007-12-14 21:51:50 +0000 | [diff] [blame] | 499 | To retrieve a field whose name is stored in a string, use the :func:`getattr` |
Georg Brandl | b3255ed | 2008-01-07 16:43:47 +0000 | [diff] [blame] | 500 | function:: |
Raymond Hettinger | e846f38 | 2007-12-14 21:51:50 +0000 | [diff] [blame] | 501 | |
| 502 | >>> getattr(p, 'x') |
| 503 | 11 |
| 504 | |
Raymond Hettinger | f6b769b | 2008-01-07 21:33:51 +0000 | [diff] [blame] | 505 | To cast a dictionary to a named tuple, use the double-star-operator [#]_:: |
Raymond Hettinger | 85dfcf3 | 2007-12-18 23:51:15 +0000 | [diff] [blame] | 506 | |
| 507 | >>> d = {'x': 11, 'y': 22} |
| 508 | >>> Point(**d) |
| 509 | Point(x=11, y=22) |
| 510 | |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame] | 511 | Since a named tuple is a regular Python class, it is easy to add or change |
Raymond Hettinger | b8e0072 | 2008-01-07 04:24:49 +0000 | [diff] [blame] | 512 | functionality with a subclass. Here is how to add a calculated field and |
Georg Brandl | 503f293 | 2008-01-07 09:18:17 +0000 | [diff] [blame] | 513 | a fixed-width print format:: |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame] | 514 | |
Raymond Hettinger | b8e0072 | 2008-01-07 04:24:49 +0000 | [diff] [blame] | 515 | >>> class Point(namedtuple('Point', 'x y')): |
Raymond Hettinger | e165508 | 2008-01-10 19:15:10 +0000 | [diff] [blame] | 516 | ... __slots__ = () |
Raymond Hettinger | e11230e | 2008-01-09 03:02:23 +0000 | [diff] [blame] | 517 | ... @property |
| 518 | ... def hypot(self): |
| 519 | ... return (self.x ** 2 + self.y ** 2) ** 0.5 |
| 520 | ... def __str__(self): |
Raymond Hettinger | 15b5e55 | 2008-01-10 23:00:01 +0000 | [diff] [blame^] | 521 | ... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot) |
Raymond Hettinger | b8e0072 | 2008-01-07 04:24:49 +0000 | [diff] [blame] | 522 | |
Raymond Hettinger | e165508 | 2008-01-10 19:15:10 +0000 | [diff] [blame] | 523 | >>> for p in Point(3, 4), Point(14, 5/7.): |
Raymond Hettinger | e11230e | 2008-01-09 03:02:23 +0000 | [diff] [blame] | 524 | ... print p |
Raymond Hettinger | 9a35921 | 2008-01-07 20:07:38 +0000 | [diff] [blame] | 525 | |
Raymond Hettinger | 15b5e55 | 2008-01-10 23:00:01 +0000 | [diff] [blame^] | 526 | Point: x= 3.000 y= 4.000 hypot= 5.000 |
| 527 | Point: x=14.000 y= 0.714 hypot=14.018 |
Raymond Hettinger | eeeb9c4 | 2007-11-15 02:44:53 +0000 | [diff] [blame] | 528 | |
Raymond Hettinger | dc55f35 | 2008-01-07 09:03:49 +0000 | [diff] [blame] | 529 | Another use for subclassing is to replace performance critcal methods with |
Raymond Hettinger | 15b5e55 | 2008-01-10 23:00:01 +0000 | [diff] [blame^] | 530 | faster versions that bypass error-checking:: |
Raymond Hettinger | dc55f35 | 2008-01-07 09:03:49 +0000 | [diff] [blame] | 531 | |
Raymond Hettinger | e11230e | 2008-01-09 03:02:23 +0000 | [diff] [blame] | 532 | class Point(namedtuple('Point', 'x y')): |
Raymond Hettinger | e165508 | 2008-01-10 19:15:10 +0000 | [diff] [blame] | 533 | __slots__ = () |
Raymond Hettinger | dc55f35 | 2008-01-07 09:03:49 +0000 | [diff] [blame] | 534 | _make = classmethod(tuple.__new__) |
| 535 | def _replace(self, _map=map, **kwds): |
Raymond Hettinger | f5e8af1 | 2008-01-07 20:56:05 +0000 | [diff] [blame] | 536 | return self._make(_map(kwds.get, ('x', 'y'), self)) |
Raymond Hettinger | dc55f35 | 2008-01-07 09:03:49 +0000 | [diff] [blame] | 537 | |
Raymond Hettinger | ac5742e | 2008-01-08 02:24:15 +0000 | [diff] [blame] | 538 | Subclassing is not useful for adding new, stored fields. Instead, simply |
| 539 | create a new named tuple type from the :attr:`_fields` attribute:: |
| 540 | |
Raymond Hettinger | e850c46 | 2008-01-10 20:37:12 +0000 | [diff] [blame] | 541 | >>> Point3D = namedtuple('Point3D', Point._fields + ('z',)) |
Raymond Hettinger | ac5742e | 2008-01-08 02:24:15 +0000 | [diff] [blame] | 542 | |
Raymond Hettinger | fb3ced6 | 2008-01-07 20:17:35 +0000 | [diff] [blame] | 543 | Default values can be implemented by using :meth:`_replace` to |
Raymond Hettinger | 9a35921 | 2008-01-07 20:07:38 +0000 | [diff] [blame] | 544 | customize a prototype instance:: |
Raymond Hettinger | bc69349 | 2007-11-15 22:39:34 +0000 | [diff] [blame] | 545 | |
| 546 | >>> Account = namedtuple('Account', 'owner balance transaction_count') |
| 547 | >>> model_account = Account('<owner name>', 0.0, 0) |
Raymond Hettinger | 42da874 | 2007-12-14 02:49:47 +0000 | [diff] [blame] | 548 | >>> johns_account = model_account._replace(owner='John') |
Raymond Hettinger | bc69349 | 2007-11-15 22:39:34 +0000 | [diff] [blame] | 549 | |
Mark Summerfield | 7f626f4 | 2007-08-30 15:03:03 +0000 | [diff] [blame] | 550 | .. rubric:: Footnotes |
| 551 | |
Raymond Hettinger | 85dfcf3 | 2007-12-18 23:51:15 +0000 | [diff] [blame] | 552 | .. [#] For information on the double-star-operator see |
Mark Summerfield | 7f626f4 | 2007-08-30 15:03:03 +0000 | [diff] [blame] | 553 | :ref:`tut-unpacking-arguments` and :ref:`calls`. |