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