Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +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 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 11 | This module implements high-performance container datatypes. Currently, |
| 12 | there are two datatypes, :class:`deque` and :class:`defaultdict`, and |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 13 | one datatype factory function, :func:`namedtuple`. Python already |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 14 | includes built-in containers, :class:`dict`, :class:`list`, |
| 15 | :class:`set`, and :class:`tuple`. In addition, the optional :mod:`bsddb` |
| 16 | module has a :meth:`bsddb.btopen` method that can be used to create in-memory |
| 17 | or file based ordered dictionaries with string keys. |
| 18 | |
| 19 | Future editions of the standard library may include balanced trees and |
| 20 | ordered dictionaries. |
| 21 | |
Mark Summerfield | 08898b4 | 2007-09-05 08:43:04 +0000 | [diff] [blame] | 22 | In addition to containers, the collections module provides some ABCs |
| 23 | (abstract base classes) that can be used to test whether |
| 24 | a class provides a particular interface, for example, is it hashable or |
| 25 | a mapping. The ABCs provided include those in the following table: |
| 26 | |
Mark Summerfield | 8f2d006 | 2008-02-06 13:30:44 +0000 | [diff] [blame] | 27 | ===================================== ================================================================================ |
Mark Summerfield | 08898b4 | 2007-09-05 08:43:04 +0000 | [diff] [blame] | 28 | ABC Notes |
Mark Summerfield | 8f2d006 | 2008-02-06 13:30:44 +0000 | [diff] [blame] | 29 | ===================================== ================================================================================ |
Mark Summerfield | 08898b4 | 2007-09-05 08:43:04 +0000 | [diff] [blame] | 30 | :class:`collections.Container` Defines ``__contains__()`` |
| 31 | :class:`collections.Hashable` Defines ``__hash__()`` |
| 32 | :class:`collections.Iterable` Defines ``__iter__()`` |
| 33 | :class:`collections.Iterator` Derived from :class:`Iterable` and in |
| 34 | addition defines ``__next__()`` |
Raymond Hettinger | e4c96ad | 2008-02-06 01:23:58 +0000 | [diff] [blame] | 35 | :class:`collections.Sized` Defines ``__len__()`` |
Mark Summerfield | 08898b4 | 2007-09-05 08:43:04 +0000 | [diff] [blame] | 36 | :class:`collections.Mapping` Derived from :class:`Container`, |
| 37 | :class:`Iterable`, |
| 38 | and :class:`Sized`, and in addition |
| 39 | defines ``__getitem__()``, ``get()``, |
| 40 | ``__contains__()``, ``__len__()``, |
Raymond Hettinger | e4c96ad | 2008-02-06 01:23:58 +0000 | [diff] [blame] | 41 | ``__eq__()``, ``__ne__()``, |
Mark Summerfield | 08898b4 | 2007-09-05 08:43:04 +0000 | [diff] [blame] | 42 | ``__iter__()``, ``keys()``, |
| 43 | ``items()``, and ``values()`` |
| 44 | :class:`collections.MutableMapping` Derived from :class:`Mapping` |
Mark Summerfield | 08898b4 | 2007-09-05 08:43:04 +0000 | [diff] [blame] | 45 | :class:`collections.Sequence` Derived from :class:`Container`, |
| 46 | :class:`Iterable`, and :class:`Sized`, |
| 47 | and in addition defines |
Mark Summerfield | 8f2d006 | 2008-02-06 13:30:44 +0000 | [diff] [blame] | 48 | ``__getitem__()`` |
Raymond Hettinger | e4c96ad | 2008-02-06 01:23:58 +0000 | [diff] [blame] | 49 | :class:`collections.MutableSequence` Derived from :class:`Sequence` |
Mark Summerfield | 8f2d006 | 2008-02-06 13:30:44 +0000 | [diff] [blame] | 50 | :class:`collections.Set` Derived from :class:`Container`, |
| 51 | :class:`Iterable`, and :class:`Sized`, |
Raymond Hettinger | e4c96ad | 2008-02-06 01:23:58 +0000 | [diff] [blame] | 52 | add in addition defines |
Mark Summerfield | 8f2d006 | 2008-02-06 13:30:44 +0000 | [diff] [blame] | 53 | ``__le__()``, ``__lt__()``, |
| 54 | ``__eq__()``, ``__and__()``, |
| 55 | ``__or__()``, ``__sub__()``, |
Raymond Hettinger | e4c96ad | 2008-02-06 01:23:58 +0000 | [diff] [blame] | 56 | ``__xor__()``, and ``isdisjoint()``, |
| 57 | :class:`collections.MutableSet` Derived from :class:`Set` and in |
| 58 | addition defines ``add()``, |
| 59 | ``clear()``, ``discard()``, ``pop()``, |
Mark Summerfield | 8f2d006 | 2008-02-06 13:30:44 +0000 | [diff] [blame] | 60 | ``remove()``, ``__ior__()``, |
| 61 | ``__iand__()``, ``__ixor__()``, and |
| 62 | ``__isub__()`` |
| 63 | ===================================== ================================================================================ |
Mark Summerfield | 08898b4 | 2007-09-05 08:43:04 +0000 | [diff] [blame] | 64 | |
Georg Brandl | 84df79b | 2008-01-05 19:25:53 +0000 | [diff] [blame] | 65 | .. XXX Have not included them all and the notes are incomplete |
Mark Summerfield | 8f2d006 | 2008-02-06 13:30:44 +0000 | [diff] [blame] | 66 | .. long = lines improves the layout |
Mark Summerfield | 08898b4 | 2007-09-05 08:43:04 +0000 | [diff] [blame] | 67 | |
| 68 | These ABCs allow us to ask classes or instances if they provide |
| 69 | particular functionality, for example:: |
| 70 | |
| 71 | from collections import Sized |
| 72 | |
| 73 | size = None |
| 74 | if isinstance(myvar, Sized): |
| 75 | size = len(myvar) |
| 76 | |
| 77 | (For more about ABCs, see the :mod:`abc` module and :pep:`3119`.) |
| 78 | |
| 79 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 80 | |
| 81 | .. _deque-objects: |
| 82 | |
| 83 | :class:`deque` objects |
| 84 | ---------------------- |
| 85 | |
| 86 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 87 | .. class:: deque([iterable[, maxlen]]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 88 | |
| 89 | Returns a new deque object initialized left-to-right (using :meth:`append`) with |
| 90 | data from *iterable*. If *iterable* is not specified, the new deque is empty. |
| 91 | |
| 92 | Deques are a generalization of stacks and queues (the name is pronounced "deck" |
| 93 | and is short for "double-ended queue"). Deques support thread-safe, memory |
| 94 | efficient appends and pops from either side of the deque with approximately the |
| 95 | same O(1) performance in either direction. |
| 96 | |
| 97 | Though :class:`list` objects support similar operations, they are optimized for |
| 98 | fast fixed-length operations and incur O(n) memory movement costs for |
| 99 | ``pop(0)`` and ``insert(0, v)`` operations which change both the size and |
| 100 | position of the underlying data representation. |
| 101 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 102 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 103 | If *maxlen* is not specified or is *None*, deques may grow to an |
| 104 | arbitrary length. Otherwise, the deque is bounded to the specified maximum |
| 105 | length. Once a bounded length deque is full, when new items are added, a |
| 106 | corresponding number of items are discarded from the opposite end. Bounded |
| 107 | length deques provide functionality similar to the ``tail`` filter in |
| 108 | Unix. They are also useful for tracking transactions and other pools of data |
| 109 | where only the most recent activity is of interest. |
| 110 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 111 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 112 | Deque objects support the following methods: |
| 113 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 114 | .. method:: deque.append(x) |
| 115 | |
| 116 | Add *x* to the right side of the deque. |
| 117 | |
| 118 | |
| 119 | .. method:: deque.appendleft(x) |
| 120 | |
| 121 | Add *x* to the left side of the deque. |
| 122 | |
| 123 | |
| 124 | .. method:: deque.clear() |
| 125 | |
| 126 | Remove all elements from the deque leaving it with length 0. |
| 127 | |
| 128 | |
| 129 | .. method:: deque.extend(iterable) |
| 130 | |
| 131 | Extend the right side of the deque by appending elements from the iterable |
| 132 | argument. |
| 133 | |
| 134 | |
| 135 | .. method:: deque.extendleft(iterable) |
| 136 | |
| 137 | Extend the left side of the deque by appending elements from *iterable*. Note, |
| 138 | the series of left appends results in reversing the order of elements in the |
| 139 | iterable argument. |
| 140 | |
| 141 | |
| 142 | .. method:: deque.pop() |
| 143 | |
| 144 | Remove and return an element from the right side of the deque. If no elements |
| 145 | are present, raises an :exc:`IndexError`. |
| 146 | |
| 147 | |
| 148 | .. method:: deque.popleft() |
| 149 | |
| 150 | Remove and return an element from the left side of the deque. If no elements are |
| 151 | present, raises an :exc:`IndexError`. |
| 152 | |
| 153 | |
| 154 | .. method:: deque.remove(value) |
| 155 | |
| 156 | Removed the first occurrence of *value*. If not found, raises a |
| 157 | :exc:`ValueError`. |
| 158 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 159 | |
| 160 | .. method:: deque.rotate(n) |
| 161 | |
| 162 | Rotate the deque *n* steps to the right. If *n* is negative, rotate to the |
| 163 | left. Rotating one step to the right is equivalent to: |
| 164 | ``d.appendleft(d.pop())``. |
| 165 | |
| 166 | In addition to the above, deques support iteration, pickling, ``len(d)``, |
| 167 | ``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with |
| 168 | the :keyword:`in` operator, and subscript references such as ``d[-1]``. |
| 169 | |
| 170 | Example:: |
| 171 | |
| 172 | >>> from collections import deque |
| 173 | >>> d = deque('ghi') # make a new deque with three items |
| 174 | >>> for elem in d: # iterate over the deque's elements |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 175 | ... print(elem.upper()) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 176 | G |
| 177 | H |
| 178 | I |
| 179 | |
| 180 | >>> d.append('j') # add a new entry to the right side |
| 181 | >>> d.appendleft('f') # add a new entry to the left side |
| 182 | >>> d # show the representation of the deque |
| 183 | deque(['f', 'g', 'h', 'i', 'j']) |
| 184 | |
| 185 | >>> d.pop() # return and remove the rightmost item |
| 186 | 'j' |
| 187 | >>> d.popleft() # return and remove the leftmost item |
| 188 | 'f' |
| 189 | >>> list(d) # list the contents of the deque |
| 190 | ['g', 'h', 'i'] |
| 191 | >>> d[0] # peek at leftmost item |
| 192 | 'g' |
| 193 | >>> d[-1] # peek at rightmost item |
| 194 | 'i' |
| 195 | |
| 196 | >>> list(reversed(d)) # list the contents of a deque in reverse |
| 197 | ['i', 'h', 'g'] |
| 198 | >>> 'h' in d # search the deque |
| 199 | True |
| 200 | >>> d.extend('jkl') # add multiple elements at once |
| 201 | >>> d |
| 202 | deque(['g', 'h', 'i', 'j', 'k', 'l']) |
| 203 | >>> d.rotate(1) # right rotation |
| 204 | >>> d |
| 205 | deque(['l', 'g', 'h', 'i', 'j', 'k']) |
| 206 | >>> d.rotate(-1) # left rotation |
| 207 | >>> d |
| 208 | deque(['g', 'h', 'i', 'j', 'k', 'l']) |
| 209 | |
| 210 | >>> deque(reversed(d)) # make a new deque in reverse order |
| 211 | deque(['l', 'k', 'j', 'i', 'h', 'g']) |
| 212 | >>> d.clear() # empty the deque |
| 213 | >>> d.pop() # cannot pop from an empty deque |
| 214 | Traceback (most recent call last): |
| 215 | File "<pyshell#6>", line 1, in -toplevel- |
| 216 | d.pop() |
| 217 | IndexError: pop from an empty deque |
| 218 | |
| 219 | >>> d.extendleft('abc') # extendleft() reverses the input order |
| 220 | >>> d |
| 221 | deque(['c', 'b', 'a']) |
| 222 | |
| 223 | |
| 224 | .. _deque-recipes: |
| 225 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 226 | :class:`deque` Recipes |
| 227 | ^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 228 | |
| 229 | This section shows various approaches to working with deques. |
| 230 | |
| 231 | The :meth:`rotate` method provides a way to implement :class:`deque` slicing and |
| 232 | deletion. For example, a pure python implementation of ``del d[n]`` relies on |
| 233 | the :meth:`rotate` method to position elements to be popped:: |
| 234 | |
| 235 | def delete_nth(d, n): |
| 236 | d.rotate(-n) |
| 237 | d.popleft() |
| 238 | d.rotate(n) |
| 239 | |
| 240 | To implement :class:`deque` slicing, use a similar approach applying |
| 241 | :meth:`rotate` to bring a target element to the left side of the deque. Remove |
| 242 | old entries with :meth:`popleft`, add new entries with :meth:`extend`, and then |
| 243 | reverse the rotation. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 244 | With minor variations on that approach, it is easy to implement Forth style |
| 245 | stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``, |
| 246 | ``rot``, and ``roll``. |
| 247 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 248 | Multi-pass data reduction algorithms can be succinctly expressed and efficiently |
| 249 | coded by extracting elements with multiple calls to :meth:`popleft`, applying |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 250 | a reduction function, and calling :meth:`append` to add the result back to the |
| 251 | deque. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 252 | |
| 253 | For example, building a balanced binary tree of nested lists entails reducing |
| 254 | two adjacent nodes into one by grouping them in a list:: |
| 255 | |
| 256 | >>> def maketree(iterable): |
| 257 | ... d = deque(iterable) |
| 258 | ... while len(d) > 1: |
| 259 | ... pair = [d.popleft(), d.popleft()] |
| 260 | ... d.append(pair) |
| 261 | ... return list(d) |
| 262 | ... |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 263 | >>> print(maketree('abcdefgh')) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 264 | [[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]] |
| 265 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 266 | Bounded length deques provide functionality similar to the ``tail`` filter |
| 267 | in Unix:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 268 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 269 | def tail(filename, n=10): |
| 270 | 'Return the last n lines of a file' |
| 271 | return deque(open(filename), n) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 272 | |
| 273 | .. _defaultdict-objects: |
| 274 | |
| 275 | :class:`defaultdict` objects |
| 276 | ---------------------------- |
| 277 | |
| 278 | |
| 279 | .. class:: defaultdict([default_factory[, ...]]) |
| 280 | |
| 281 | Returns a new dictionary-like object. :class:`defaultdict` is a subclass of the |
| 282 | builtin :class:`dict` class. It overrides one method and adds one writable |
| 283 | instance variable. The remaining functionality is the same as for the |
| 284 | :class:`dict` class and is not documented here. |
| 285 | |
| 286 | The first argument provides the initial value for the :attr:`default_factory` |
| 287 | attribute; it defaults to ``None``. All remaining arguments are treated the same |
| 288 | as if they were passed to the :class:`dict` constructor, including keyword |
| 289 | arguments. |
| 290 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 291 | |
| 292 | :class:`defaultdict` objects support the following method in addition to the |
| 293 | standard :class:`dict` operations: |
| 294 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 295 | .. method:: defaultdict.__missing__(key) |
| 296 | |
| 297 | If the :attr:`default_factory` attribute is ``None``, this raises an |
| 298 | :exc:`KeyError` exception with the *key* as argument. |
| 299 | |
| 300 | If :attr:`default_factory` is not ``None``, it is called without arguments to |
| 301 | provide a default value for the given *key*, this value is inserted in the |
| 302 | dictionary for the *key*, and returned. |
| 303 | |
| 304 | If calling :attr:`default_factory` raises an exception this exception is |
| 305 | propagated unchanged. |
| 306 | |
| 307 | This method is called by the :meth:`__getitem__` method of the :class:`dict` |
| 308 | class when the requested key is not found; whatever it returns or raises is then |
| 309 | returned or raised by :meth:`__getitem__`. |
| 310 | |
| 311 | :class:`defaultdict` objects support the following instance variable: |
| 312 | |
| 313 | |
| 314 | .. attribute:: defaultdict.default_factory |
| 315 | |
| 316 | This attribute is used by the :meth:`__missing__` method; it is initialized from |
| 317 | the first argument to the constructor, if present, or to ``None``, if absent. |
| 318 | |
| 319 | |
| 320 | .. _defaultdict-examples: |
| 321 | |
| 322 | :class:`defaultdict` Examples |
| 323 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 324 | |
| 325 | Using :class:`list` as the :attr:`default_factory`, it is easy to group a |
| 326 | sequence of key-value pairs into a dictionary of lists:: |
| 327 | |
| 328 | >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] |
| 329 | >>> d = defaultdict(list) |
| 330 | >>> for k, v in s: |
| 331 | ... d[k].append(v) |
| 332 | ... |
| 333 | >>> d.items() |
| 334 | [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] |
| 335 | |
| 336 | When each key is encountered for the first time, it is not already in the |
| 337 | mapping; so an entry is automatically created using the :attr:`default_factory` |
| 338 | function which returns an empty :class:`list`. The :meth:`list.append` |
| 339 | operation then attaches the value to the new list. When keys are encountered |
| 340 | again, the look-up proceeds normally (returning the list for that key) and the |
| 341 | :meth:`list.append` operation adds another value to the list. This technique is |
| 342 | simpler and faster than an equivalent technique using :meth:`dict.setdefault`:: |
| 343 | |
| 344 | >>> d = {} |
| 345 | >>> for k, v in s: |
| 346 | ... d.setdefault(k, []).append(v) |
| 347 | ... |
| 348 | >>> d.items() |
| 349 | [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] |
| 350 | |
| 351 | Setting the :attr:`default_factory` to :class:`int` makes the |
| 352 | :class:`defaultdict` useful for counting (like a bag or multiset in other |
| 353 | languages):: |
| 354 | |
| 355 | >>> s = 'mississippi' |
| 356 | >>> d = defaultdict(int) |
| 357 | >>> for k in s: |
| 358 | ... d[k] += 1 |
| 359 | ... |
| 360 | >>> d.items() |
| 361 | [('i', 4), ('p', 2), ('s', 4), ('m', 1)] |
| 362 | |
| 363 | When a letter is first encountered, it is missing from the mapping, so the |
| 364 | :attr:`default_factory` function calls :func:`int` to supply a default count of |
| 365 | zero. The increment operation then builds up the count for each letter. |
| 366 | |
| 367 | The function :func:`int` which always returns zero is just a special case of |
| 368 | constant functions. A faster and more flexible way to create constant functions |
| 369 | is to use a lambda function which can supply any constant value (not just |
| 370 | zero):: |
| 371 | |
| 372 | >>> def constant_factory(value): |
| 373 | ... return lambda: value |
| 374 | >>> d = defaultdict(constant_factory('<missing>')) |
| 375 | >>> d.update(name='John', action='ran') |
| 376 | >>> '%(name)s %(action)s to %(object)s' % d |
| 377 | 'John ran to <missing>' |
| 378 | |
| 379 | Setting the :attr:`default_factory` to :class:`set` makes the |
| 380 | :class:`defaultdict` useful for building a dictionary of sets:: |
| 381 | |
| 382 | >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)] |
| 383 | >>> d = defaultdict(set) |
| 384 | >>> for k, v in s: |
| 385 | ... d[k].add(v) |
| 386 | ... |
| 387 | >>> d.items() |
| 388 | [('blue', set([2, 4])), ('red', set([1, 3]))] |
| 389 | |
| 390 | |
| 391 | .. _named-tuple-factory: |
| 392 | |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 393 | :func:`namedtuple` Factory Function for Tuples with Named Fields |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 394 | ---------------------------------------------------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 395 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 396 | Named tuples assign meaning to each position in a tuple and allow for more readable, |
| 397 | self-documenting code. They can be used wherever regular tuples are used, and |
| 398 | they add the ability to access fields by name instead of position index. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 399 | |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 400 | .. function:: namedtuple(typename, fieldnames, [verbose]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 401 | |
| 402 | Returns a new tuple subclass named *typename*. The new subclass is used to |
| 403 | create tuple-like objects that have fields accessable by attribute lookup as |
| 404 | well as being indexable and iterable. Instances of the subclass also have a |
| 405 | helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__` |
| 406 | method which lists the tuple contents in a ``name=value`` format. |
| 407 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 408 | The *fieldnames* are a single string with each fieldname separated by whitespace |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 409 | and/or commas, for example ``'x y'`` or ``'x, y'``. Alternatively, *fieldnames* |
| 410 | can be a sequence of strings such as ``['x', 'y']``. |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 411 | |
| 412 | Any valid Python identifier may be used for a fieldname except for names |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 413 | starting with an underscore. Valid identifiers consist of letters, digits, |
| 414 | and underscores but do not start with a digit or underscore and cannot be |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 415 | a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 416 | or *raise*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 417 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 418 | If *verbose* is true, the class definition is printed just before being built. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 419 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 420 | Named tuple instances do not have per-instance dictionaries, so they are |
Thomas Wouters | 8ce81f7 | 2007-09-20 18:22:40 +0000 | [diff] [blame] | 421 | lightweight and require no more memory than regular tuples. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 422 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 423 | Example:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 424 | |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 425 | >>> Point = namedtuple('Point', 'x y', verbose=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 426 | class Point(tuple): |
| 427 | 'Point(x, y)' |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 428 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 429 | __slots__ = () |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 430 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 431 | _fields = ('x', 'y') |
| 432 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 433 | def __new__(cls, x, y): |
| 434 | return tuple.__new__(cls, (x, y)) |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 435 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 436 | @classmethod |
| 437 | def _make(cls, iterable): |
| 438 | 'Make a new Point object from a sequence or iterable' |
| 439 | result = tuple.__new__(cls, iterable) |
| 440 | if len(result) != 2: |
| 441 | raise TypeError('Expected 2 arguments, got %d' % len(result)) |
| 442 | return result |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 443 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 444 | def __repr__(self): |
| 445 | return 'Point(x=%r, y=%r)' % self |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 446 | |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 447 | def _asdict(t): |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 448 | 'Return a new dict which maps field names to their values' |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 449 | return {'x': t[0], 'y': t[1]} |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 450 | |
| 451 | def _replace(self, **kwds): |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 452 | 'Return a new Point object replacing specified fields with new values' |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 453 | result = self._make(map(kwds.pop, ('x', 'y'), self)) |
| 454 | if kwds: |
| 455 | raise ValueError('Got unexpected field names: %r' % kwds.keys()) |
| 456 | return result |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 457 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 458 | x = property(itemgetter(0)) |
| 459 | y = property(itemgetter(1)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 460 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 461 | >>> p = Point(11, y=22) # instantiate with positional or keyword arguments |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 462 | >>> p[0] + p[1] # indexable like the plain tuple (11, 22) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 463 | 33 |
| 464 | >>> x, y = p # unpack like a regular tuple |
| 465 | >>> x, y |
| 466 | (11, 22) |
| 467 | >>> p.x + p.y # fields also accessable by name |
| 468 | 33 |
| 469 | >>> p # readable __repr__ with a name=value style |
| 470 | Point(x=11, y=22) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 471 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 472 | Named tuples are especially useful for assigning field names to result tuples returned |
| 473 | by the :mod:`csv` or :mod:`sqlite3` modules:: |
| 474 | |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 475 | EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade') |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 476 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 477 | import csv |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 478 | for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 479 | print(emp.name, emp.title) |
| 480 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 481 | import sqlite3 |
| 482 | conn = sqlite3.connect('/companydata') |
| 483 | cursor = conn.cursor() |
| 484 | cursor.execute('SELECT name, age, title, department, paygrade FROM employees') |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 485 | for emp in map(EmployeeRecord._make, cursor.fetchall()): |
Christian Heimes | 0041223 | 2008-01-10 16:02:19 +0000 | [diff] [blame] | 486 | print(emp.name, emp.title) |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 487 | |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 488 | In addition to the methods inherited from tuples, named tuples support |
Christian Heimes | 2380ac7 | 2008-01-09 00:17:24 +0000 | [diff] [blame] | 489 | three additional methods and one attribute. To prevent conflicts with |
| 490 | field names, the method and attribute names start with an underscore. |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 491 | |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 492 | .. method:: somenamedtuple._make(iterable) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 493 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 494 | Class method that makes a new instance from an existing sequence or iterable. |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 495 | |
| 496 | :: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 497 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 498 | >>> t = [11, 22] |
| 499 | >>> Point._make(t) |
| 500 | Point(x=11, y=22) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 501 | |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 502 | .. method:: somenamedtuple._asdict() |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 503 | |
| 504 | Return a new dict which maps field names to their corresponding values: |
| 505 | |
| 506 | :: |
| 507 | |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 508 | >>> p._asdict() |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 509 | {'x': 11, 'y': 22} |
| 510 | |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 511 | .. method:: somenamedtuple._replace(kwargs) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 512 | |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 513 | Return a new instance of the named tuple replacing specified fields with new values: |
Thomas Wouters | 8ce81f7 | 2007-09-20 18:22:40 +0000 | [diff] [blame] | 514 | |
| 515 | :: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 516 | |
| 517 | >>> p = Point(x=11, y=22) |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 518 | >>> p._replace(x=33) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 519 | Point(x=33, y=22) |
| 520 | |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 521 | >>> for partnum, record in inventory.items(): |
Christian Heimes | 454f37b | 2008-01-10 00:10:02 +0000 | [diff] [blame] | 522 | ... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now()) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 523 | |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 524 | .. attribute:: somenamedtuple._fields |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 525 | |
Christian Heimes | 2380ac7 | 2008-01-09 00:17:24 +0000 | [diff] [blame] | 526 | Tuple of strings listing the field names. Useful for introspection |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 527 | and for creating new named tuple types from existing named tuples. |
Thomas Wouters | 8ce81f7 | 2007-09-20 18:22:40 +0000 | [diff] [blame] | 528 | |
| 529 | :: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 530 | |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 531 | >>> p._fields # view the field names |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 532 | ('x', 'y') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 533 | |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 534 | >>> Color = namedtuple('Color', 'red green blue') |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 535 | >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 536 | >>> Pixel(11, 22, 128, 255, 0) |
Christian Heimes | 454f37b | 2008-01-10 00:10:02 +0000 | [diff] [blame] | 537 | Pixel(x=11, y=22, red=128, green=255, blue=0) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 538 | |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 539 | To retrieve a field whose name is stored in a string, use the :func:`getattr` |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 540 | function:: |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 541 | |
| 542 | >>> getattr(p, 'x') |
| 543 | 11 |
| 544 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 545 | To convert a dictionary to a named tuple, use the double-star-operator [#]_:: |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 546 | |
| 547 | >>> d = {'x': 11, 'y': 22} |
| 548 | >>> Point(**d) |
| 549 | Point(x=11, y=22) |
| 550 | |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 551 | Since a named tuple is a regular Python class, it is easy to add or change |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 552 | functionality with a subclass. Here is how to add a calculated field and |
| 553 | a fixed-width print format:: |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 554 | |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 555 | >>> class Point(namedtuple('Point', 'x y')): |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 556 | ... __slots__ = () |
Christian Heimes | 454f37b | 2008-01-10 00:10:02 +0000 | [diff] [blame] | 557 | ... @property |
| 558 | ... def hypot(self): |
| 559 | ... return (self.x ** 2 + self.y ** 2) ** 0.5 |
| 560 | ... def __str__(self): |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 561 | ... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot) |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 562 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 563 | >>> for p in Point(3, 4), Point(14, 5/7.): |
Christian Heimes | 0041223 | 2008-01-10 16:02:19 +0000 | [diff] [blame] | 564 | ... print(p) |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 565 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 566 | Point: x= 3.000 y= 4.000 hypot= 5.000 |
| 567 | Point: x=14.000 y= 0.714 hypot=14.018 |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 568 | |
Christian Heimes | af98da1 | 2008-01-27 15:18:18 +0000 | [diff] [blame] | 569 | The subclass shown above sets ``__slots__`` to an empty tuple. This keeps |
Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 570 | keep memory requirements low by preventing the creation of instance dictionaries. |
| 571 | |
Christian Heimes | 2380ac7 | 2008-01-09 00:17:24 +0000 | [diff] [blame] | 572 | |
| 573 | Subclassing is not useful for adding new, stored fields. Instead, simply |
| 574 | create a new named tuple type from the :attr:`_fields` attribute:: |
| 575 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 576 | >>> Point3D = namedtuple('Point3D', Point._fields + ('z',)) |
Christian Heimes | 2380ac7 | 2008-01-09 00:17:24 +0000 | [diff] [blame] | 577 | |
| 578 | Default values can be implemented by using :meth:`_replace` to |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 579 | customize a prototype instance:: |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 580 | |
| 581 | >>> Account = namedtuple('Account', 'owner balance transaction_count') |
Christian Heimes | 587c2bf | 2008-01-19 16:21:02 +0000 | [diff] [blame] | 582 | >>> default_account = Account('<owner name>', 0.0, 0) |
| 583 | >>> johns_account = default_account._replace(owner='John') |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 584 | |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 585 | .. rubric:: Footnotes |
| 586 | |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 587 | .. [#] For information on the double-star-operator see |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 588 | :ref:`tut-unpacking-arguments` and :ref:`calls`. |
Raymond Hettinger | e4c96ad | 2008-02-06 01:23:58 +0000 | [diff] [blame] | 589 | |
| 590 | |
| 591 | |
| 592 | :class:`UserDict` objects |
Mark Summerfield | 8f2d006 | 2008-02-06 13:30:44 +0000 | [diff] [blame] | 593 | ------------------------- |
Raymond Hettinger | e4c96ad | 2008-02-06 01:23:58 +0000 | [diff] [blame] | 594 | |
| 595 | The class, :class:`UserDict` acts as a wrapper around dictionary objects. |
| 596 | The need for this class has been partially supplanted by the ability to |
| 597 | subclass directly from :class:`dict`; however, this class can be easier |
| 598 | to work with because the underlying dictionary is accessible as an |
| 599 | attribute. |
| 600 | |
| 601 | .. class:: UserDict([initialdata]) |
| 602 | |
| 603 | Class that simulates a dictionary. The instance's contents are kept in a |
| 604 | regular dictionary, which is accessible via the :attr:`data` attribute of |
| 605 | :class:`UserDict` instances. If *initialdata* is provided, :attr:`data` is |
| 606 | initialized with its contents; note that a reference to *initialdata* will not |
| 607 | be kept, allowing it be used for other purposes. |
| 608 | |
| 609 | In addition to supporting the methods and operations of mappings, |
| 610 | :class:`UserDict` and :class:`IterableUserDict` instances |
| 611 | provide the following attribute: |
| 612 | |
| 613 | .. attribute:: UserDict.data |
| 614 | |
| 615 | A real dictionary used to store the contents of the :class:`UserDict` class. |