1:mod:`!collections` --- Container datatypes 2=========================================== 3 4.. module:: collections 5 :synopsis: Container datatypes 6 7.. moduleauthor:: Raymond Hettinger <python@rcn.com> 8.. sectionauthor:: Raymond Hettinger <python@rcn.com> 9 10**Source code:** :source:`Lib/collections/__init__.py` 11 12.. testsetup:: * 13 14 from collections import * 15 import itertools 16 __name__ = '<doctest>' 17 18-------------- 19 20This module implements specialized container datatypes providing alternatives to 21Python's general purpose built-in containers, :class:`dict`, :class:`list`, 22:class:`set`, and :class:`tuple`. 23 24===================== ==================================================================== 25:func:`namedtuple` factory function for creating tuple subclasses with named fields 26:class:`deque` list-like container with fast appends and pops on either end 27:class:`ChainMap` dict-like class for creating a single view of multiple mappings 28:class:`Counter` dict subclass for counting :term:`hashable` objects 29:class:`OrderedDict` dict subclass that remembers the order entries were added 30:class:`defaultdict` dict subclass that calls a factory function to supply missing values 31:class:`UserDict` wrapper around dictionary objects for easier dict subclassing 32:class:`UserList` wrapper around list objects for easier list subclassing 33:class:`UserString` wrapper around string objects for easier string subclassing 34===================== ==================================================================== 35 36 37:class:`ChainMap` objects 38------------------------- 39 40.. versionadded:: 3.3 41 42A :class:`ChainMap` class is provided for quickly linking a number of mappings 43so they can be treated as a single unit. It is often much faster than creating 44a new dictionary and running multiple :meth:`~dict.update` calls. 45 46The class can be used to simulate nested scopes and is useful in templating. 47 48.. class:: ChainMap(*maps) 49 50 A :class:`ChainMap` groups multiple dicts or other mappings together to 51 create a single, updateable view. If no *maps* are specified, a single empty 52 dictionary is provided so that a new chain always has at least one mapping. 53 54 The underlying mappings are stored in a list. That list is public and can 55 be accessed or updated using the *maps* attribute. There is no other state. 56 57 Lookups search the underlying mappings successively until a key is found. In 58 contrast, writes, updates, and deletions only operate on the first mapping. 59 60 A :class:`ChainMap` incorporates the underlying mappings by reference. So, if 61 one of the underlying mappings gets updated, those changes will be reflected 62 in :class:`ChainMap`. 63 64 All of the usual dictionary methods are supported. In addition, there is a 65 *maps* attribute, a method for creating new subcontexts, and a property for 66 accessing all but the first mapping: 67 68 .. attribute:: maps 69 70 A user updateable list of mappings. The list is ordered from 71 first-searched to last-searched. It is the only stored state and can 72 be modified to change which mappings are searched. The list should 73 always contain at least one mapping. 74 75 .. method:: new_child(m=None, **kwargs) 76 77 Returns a new :class:`ChainMap` containing a new map followed by 78 all of the maps in the current instance. If ``m`` is specified, 79 it becomes the new map at the front of the list of mappings; if not 80 specified, an empty dict is used, so that a call to ``d.new_child()`` 81 is equivalent to: ``ChainMap({}, *d.maps)``. If any keyword arguments 82 are specified, they update passed map or new empty dict. This method 83 is used for creating subcontexts that can be updated without altering 84 values in any of the parent mappings. 85 86 .. versionchanged:: 3.4 87 The optional ``m`` parameter was added. 88 89 .. versionchanged:: 3.10 90 Keyword arguments support was added. 91 92 .. attribute:: parents 93 94 Property returning a new :class:`ChainMap` containing all of the maps in 95 the current instance except the first one. This is useful for skipping 96 the first map in the search. Use cases are similar to those for the 97 :keyword:`nonlocal` keyword used in :term:`nested scopes <nested 98 scope>`. The use cases also parallel those for the built-in 99 :func:`super` function. A reference to ``d.parents`` is equivalent to: 100 ``ChainMap(*d.maps[1:])``. 101 102 Note, the iteration order of a :class:`ChainMap` is determined by 103 scanning the mappings last to first:: 104 105 >>> baseline = {'music': 'bach', 'art': 'rembrandt'} 106 >>> adjustments = {'art': 'van gogh', 'opera': 'carmen'} 107 >>> list(ChainMap(adjustments, baseline)) 108 ['music', 'art', 'opera'] 109 110 This gives the same ordering as a series of :meth:`dict.update` calls 111 starting with the last mapping:: 112 113 >>> combined = baseline.copy() 114 >>> combined.update(adjustments) 115 >>> list(combined) 116 ['music', 'art', 'opera'] 117 118 .. versionchanged:: 3.9 119 Added support for ``|`` and ``|=`` operators, specified in :pep:`584`. 120 121.. seealso:: 122 123 * The `MultiContext class 124 <https://github.com/enthought/codetools/blob/4.0.0/codetools/contexts/multi_context.py>`_ 125 in the Enthought `CodeTools package 126 <https://github.com/enthought/codetools>`_ has options to support 127 writing to any mapping in the chain. 128 129 * Django's `Context class 130 <https://github.com/django/django/blob/main/django/template/context.py>`_ 131 for templating is a read-only chain of mappings. It also features 132 pushing and popping of contexts similar to the 133 :meth:`~collections.ChainMap.new_child` method and the 134 :attr:`~collections.ChainMap.parents` property. 135 136 * The `Nested Contexts recipe 137 <https://code.activestate.com/recipes/577434-nested-contexts-a-chain-of-mapping-objects/>`_ has options to control 138 whether writes and other mutations apply only to the first mapping or to 139 any mapping in the chain. 140 141 * A `greatly simplified read-only version of Chainmap 142 <https://code.activestate.com/recipes/305268/>`_. 143 144 145:class:`ChainMap` Examples and Recipes 146^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 147 148This section shows various approaches to working with chained maps. 149 150 151Example of simulating Python's internal lookup chain:: 152 153 import builtins 154 pylookup = ChainMap(locals(), globals(), vars(builtins)) 155 156Example of letting user specified command-line arguments take precedence over 157environment variables which in turn take precedence over default values:: 158 159 import os, argparse 160 161 defaults = {'color': 'red', 'user': 'guest'} 162 163 parser = argparse.ArgumentParser() 164 parser.add_argument('-u', '--user') 165 parser.add_argument('-c', '--color') 166 namespace = parser.parse_args() 167 command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} 168 169 combined = ChainMap(command_line_args, os.environ, defaults) 170 print(combined['color']) 171 print(combined['user']) 172 173Example patterns for using the :class:`ChainMap` class to simulate nested 174contexts:: 175 176 c = ChainMap() # Create root context 177 d = c.new_child() # Create nested child context 178 e = c.new_child() # Child of c, independent from d 179 e.maps[0] # Current context dictionary -- like Python's locals() 180 e.maps[-1] # Root context -- like Python's globals() 181 e.parents # Enclosing context chain -- like Python's nonlocals 182 183 d['x'] = 1 # Set value in current context 184 d['x'] # Get first key in the chain of contexts 185 del d['x'] # Delete from current context 186 list(d) # All nested values 187 k in d # Check all nested values 188 len(d) # Number of nested values 189 d.items() # All nested items 190 dict(d) # Flatten into a regular dictionary 191 192The :class:`ChainMap` class only makes updates (writes and deletions) to the 193first mapping in the chain while lookups will search the full chain. However, 194if deep writes and deletions are desired, it is easy to make a subclass that 195updates keys found deeper in the chain:: 196 197 class DeepChainMap(ChainMap): 198 'Variant of ChainMap that allows direct updates to inner scopes' 199 200 def __setitem__(self, key, value): 201 for mapping in self.maps: 202 if key in mapping: 203 mapping[key] = value 204 return 205 self.maps[0][key] = value 206 207 def __delitem__(self, key): 208 for mapping in self.maps: 209 if key in mapping: 210 del mapping[key] 211 return 212 raise KeyError(key) 213 214 >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) 215 >>> d['lion'] = 'orange' # update an existing key two levels down 216 >>> d['snake'] = 'red' # new keys get added to the topmost dict 217 >>> del d['elephant'] # remove an existing key one level down 218 >>> d # display result 219 DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'}) 220 221 222:class:`Counter` objects 223------------------------ 224 225A counter tool is provided to support convenient and rapid tallies. 226For example:: 227 228 >>> # Tally occurrences of words in a list 229 >>> cnt = Counter() 230 >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: 231 ... cnt[word] += 1 232 ... 233 >>> cnt 234 Counter({'blue': 3, 'red': 2, 'green': 1}) 235 236 >>> # Find the ten most common words in Hamlet 237 >>> import re 238 >>> words = re.findall(r'\w+', open('hamlet.txt').read().lower()) 239 >>> Counter(words).most_common(10) 240 [('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631), 241 ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)] 242 243.. class:: Counter([iterable-or-mapping]) 244 245 A :class:`Counter` is a :class:`dict` subclass for counting :term:`hashable` objects. 246 It is a collection where elements are stored as dictionary keys 247 and their counts are stored as dictionary values. Counts are allowed to be 248 any integer value including zero or negative counts. The :class:`Counter` 249 class is similar to bags or multisets in other languages. 250 251 Elements are counted from an *iterable* or initialized from another 252 *mapping* (or counter): 253 254 >>> c = Counter() # a new, empty counter 255 >>> c = Counter('gallahad') # a new counter from an iterable 256 >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping 257 >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args 258 259 Counter objects have a dictionary interface except that they return a zero 260 count for missing items instead of raising a :exc:`KeyError`: 261 262 >>> c = Counter(['eggs', 'ham']) 263 >>> c['bacon'] # count of a missing element is zero 264 0 265 266 Setting a count to zero does not remove an element from a counter. 267 Use ``del`` to remove it entirely: 268 269 >>> c['sausage'] = 0 # counter entry with a zero count 270 >>> del c['sausage'] # del actually removes the entry 271 272 .. versionadded:: 3.1 273 274 .. versionchanged:: 3.7 As a :class:`dict` subclass, :class:`Counter` 275 inherited the capability to remember insertion order. Math operations 276 on *Counter* objects also preserve order. Results are ordered 277 according to when an element is first encountered in the left operand 278 and then by the order encountered in the right operand. 279 280 Counter objects support additional methods beyond those available for all 281 dictionaries: 282 283 .. method:: elements() 284 285 Return an iterator over elements repeating each as many times as its 286 count. Elements are returned in the order first encountered. If an 287 element's count is less than one, :meth:`elements` will ignore it. 288 289 >>> c = Counter(a=4, b=2, c=0, d=-2) 290 >>> sorted(c.elements()) 291 ['a', 'a', 'a', 'a', 'b', 'b'] 292 293 .. method:: most_common([n]) 294 295 Return a list of the *n* most common elements and their counts from the 296 most common to the least. If *n* is omitted or ``None``, 297 :meth:`most_common` returns *all* elements in the counter. 298 Elements with equal counts are ordered in the order first encountered: 299 300 >>> Counter('abracadabra').most_common(3) 301 [('a', 5), ('b', 2), ('r', 2)] 302 303 .. method:: subtract([iterable-or-mapping]) 304 305 Elements are subtracted from an *iterable* or from another *mapping* 306 (or counter). Like :meth:`dict.update` but subtracts counts instead 307 of replacing them. Both inputs and outputs may be zero or negative. 308 309 >>> c = Counter(a=4, b=2, c=0, d=-2) 310 >>> d = Counter(a=1, b=2, c=3, d=4) 311 >>> c.subtract(d) 312 >>> c 313 Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6}) 314 315 .. versionadded:: 3.2 316 317 .. method:: total() 318 319 Compute the sum of the counts. 320 321 >>> c = Counter(a=10, b=5, c=0) 322 >>> c.total() 323 15 324 325 .. versionadded:: 3.10 326 327 The usual dictionary methods are available for :class:`Counter` objects 328 except for two which work differently for counters. 329 330 .. method:: fromkeys(iterable) 331 332 This class method is not implemented for :class:`Counter` objects. 333 334 .. method:: update([iterable-or-mapping]) 335 336 Elements are counted from an *iterable* or added-in from another 337 *mapping* (or counter). Like :meth:`dict.update` but adds counts 338 instead of replacing them. Also, the *iterable* is expected to be a 339 sequence of elements, not a sequence of ``(key, value)`` pairs. 340 341Counters support rich comparison operators for equality, subset, and 342superset relationships: ``==``, ``!=``, ``<``, ``<=``, ``>``, ``>=``. 343All of those tests treat missing elements as having zero counts so that 344``Counter(a=1) == Counter(a=1, b=0)`` returns true. 345 346.. versionchanged:: 3.10 347 Rich comparison operations were added. 348 349.. versionchanged:: 3.10 350 In equality tests, missing elements are treated as having zero counts. 351 Formerly, ``Counter(a=3)`` and ``Counter(a=3, b=0)`` were considered 352 distinct. 353 354Common patterns for working with :class:`Counter` objects:: 355 356 c.total() # total of all counts 357 c.clear() # reset all counts 358 list(c) # list unique elements 359 set(c) # convert to a set 360 dict(c) # convert to a regular dictionary 361 c.items() # access the (elem, cnt) pairs 362 Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs 363 c.most_common()[:-n-1:-1] # n least common elements 364 +c # remove zero and negative counts 365 366Several mathematical operations are provided for combining :class:`Counter` 367objects to produce multisets (counters that have counts greater than zero). 368Addition and subtraction combine counters by adding or subtracting the counts 369of corresponding elements. Intersection and union return the minimum and 370maximum of corresponding counts. Equality and inclusion compare 371corresponding counts. Each operation can accept inputs with signed 372counts, but the output will exclude results with counts of zero or less. 373 374.. doctest:: 375 376 >>> c = Counter(a=3, b=1) 377 >>> d = Counter(a=1, b=2) 378 >>> c + d # add two counters together: c[x] + d[x] 379 Counter({'a': 4, 'b': 3}) 380 >>> c - d # subtract (keeping only positive counts) 381 Counter({'a': 2}) 382 >>> c & d # intersection: min(c[x], d[x]) 383 Counter({'a': 1, 'b': 1}) 384 >>> c | d # union: max(c[x], d[x]) 385 Counter({'a': 3, 'b': 2}) 386 >>> c == d # equality: c[x] == d[x] 387 False 388 >>> c <= d # inclusion: c[x] <= d[x] 389 False 390 391Unary addition and subtraction are shortcuts for adding an empty counter 392or subtracting from an empty counter. 393 394 >>> c = Counter(a=2, b=-4) 395 >>> +c 396 Counter({'a': 2}) 397 >>> -c 398 Counter({'b': 4}) 399 400.. versionadded:: 3.3 401 Added support for unary plus, unary minus, and in-place multiset operations. 402 403.. note:: 404 405 Counters were primarily designed to work with positive integers to represent 406 running counts; however, care was taken to not unnecessarily preclude use 407 cases needing other types or negative values. To help with those use cases, 408 this section documents the minimum range and type restrictions. 409 410 * The :class:`Counter` class itself is a dictionary subclass with no 411 restrictions on its keys and values. The values are intended to be numbers 412 representing counts, but you *could* store anything in the value field. 413 414 * The :meth:`~Counter.most_common` method requires only that the values be orderable. 415 416 * For in-place operations such as ``c[key] += 1``, the value type need only 417 support addition and subtraction. So fractions, floats, and decimals would 418 work and negative values are supported. The same is also true for 419 :meth:`~Counter.update` and :meth:`~Counter.subtract` which allow negative and zero values 420 for both inputs and outputs. 421 422 * The multiset methods are designed only for use cases with positive values. 423 The inputs may be negative or zero, but only outputs with positive values 424 are created. There are no type restrictions, but the value type needs to 425 support addition, subtraction, and comparison. 426 427 * The :meth:`~Counter.elements` method requires integer counts. It ignores zero and 428 negative counts. 429 430.. seealso:: 431 432 * `Bag class <https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html>`_ 433 in Smalltalk. 434 435 * Wikipedia entry for `Multisets <https://en.wikipedia.org/wiki/Multiset>`_. 436 437 * `C++ multisets <http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm>`_ 438 tutorial with examples. 439 440 * For mathematical operations on multisets and their use cases, see 441 *Knuth, Donald. The Art of Computer Programming Volume II, 442 Section 4.6.3, Exercise 19*. 443 444 * To enumerate all distinct multisets of a given size over a given set of 445 elements, see :func:`itertools.combinations_with_replacement`:: 446 447 map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC 448 449 450:class:`deque` objects 451---------------------- 452 453.. class:: deque([iterable, [maxlen]]) 454 455 Returns a new deque object initialized left-to-right (using :meth:`append`) with 456 data from *iterable*. If *iterable* is not specified, the new deque is empty. 457 458 Deques are a generalization of stacks and queues (the name is pronounced "deck" 459 and is short for "double-ended queue"). Deques support thread-safe, memory 460 efficient appends and pops from either side of the deque with approximately the 461 same *O*\ (1) performance in either direction. 462 463 Though :class:`list` objects support similar operations, they are optimized for 464 fast fixed-length operations and incur *O*\ (*n*) memory movement costs for 465 ``pop(0)`` and ``insert(0, v)`` operations which change both the size and 466 position of the underlying data representation. 467 468 469 If *maxlen* is not specified or is ``None``, deques may grow to an 470 arbitrary length. Otherwise, the deque is bounded to the specified maximum 471 length. Once a bounded length deque is full, when new items are added, a 472 corresponding number of items are discarded from the opposite end. Bounded 473 length deques provide functionality similar to the ``tail`` filter in 474 Unix. They are also useful for tracking transactions and other pools of data 475 where only the most recent activity is of interest. 476 477 478 Deque objects support the following methods: 479 480 .. method:: append(x) 481 482 Add *x* to the right side of the deque. 483 484 485 .. method:: appendleft(x) 486 487 Add *x* to the left side of the deque. 488 489 490 .. method:: clear() 491 492 Remove all elements from the deque leaving it with length 0. 493 494 495 .. method:: copy() 496 497 Create a shallow copy of the deque. 498 499 .. versionadded:: 3.5 500 501 502 .. method:: count(x) 503 504 Count the number of deque elements equal to *x*. 505 506 .. versionadded:: 3.2 507 508 509 .. method:: extend(iterable) 510 511 Extend the right side of the deque by appending elements from the iterable 512 argument. 513 514 515 .. method:: extendleft(iterable) 516 517 Extend the left side of the deque by appending elements from *iterable*. 518 Note, the series of left appends results in reversing the order of 519 elements in the iterable argument. 520 521 522 .. method:: index(x[, start[, stop]]) 523 524 Return the position of *x* in the deque (at or after index *start* 525 and before index *stop*). Returns the first match or raises 526 :exc:`ValueError` if not found. 527 528 .. versionadded:: 3.5 529 530 531 .. method:: insert(i, x) 532 533 Insert *x* into the deque at position *i*. 534 535 If the insertion would cause a bounded deque to grow beyond *maxlen*, 536 an :exc:`IndexError` is raised. 537 538 .. versionadded:: 3.5 539 540 541 .. method:: pop() 542 543 Remove and return an element from the right side of the deque. If no 544 elements are present, raises an :exc:`IndexError`. 545 546 547 .. method:: popleft() 548 549 Remove and return an element from the left side of the deque. If no 550 elements are present, raises an :exc:`IndexError`. 551 552 553 .. method:: remove(value) 554 555 Remove the first occurrence of *value*. If not found, raises a 556 :exc:`ValueError`. 557 558 559 .. method:: reverse() 560 561 Reverse the elements of the deque in-place and then return ``None``. 562 563 .. versionadded:: 3.2 564 565 566 .. method:: rotate(n=1) 567 568 Rotate the deque *n* steps to the right. If *n* is negative, rotate 569 to the left. 570 571 When the deque is not empty, rotating one step to the right is equivalent 572 to ``d.appendleft(d.pop())``, and rotating one step to the left is 573 equivalent to ``d.append(d.popleft())``. 574 575 576 Deque objects also provide one read-only attribute: 577 578 .. attribute:: maxlen 579 580 Maximum size of a deque or ``None`` if unbounded. 581 582 .. versionadded:: 3.1 583 584 585In addition to the above, deques support iteration, pickling, ``len(d)``, 586``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with 587the :keyword:`in` operator, and subscript references such as ``d[0]`` to access 588the first element. Indexed access is *O*\ (1) at both ends but slows to *O*\ (*n*) in 589the middle. For fast random access, use lists instead. 590 591Starting in version 3.5, deques support ``__add__()``, ``__mul__()``, 592and ``__imul__()``. 593 594Example: 595 596.. doctest:: 597 598 >>> from collections import deque 599 >>> d = deque('ghi') # make a new deque with three items 600 >>> for elem in d: # iterate over the deque's elements 601 ... print(elem.upper()) 602 G 603 H 604 I 605 606 >>> d.append('j') # add a new entry to the right side 607 >>> d.appendleft('f') # add a new entry to the left side 608 >>> d # show the representation of the deque 609 deque(['f', 'g', 'h', 'i', 'j']) 610 611 >>> d.pop() # return and remove the rightmost item 612 'j' 613 >>> d.popleft() # return and remove the leftmost item 614 'f' 615 >>> list(d) # list the contents of the deque 616 ['g', 'h', 'i'] 617 >>> d[0] # peek at leftmost item 618 'g' 619 >>> d[-1] # peek at rightmost item 620 'i' 621 622 >>> list(reversed(d)) # list the contents of a deque in reverse 623 ['i', 'h', 'g'] 624 >>> 'h' in d # search the deque 625 True 626 >>> d.extend('jkl') # add multiple elements at once 627 >>> d 628 deque(['g', 'h', 'i', 'j', 'k', 'l']) 629 >>> d.rotate(1) # right rotation 630 >>> d 631 deque(['l', 'g', 'h', 'i', 'j', 'k']) 632 >>> d.rotate(-1) # left rotation 633 >>> d 634 deque(['g', 'h', 'i', 'j', 'k', 'l']) 635 636 >>> deque(reversed(d)) # make a new deque in reverse order 637 deque(['l', 'k', 'j', 'i', 'h', 'g']) 638 >>> d.clear() # empty the deque 639 >>> d.pop() # cannot pop from an empty deque 640 Traceback (most recent call last): 641 File "<pyshell#6>", line 1, in -toplevel- 642 d.pop() 643 IndexError: pop from an empty deque 644 645 >>> d.extendleft('abc') # extendleft() reverses the input order 646 >>> d 647 deque(['c', 'b', 'a']) 648 649 650:class:`deque` Recipes 651^^^^^^^^^^^^^^^^^^^^^^ 652 653This section shows various approaches to working with deques. 654 655Bounded length deques provide functionality similar to the ``tail`` filter 656in Unix:: 657 658 def tail(filename, n=10): 659 'Return the last n lines of a file' 660 with open(filename) as f: 661 return deque(f, n) 662 663Another approach to using deques is to maintain a sequence of recently 664added elements by appending to the right and popping to the left:: 665 666 def moving_average(iterable, n=3): 667 # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0 668 # https://en.wikipedia.org/wiki/Moving_average 669 it = iter(iterable) 670 d = deque(itertools.islice(it, n-1)) 671 d.appendleft(0) 672 s = sum(d) 673 for elem in it: 674 s += elem - d.popleft() 675 d.append(elem) 676 yield s / n 677 678A `round-robin scheduler 679<https://en.wikipedia.org/wiki/Round-robin_scheduling>`_ can be implemented with 680input iterators stored in a :class:`deque`. Values are yielded from the active 681iterator in position zero. If that iterator is exhausted, it can be removed 682with :meth:`~deque.popleft`; otherwise, it can be cycled back to the end with 683the :meth:`~deque.rotate` method:: 684 685 def roundrobin(*iterables): 686 "roundrobin('ABC', 'D', 'EF') --> A D E B F C" 687 iterators = deque(map(iter, iterables)) 688 while iterators: 689 try: 690 while True: 691 yield next(iterators[0]) 692 iterators.rotate(-1) 693 except StopIteration: 694 # Remove an exhausted iterator. 695 iterators.popleft() 696 697The :meth:`~deque.rotate` method provides a way to implement :class:`deque` slicing and 698deletion. For example, a pure Python implementation of ``del d[n]`` relies on 699the ``rotate()`` method to position elements to be popped:: 700 701 def delete_nth(d, n): 702 d.rotate(-n) 703 d.popleft() 704 d.rotate(n) 705 706To implement :class:`deque` slicing, use a similar approach applying 707:meth:`~deque.rotate` to bring a target element to the left side of the deque. Remove 708old entries with :meth:`~deque.popleft`, add new entries with :meth:`~deque.extend`, and then 709reverse the rotation. 710With minor variations on that approach, it is easy to implement Forth style 711stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``, 712``rot``, and ``roll``. 713 714 715:class:`defaultdict` objects 716---------------------------- 717 718.. class:: defaultdict(default_factory=None, /, [...]) 719 720 Return a new dictionary-like object. :class:`defaultdict` is a subclass of the 721 built-in :class:`dict` class. It overrides one method and adds one writable 722 instance variable. The remaining functionality is the same as for the 723 :class:`dict` class and is not documented here. 724 725 The first argument provides the initial value for the :attr:`default_factory` 726 attribute; it defaults to ``None``. All remaining arguments are treated the same 727 as if they were passed to the :class:`dict` constructor, including keyword 728 arguments. 729 730 731 :class:`defaultdict` objects support the following method in addition to the 732 standard :class:`dict` operations: 733 734 .. method:: __missing__(key) 735 736 If the :attr:`default_factory` attribute is ``None``, this raises a 737 :exc:`KeyError` exception with the *key* as argument. 738 739 If :attr:`default_factory` is not ``None``, it is called without arguments 740 to provide a default value for the given *key*, this value is inserted in 741 the dictionary for the *key*, and returned. 742 743 If calling :attr:`default_factory` raises an exception this exception is 744 propagated unchanged. 745 746 This method is called by the :meth:`~object.__getitem__` method of the 747 :class:`dict` class when the requested key is not found; whatever it 748 returns or raises is then returned or raised by :meth:`~object.__getitem__`. 749 750 Note that :meth:`__missing__` is *not* called for any operations besides 751 :meth:`~object.__getitem__`. This means that :meth:`get` will, like normal 752 dictionaries, return ``None`` as a default rather than using 753 :attr:`default_factory`. 754 755 756 :class:`defaultdict` objects support the following instance variable: 757 758 759 .. attribute:: default_factory 760 761 This attribute is used by the :meth:`__missing__` method; it is 762 initialized from the first argument to the constructor, if present, or to 763 ``None``, if absent. 764 765 .. versionchanged:: 3.9 766 Added merge (``|``) and update (``|=``) operators, specified in 767 :pep:`584`. 768 769 770:class:`defaultdict` Examples 771^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 772 773Using :class:`list` as the :attr:`~defaultdict.default_factory`, it is easy to group a 774sequence of key-value pairs into a dictionary of lists: 775 776 >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] 777 >>> d = defaultdict(list) 778 >>> for k, v in s: 779 ... d[k].append(v) 780 ... 781 >>> sorted(d.items()) 782 [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] 783 784When each key is encountered for the first time, it is not already in the 785mapping; so an entry is automatically created using the :attr:`~defaultdict.default_factory` 786function which returns an empty :class:`list`. The :meth:`!list.append` 787operation then attaches the value to the new list. When keys are encountered 788again, the look-up proceeds normally (returning the list for that key) and the 789:meth:`!list.append` operation adds another value to the list. This technique is 790simpler and faster than an equivalent technique using :meth:`dict.setdefault`: 791 792 >>> d = {} 793 >>> for k, v in s: 794 ... d.setdefault(k, []).append(v) 795 ... 796 >>> sorted(d.items()) 797 [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] 798 799Setting the :attr:`~defaultdict.default_factory` to :class:`int` makes the 800:class:`defaultdict` useful for counting (like a bag or multiset in other 801languages): 802 803 >>> s = 'mississippi' 804 >>> d = defaultdict(int) 805 >>> for k in s: 806 ... d[k] += 1 807 ... 808 >>> sorted(d.items()) 809 [('i', 4), ('m', 1), ('p', 2), ('s', 4)] 810 811When a letter is first encountered, it is missing from the mapping, so the 812:attr:`~defaultdict.default_factory` function calls :func:`int` to supply a default count of 813zero. The increment operation then builds up the count for each letter. 814 815The function :func:`int` which always returns zero is just a special case of 816constant functions. A faster and more flexible way to create constant functions 817is to use a lambda function which can supply any constant value (not just 818zero): 819 820 >>> def constant_factory(value): 821 ... return lambda: value 822 ... 823 >>> d = defaultdict(constant_factory('<missing>')) 824 >>> d.update(name='John', action='ran') 825 >>> '%(name)s %(action)s to %(object)s' % d 826 'John ran to <missing>' 827 828Setting the :attr:`~defaultdict.default_factory` to :class:`set` makes the 829:class:`defaultdict` useful for building a dictionary of sets: 830 831 >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)] 832 >>> d = defaultdict(set) 833 >>> for k, v in s: 834 ... d[k].add(v) 835 ... 836 >>> sorted(d.items()) 837 [('blue', {2, 4}), ('red', {1, 3})] 838 839 840:func:`namedtuple` Factory Function for Tuples with Named Fields 841---------------------------------------------------------------- 842 843Named tuples assign meaning to each position in a tuple and allow for more readable, 844self-documenting code. They can be used wherever regular tuples are used, and 845they add the ability to access fields by name instead of position index. 846 847.. function:: namedtuple(typename, field_names, *, rename=False, defaults=None, module=None) 848 849 Returns a new tuple subclass named *typename*. The new subclass is used to 850 create tuple-like objects that have fields accessible by attribute lookup as 851 well as being indexable and iterable. Instances of the subclass also have a 852 helpful docstring (with typename and field_names) and a helpful :meth:`__repr__` 853 method which lists the tuple contents in a ``name=value`` format. 854 855 The *field_names* are a sequence of strings such as ``['x', 'y']``. 856 Alternatively, *field_names* can be a single string with each fieldname 857 separated by whitespace and/or commas, for example ``'x y'`` or ``'x, y'``. 858 859 Any valid Python identifier may be used for a fieldname except for names 860 starting with an underscore. Valid identifiers consist of letters, digits, 861 and underscores but do not start with a digit or underscore and cannot be 862 a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, 863 or *raise*. 864 865 If *rename* is true, invalid fieldnames are automatically replaced 866 with positional names. For example, ``['abc', 'def', 'ghi', 'abc']`` is 867 converted to ``['abc', '_1', 'ghi', '_3']``, eliminating the keyword 868 ``def`` and the duplicate fieldname ``abc``. 869 870 *defaults* can be ``None`` or an :term:`iterable` of default values. 871 Since fields with a default value must come after any fields without a 872 default, the *defaults* are applied to the rightmost parameters. For 873 example, if the fieldnames are ``['x', 'y', 'z']`` and the defaults are 874 ``(1, 2)``, then ``x`` will be a required argument, ``y`` will default to 875 ``1``, and ``z`` will default to ``2``. 876 877 If *module* is defined, the :attr:`~type.__module__` attribute of the 878 named tuple is set to that value. 879 880 Named tuple instances do not have per-instance dictionaries, so they are 881 lightweight and require no more memory than regular tuples. 882 883 To support pickling, the named tuple class should be assigned to a variable 884 that matches *typename*. 885 886 .. versionchanged:: 3.1 887 Added support for *rename*. 888 889 .. versionchanged:: 3.6 890 The *verbose* and *rename* parameters became 891 :ref:`keyword-only arguments <keyword-only_parameter>`. 892 893 .. versionchanged:: 3.6 894 Added the *module* parameter. 895 896 .. versionchanged:: 3.7 897 Removed the *verbose* parameter and the :attr:`_source` attribute. 898 899 .. versionchanged:: 3.7 900 Added the *defaults* parameter and the :attr:`_field_defaults` 901 attribute. 902 903.. doctest:: 904 :options: +NORMALIZE_WHITESPACE 905 906 >>> # Basic example 907 >>> Point = namedtuple('Point', ['x', 'y']) 908 >>> p = Point(11, y=22) # instantiate with positional or keyword arguments 909 >>> p[0] + p[1] # indexable like the plain tuple (11, 22) 910 33 911 >>> x, y = p # unpack like a regular tuple 912 >>> x, y 913 (11, 22) 914 >>> p.x + p.y # fields also accessible by name 915 33 916 >>> p # readable __repr__ with a name=value style 917 Point(x=11, y=22) 918 919Named tuples are especially useful for assigning field names to result tuples returned 920by the :mod:`csv` or :mod:`sqlite3` modules:: 921 922 EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade') 923 924 import csv 925 for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))): 926 print(emp.name, emp.title) 927 928 import sqlite3 929 conn = sqlite3.connect('/companydata') 930 cursor = conn.cursor() 931 cursor.execute('SELECT name, age, title, department, paygrade FROM employees') 932 for emp in map(EmployeeRecord._make, cursor.fetchall()): 933 print(emp.name, emp.title) 934 935In addition to the methods inherited from tuples, named tuples support 936three additional methods and two attributes. To prevent conflicts with 937field names, the method and attribute names start with an underscore. 938 939.. classmethod:: somenamedtuple._make(iterable) 940 941 Class method that makes a new instance from an existing sequence or iterable. 942 943 .. doctest:: 944 945 >>> t = [11, 22] 946 >>> Point._make(t) 947 Point(x=11, y=22) 948 949.. method:: somenamedtuple._asdict() 950 951 Return a new :class:`dict` which maps field names to their corresponding 952 values: 953 954 .. doctest:: 955 956 >>> p = Point(x=11, y=22) 957 >>> p._asdict() 958 {'x': 11, 'y': 22} 959 960 .. versionchanged:: 3.1 961 Returns an :class:`OrderedDict` instead of a regular :class:`dict`. 962 963 .. versionchanged:: 3.8 964 Returns a regular :class:`dict` instead of an :class:`OrderedDict`. 965 As of Python 3.7, regular dicts are guaranteed to be ordered. If the 966 extra features of :class:`OrderedDict` are required, the suggested 967 remediation is to cast the result to the desired type: 968 ``OrderedDict(nt._asdict())``. 969 970.. method:: somenamedtuple._replace(**kwargs) 971 972 Return a new instance of the named tuple replacing specified fields with new 973 values:: 974 975 >>> p = Point(x=11, y=22) 976 >>> p._replace(x=33) 977 Point(x=33, y=22) 978 979 >>> for partnum, record in inventory.items(): 980 ... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now()) 981 982 Named tuples are also supported by generic function :func:`copy.replace`. 983 984 .. versionchanged:: 3.13 985 Raise :exc:`TypeError` instead of :exc:`ValueError` for invalid 986 keyword arguments. 987 988.. attribute:: somenamedtuple._fields 989 990 Tuple of strings listing the field names. Useful for introspection 991 and for creating new named tuple types from existing named tuples. 992 993 .. doctest:: 994 995 >>> p._fields # view the field names 996 ('x', 'y') 997 998 >>> Color = namedtuple('Color', 'red green blue') 999 >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) 1000 >>> Pixel(11, 22, 128, 255, 0) 1001 Pixel(x=11, y=22, red=128, green=255, blue=0) 1002 1003.. attribute:: somenamedtuple._field_defaults 1004 1005 Dictionary mapping field names to default values. 1006 1007 .. doctest:: 1008 1009 >>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0]) 1010 >>> Account._field_defaults 1011 {'balance': 0} 1012 >>> Account('premium') 1013 Account(type='premium', balance=0) 1014 1015To retrieve a field whose name is stored in a string, use the :func:`getattr` 1016function: 1017 1018 >>> getattr(p, 'x') 1019 11 1020 1021To convert a dictionary to a named tuple, use the double-star-operator 1022(as described in :ref:`tut-unpacking-arguments`): 1023 1024 >>> d = {'x': 11, 'y': 22} 1025 >>> Point(**d) 1026 Point(x=11, y=22) 1027 1028Since a named tuple is a regular Python class, it is easy to add or change 1029functionality with a subclass. Here is how to add a calculated field and 1030a fixed-width print format: 1031 1032.. doctest:: 1033 1034 >>> class Point(namedtuple('Point', ['x', 'y'])): 1035 ... __slots__ = () 1036 ... @property 1037 ... def hypot(self): 1038 ... return (self.x ** 2 + self.y ** 2) ** 0.5 1039 ... def __str__(self): 1040 ... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot) 1041 1042 >>> for p in Point(3, 4), Point(14, 5/7): 1043 ... print(p) 1044 Point: x= 3.000 y= 4.000 hypot= 5.000 1045 Point: x=14.000 y= 0.714 hypot=14.018 1046 1047The subclass shown above sets ``__slots__`` to an empty tuple. This helps 1048keep memory requirements low by preventing the creation of instance dictionaries. 1049 1050Subclassing is not useful for adding new, stored fields. Instead, simply 1051create a new named tuple type from the :attr:`~somenamedtuple._fields` attribute: 1052 1053 >>> Point3D = namedtuple('Point3D', Point._fields + ('z',)) 1054 1055Docstrings can be customized by making direct assignments to the ``__doc__`` 1056fields: 1057 1058 >>> Book = namedtuple('Book', ['id', 'title', 'authors']) 1059 >>> Book.__doc__ += ': Hardcover book in active collection' 1060 >>> Book.id.__doc__ = '13-digit ISBN' 1061 >>> Book.title.__doc__ = 'Title of first printing' 1062 >>> Book.authors.__doc__ = 'List of authors sorted by last name' 1063 1064.. versionchanged:: 3.5 1065 Property docstrings became writeable. 1066 1067.. seealso:: 1068 1069 * See :class:`typing.NamedTuple` for a way to add type hints for named 1070 tuples. It also provides an elegant notation using the :keyword:`class` 1071 keyword:: 1072 1073 class Component(NamedTuple): 1074 part_number: int 1075 weight: float 1076 description: Optional[str] = None 1077 1078 * See :meth:`types.SimpleNamespace` for a mutable namespace based on an 1079 underlying dictionary instead of a tuple. 1080 1081 * The :mod:`dataclasses` module provides a decorator and functions for 1082 automatically adding generated special methods to user-defined classes. 1083 1084 1085:class:`OrderedDict` objects 1086---------------------------- 1087 1088Ordered dictionaries are just like regular dictionaries but have some extra 1089capabilities relating to ordering operations. They have become less 1090important now that the built-in :class:`dict` class gained the ability 1091to remember insertion order (this new behavior became guaranteed in 1092Python 3.7). 1093 1094Some differences from :class:`dict` still remain: 1095 1096* The regular :class:`dict` was designed to be very good at mapping 1097 operations. Tracking insertion order was secondary. 1098 1099* The :class:`OrderedDict` was designed to be good at reordering operations. 1100 Space efficiency, iteration speed, and the performance of update 1101 operations were secondary. 1102 1103* The :class:`OrderedDict` algorithm can handle frequent reordering operations 1104 better than :class:`dict`. As shown in the recipes below, this makes it 1105 suitable for implementing various kinds of LRU caches. 1106 1107* The equality operation for :class:`OrderedDict` checks for matching order. 1108 1109 A regular :class:`dict` can emulate the order sensitive equality test with 1110 ``p == q and all(k1 == k2 for k1, k2 in zip(p, q))``. 1111 1112* The :meth:`popitem` method of :class:`OrderedDict` has a different 1113 signature. It accepts an optional argument to specify which item is popped. 1114 1115 A regular :class:`dict` can emulate OrderedDict's ``od.popitem(last=True)`` 1116 with ``d.popitem()`` which is guaranteed to pop the rightmost (last) item. 1117 1118 A regular :class:`dict` can emulate OrderedDict's ``od.popitem(last=False)`` 1119 with ``(k := next(iter(d)), d.pop(k))`` which will return and remove the 1120 leftmost (first) item if it exists. 1121 1122* :class:`OrderedDict` has a :meth:`move_to_end` method to efficiently 1123 reposition an element to an endpoint. 1124 1125 A regular :class:`dict` can emulate OrderedDict's ``od.move_to_end(k, 1126 last=True)`` with ``d[k] = d.pop(k)`` which will move the key and its 1127 associated value to the rightmost (last) position. 1128 1129 A regular :class:`dict` does not have an efficient equivalent for 1130 OrderedDict's ``od.move_to_end(k, last=False)`` which moves the key 1131 and its associated value to the leftmost (first) position. 1132 1133* Until Python 3.8, :class:`dict` lacked a :meth:`__reversed__` method. 1134 1135 1136.. class:: OrderedDict([items]) 1137 1138 Return an instance of a :class:`dict` subclass that has methods 1139 specialized for rearranging dictionary order. 1140 1141 .. versionadded:: 3.1 1142 1143 .. method:: popitem(last=True) 1144 1145 The :meth:`popitem` method for ordered dictionaries returns and removes a 1146 (key, value) pair. The pairs are returned in 1147 :abbr:`LIFO (last-in, first-out)` order if *last* is true 1148 or :abbr:`FIFO (first-in, first-out)` order if false. 1149 1150 .. method:: move_to_end(key, last=True) 1151 1152 Move an existing *key* to either end of an ordered dictionary. The item 1153 is moved to the right end if *last* is true (the default) or to the 1154 beginning if *last* is false. Raises :exc:`KeyError` if the *key* does 1155 not exist: 1156 1157 .. doctest:: 1158 1159 >>> d = OrderedDict.fromkeys('abcde') 1160 >>> d.move_to_end('b') 1161 >>> ''.join(d) 1162 'acdeb' 1163 >>> d.move_to_end('b', last=False) 1164 >>> ''.join(d) 1165 'bacde' 1166 1167 .. versionadded:: 3.2 1168 1169In addition to the usual mapping methods, ordered dictionaries also support 1170reverse iteration using :func:`reversed`. 1171 1172.. _collections_OrderedDict__eq__: 1173 1174Equality tests between :class:`OrderedDict` objects are order-sensitive 1175and are roughly equivalent to ``list(od1.items())==list(od2.items())``. 1176 1177Equality tests between :class:`OrderedDict` objects and other 1178:class:`~collections.abc.Mapping` objects are order-insensitive like regular 1179dictionaries. This allows :class:`OrderedDict` objects to be substituted 1180anywhere a regular dictionary is used. 1181 1182.. versionchanged:: 3.5 1183 The items, keys, and values :term:`views <dictionary view>` 1184 of :class:`OrderedDict` now support reverse iteration using :func:`reversed`. 1185 1186.. versionchanged:: 3.6 1187 With the acceptance of :pep:`468`, order is retained for keyword arguments 1188 passed to the :class:`OrderedDict` constructor and its :meth:`update` 1189 method. 1190 1191.. versionchanged:: 3.9 1192 Added merge (``|``) and update (``|=``) operators, specified in :pep:`584`. 1193 1194 1195:class:`OrderedDict` Examples and Recipes 1196^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1197 1198It is straightforward to create an ordered dictionary variant 1199that remembers the order the keys were *last* inserted. 1200If a new entry overwrites an existing entry, the 1201original insertion position is changed and moved to the end:: 1202 1203 class LastUpdatedOrderedDict(OrderedDict): 1204 'Store items in the order the keys were last added' 1205 1206 def __setitem__(self, key, value): 1207 super().__setitem__(key, value) 1208 self.move_to_end(key) 1209 1210An :class:`OrderedDict` would also be useful for implementing 1211variants of :func:`functools.lru_cache`: 1212 1213.. testcode:: 1214 1215 from collections import OrderedDict 1216 from time import time 1217 1218 class TimeBoundedLRU: 1219 "LRU Cache that invalidates and refreshes old entries." 1220 1221 def __init__(self, func, maxsize=128, maxage=30): 1222 self.cache = OrderedDict() # { args : (timestamp, result)} 1223 self.func = func 1224 self.maxsize = maxsize 1225 self.maxage = maxage 1226 1227 def __call__(self, *args): 1228 if args in self.cache: 1229 self.cache.move_to_end(args) 1230 timestamp, result = self.cache[args] 1231 if time() - timestamp <= self.maxage: 1232 return result 1233 result = self.func(*args) 1234 self.cache[args] = time(), result 1235 if len(self.cache) > self.maxsize: 1236 self.cache.popitem(last=False) 1237 return result 1238 1239 1240.. testcode:: 1241 1242 class MultiHitLRUCache: 1243 """ LRU cache that defers caching a result until 1244 it has been requested multiple times. 1245 1246 To avoid flushing the LRU cache with one-time requests, 1247 we don't cache until a request has been made more than once. 1248 1249 """ 1250 1251 def __init__(self, func, maxsize=128, maxrequests=4096, cache_after=1): 1252 self.requests = OrderedDict() # { uncached_key : request_count } 1253 self.cache = OrderedDict() # { cached_key : function_result } 1254 self.func = func 1255 self.maxrequests = maxrequests # max number of uncached requests 1256 self.maxsize = maxsize # max number of stored return values 1257 self.cache_after = cache_after 1258 1259 def __call__(self, *args): 1260 if args in self.cache: 1261 self.cache.move_to_end(args) 1262 return self.cache[args] 1263 result = self.func(*args) 1264 self.requests[args] = self.requests.get(args, 0) + 1 1265 if self.requests[args] <= self.cache_after: 1266 self.requests.move_to_end(args) 1267 if len(self.requests) > self.maxrequests: 1268 self.requests.popitem(last=False) 1269 else: 1270 self.requests.pop(args, None) 1271 self.cache[args] = result 1272 if len(self.cache) > self.maxsize: 1273 self.cache.popitem(last=False) 1274 return result 1275 1276.. doctest:: 1277 :hide: 1278 1279 >>> def square(x): 1280 ... return x * x 1281 ... 1282 >>> f = MultiHitLRUCache(square, maxsize=4, maxrequests=6) 1283 >>> list(map(f, range(10))) # First requests, don't cache 1284 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 1285 >>> f(4) # Cache the second request 1286 16 1287 >>> f(6) # Cache the second request 1288 36 1289 >>> f(2) # The first request aged out, so don't cache 1290 4 1291 >>> f(6) # Cache hit 1292 36 1293 >>> f(4) # Cache hit and move to front 1294 16 1295 >>> list(f.cache.values()) 1296 [36, 16] 1297 >>> set(f.requests).isdisjoint(f.cache) 1298 True 1299 >>> list(map(f, [9, 8, 7])) # Cache these second requests 1300 [81, 64, 49] 1301 >>> list(map(f, [7, 9])) # Cache hits 1302 [49, 81] 1303 >>> list(f.cache.values()) 1304 [16, 64, 49, 81] 1305 >>> set(f.requests).isdisjoint(f.cache) 1306 True 1307 1308:class:`UserDict` objects 1309------------------------- 1310 1311The class, :class:`UserDict` acts as a wrapper around dictionary objects. 1312The need for this class has been partially supplanted by the ability to 1313subclass directly from :class:`dict`; however, this class can be easier 1314to work with because the underlying dictionary is accessible as an 1315attribute. 1316 1317.. class:: UserDict([initialdata]) 1318 1319 Class that simulates a dictionary. The instance's contents are kept in a 1320 regular dictionary, which is accessible via the :attr:`data` attribute of 1321 :class:`UserDict` instances. If *initialdata* is provided, :attr:`data` is 1322 initialized with its contents; note that a reference to *initialdata* will not 1323 be kept, allowing it to be used for other purposes. 1324 1325 In addition to supporting the methods and operations of mappings, 1326 :class:`UserDict` instances provide the following attribute: 1327 1328 .. attribute:: data 1329 1330 A real dictionary used to store the contents of the :class:`UserDict` 1331 class. 1332 1333 1334 1335:class:`UserList` objects 1336------------------------- 1337 1338This class acts as a wrapper around list objects. It is a useful base class 1339for your own list-like classes which can inherit from them and override 1340existing methods or add new ones. In this way, one can add new behaviors to 1341lists. 1342 1343The need for this class has been partially supplanted by the ability to 1344subclass directly from :class:`list`; however, this class can be easier 1345to work with because the underlying list is accessible as an attribute. 1346 1347.. class:: UserList([list]) 1348 1349 Class that simulates a list. The instance's contents are kept in a regular 1350 list, which is accessible via the :attr:`data` attribute of :class:`UserList` 1351 instances. The instance's contents are initially set to a copy of *list*, 1352 defaulting to the empty list ``[]``. *list* can be any iterable, for 1353 example a real Python list or a :class:`UserList` object. 1354 1355 In addition to supporting the methods and operations of mutable sequences, 1356 :class:`UserList` instances provide the following attribute: 1357 1358 .. attribute:: data 1359 1360 A real :class:`list` object used to store the contents of the 1361 :class:`UserList` class. 1362 1363**Subclassing requirements:** Subclasses of :class:`UserList` are expected to 1364offer a constructor which can be called with either no arguments or one 1365argument. List operations which return a new sequence attempt to create an 1366instance of the actual implementation class. To do so, it assumes that the 1367constructor can be called with a single parameter, which is a sequence object 1368used as a data source. 1369 1370If a derived class does not wish to comply with this requirement, all of the 1371special methods supported by this class will need to be overridden; please 1372consult the sources for information about the methods which need to be provided 1373in that case. 1374 1375:class:`UserString` objects 1376--------------------------- 1377 1378The class, :class:`UserString` acts as a wrapper around string objects. 1379The need for this class has been partially supplanted by the ability to 1380subclass directly from :class:`str`; however, this class can be easier 1381to work with because the underlying string is accessible as an 1382attribute. 1383 1384.. class:: UserString(seq) 1385 1386 Class that simulates a string object. The instance's 1387 content is kept in a regular string object, which is accessible via the 1388 :attr:`data` attribute of :class:`UserString` instances. The instance's 1389 contents are initially set to a copy of *seq*. The *seq* argument can 1390 be any object which can be converted into a string using the built-in 1391 :func:`str` function. 1392 1393 In addition to supporting the methods and operations of strings, 1394 :class:`UserString` instances provide the following attribute: 1395 1396 .. attribute:: data 1397 1398 A real :class:`str` object used to store the contents of the 1399 :class:`UserString` class. 1400 1401 .. versionchanged:: 3.5 1402 New methods ``__getnewargs__``, ``__rmod__``, ``casefold``, 1403 ``format_map``, ``isprintable``, and ``maketrans``. 1404