Debian Codegraph @

Doc/library/collections.rst

raw
1 :mod:`!collections` --- Container datatypes
2 ===========================================
3
4 .. module:: collections
5 :synopsis: Container datatypes
6
7 .. moduleauthor:: Raymond Hettinger <[email protected]>
8 .. sectionauthor:: Raymond Hettinger <[email protected]>
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
20 This module implements specialized container datatypes providing alternatives to
21 Python'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
42 A :class:`ChainMap` class is provided for quickly linking a number of mappings
43 so they can be treated as a single unit. It is often much faster than creating
44 a new dictionary and running multiple :meth:`~dict.update` calls.
45
46 The 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
148 This section shows various approaches to working with chained maps.
149
150
151 Example of simulating Python's internal lookup chain::
152
153 import builtins
154 pylookup = ChainMap(locals(), globals(), vars(builtins))
155
156 Example of letting user specified command-line arguments take precedence over
157 environment 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
173 Example patterns for using the :class:`ChainMap` class to simulate nested
174 contexts::
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
192 The :class:`ChainMap` class only makes updates (writes and deletions) to the
193 first mapping in the chain while lookups will search the full chain. However,
194 if deep writes and deletions are desired, it is easy to make a subclass that
195 updates 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
225 A counter tool is provided to support convenient and rapid tallies.
226 For 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
341 Counters support rich comparison operators for equality, subset, and
342 superset relationships: ``==``, ``!=``, ``<``, ``<=``, ``>``, ``>=``.
343 All 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
354 Common 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
366 Several mathematical operations are provided for combining :class:`Counter`
367 objects to produce multisets (counters that have counts greater than zero).
368 Addition and subtraction combine counters by adding or subtracting the counts
369 of corresponding elements. Intersection and union return the minimum and
370 maximum of corresponding counts. Equality and inclusion compare
371 corresponding counts. Each operation can accept inputs with signed
372 counts, 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
391 Unary addition and subtraction are shortcuts for adding an empty counter
392 or 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
585 In addition to the above, deques support iteration, pickling, ``len(d)``,
586 ``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with
587 the :keyword:`in` operator, and subscript references such as ``d[0]`` to access
588 the first element. Indexed access is *O*\ (1) at both ends but slows to *O*\ (*n*) in
589 the middle. For fast random access, use lists instead.
590
591 Starting in version 3.5, deques support ``__add__()``, ``__mul__()``,
592 and ``__imul__()``.
593
594 Example:
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
653 This section shows various approaches to working with deques.
654
655 Bounded length deques provide functionality similar to the ``tail`` filter
656 in 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
663 Another approach to using deques is to maintain a sequence of recently
664 added 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
678 A `round-robin scheduler
679 <https://en.wikipedia.org/wiki/Round-robin_scheduling>`_ can be implemented with
680 input iterators stored in a :class:`deque`. Values are yielded from the active
681 iterator in position zero. If that iterator is exhausted, it can be removed
682 with :meth:`~deque.popleft`; otherwise, it can be cycled back to the end with
683 the :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
697 The :meth:`~deque.rotate` method provides a way to implement :class:`deque` slicing and
698 deletion. For example, a pure Python implementation of ``del d[n]`` relies on
699 the ``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
706 To 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
708 old entries with :meth:`~deque.popleft`, add new entries with :meth:`~deque.extend`, and then
709 reverse the rotation.
710 With minor variations on that approach, it is easy to implement Forth style
711 stack 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:`~dict.get` will, like
752 normal 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:`~defaultdict.__missing__` method;
762 it is initialized from the first argument to the constructor, if present,
763 or to ``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
773 Using :class:`list` as the :attr:`~defaultdict.default_factory`, it is easy to group a
774 sequence 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
784 When each key is encountered for the first time, it is not already in the
785 mapping; so an entry is automatically created using the :attr:`~defaultdict.default_factory`
786 function which returns an empty :class:`list`. The :meth:`list.append`
787 operation then attaches the value to the new list. When keys are encountered
788 again, 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
790 simpler 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
799 Setting the :attr:`~defaultdict.default_factory` to :class:`int` makes the
800 :class:`defaultdict` useful for counting (like a bag or multiset in other
801 languages):
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
811 When 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
813 zero. The increment operation then builds up the count for each letter.
814
815 The function :func:`int` which always returns zero is just a special case of
816 constant functions. A faster and more flexible way to create constant functions
817 is to use a lambda function which can supply any constant value (not just
818 zero):
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
828 Setting 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
843 Named tuples assign meaning to each position in a tuple and allow for more readable,
844 self-documenting code. They can be used wherever regular tuples are used, and
845 they 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
853 :meth:`~object.__repr__` method which lists the tuple contents in a ``name=value``
854 format.
855
856 The *field_names* are a sequence of strings such as ``['x', 'y']``.
857 Alternatively, *field_names* can be a single string with each fieldname
858 separated by whitespace and/or commas, for example ``'x y'`` or ``'x, y'``.
859
860 Any valid Python identifier may be used for a fieldname except for names
861 starting with an underscore. Valid identifiers consist of letters, digits,
862 and underscores but do not start with a digit or underscore and cannot be
863 a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*,
864 or *raise*.
865
866 If *rename* is true, invalid fieldnames are automatically replaced
867 with positional names. For example, ``['abc', 'def', 'ghi', 'abc']`` is
868 converted to ``['abc', '_1', 'ghi', '_3']``, eliminating the keyword
869 ``def`` and the duplicate fieldname ``abc``.
870
871 *defaults* can be ``None`` or an :term:`iterable` of default values.
872 Since fields with a default value must come after any fields without a
873 default, the *defaults* are applied to the rightmost parameters. For
874 example, if the fieldnames are ``['x', 'y', 'z']`` and the defaults are
875 ``(1, 2)``, then ``x`` will be a required argument, ``y`` will default to
876 ``1``, and ``z`` will default to ``2``.
877
878 If *module* is defined, the :attr:`~type.__module__` attribute of the
879 named tuple is set to that value.
880
881 Named tuple instances do not have per-instance dictionaries, so they are
882 lightweight and require no more memory than regular tuples.
883
884 To support pickling, the named tuple class should be assigned to a variable
885 that matches *typename*.
886
887 .. versionchanged:: 3.1
888 Added support for *rename*.
889
890 .. versionchanged:: 3.6
891 The *verbose* and *rename* parameters became
892 :ref:`keyword-only arguments <keyword-only_parameter>`.
893
894 .. versionchanged:: 3.6
895 Added the *module* parameter.
896
897 .. versionchanged:: 3.7
898 Removed the *verbose* parameter and the :attr:`!_source` attribute.
899
900 .. versionchanged:: 3.7
901 Added the *defaults* parameter and the :attr:`~somenamedtuple._field_defaults`
902 attribute.
903
904 .. doctest::
905 :options: +NORMALIZE_WHITESPACE
906
907 >>> # Basic example
908 >>> Point = namedtuple('Point', ['x', 'y'])
909 >>> p = Point(11, y=22) # instantiate with positional or keyword arguments
910 >>> p[0] + p[1] # indexable like the plain tuple (11, 22)
911 33
912 >>> x, y = p # unpack like a regular tuple
913 >>> x, y
914 (11, 22)
915 >>> p.x + p.y # fields also accessible by name
916 33
917 >>> p # readable __repr__ with a name=value style
918 Point(x=11, y=22)
919
920 Named tuples are especially useful for assigning field names to result tuples returned
921 by the :mod:`csv` or :mod:`sqlite3` modules::
922
923 EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
924
925 import csv
926 for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
927 print(emp.name, emp.title)
928
929 import sqlite3
930 conn = sqlite3.connect('/companydata')
931 cursor = conn.cursor()
932 cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
933 for emp in map(EmployeeRecord._make, cursor.fetchall()):
934 print(emp.name, emp.title)
935
936 In addition to the methods inherited from tuples, named tuples support
937 three additional methods and two attributes. To prevent conflicts with
938 field names, the method and attribute names start with an underscore.
939
940 .. classmethod:: somenamedtuple._make(iterable)
941
942 Class method that makes a new instance from an existing sequence or iterable.
943
944 .. doctest::
945
946 >>> t = [11, 22]
947 >>> Point._make(t)
948 Point(x=11, y=22)
949
950 .. method:: somenamedtuple._asdict()
951
952 Return a new :class:`dict` which maps field names to their corresponding
953 values:
954
955 .. doctest::
956
957 >>> p = Point(x=11, y=22)
958 >>> p._asdict()
959 {'x': 11, 'y': 22}
960
961 .. versionchanged:: 3.1
962 Returns an :class:`OrderedDict` instead of a regular :class:`dict`.
963
964 .. versionchanged:: 3.8
965 Returns a regular :class:`dict` instead of an :class:`OrderedDict`.
966 As of Python 3.7, regular dicts are guaranteed to be ordered. If the
967 extra features of :class:`OrderedDict` are required, the suggested
968 remediation is to cast the result to the desired type:
969 ``OrderedDict(nt._asdict())``.
970
971 .. method:: somenamedtuple._replace(**kwargs)
972
973 Return a new instance of the named tuple replacing specified fields with new
974 values::
975
976 >>> p = Point(x=11, y=22)
977 >>> p._replace(x=33)
978 Point(x=33, y=22)
979
980 >>> for partnum, record in inventory.items():
981 ... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
982
983 Named tuples are also supported by generic function :func:`copy.replace`.
984
985 .. versionchanged:: 3.13
986 Raise :exc:`TypeError` instead of :exc:`ValueError` for invalid
987 keyword arguments.
988
989 .. attribute:: somenamedtuple._fields
990
991 Tuple of strings listing the field names. Useful for introspection
992 and for creating new named tuple types from existing named tuples.
993
994 .. doctest::
995
996 >>> p._fields # view the field names
997 ('x', 'y')
998
999 >>> Color = namedtuple('Color', 'red green blue')
1000 >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
1001 >>> Pixel(11, 22, 128, 255, 0)
1002 Pixel(x=11, y=22, red=128, green=255, blue=0)
1003
1004 .. attribute:: somenamedtuple._field_defaults
1005
1006 Dictionary mapping field names to default values.
1007
1008 .. doctest::
1009
1010 >>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
1011 >>> Account._field_defaults
1012 {'balance': 0}
1013 >>> Account('premium')
1014 Account(type='premium', balance=0)
1015
1016 To retrieve a field whose name is stored in a string, use the :func:`getattr`
1017 function:
1018
1019 >>> getattr(p, 'x')
1020 11
1021
1022 To convert a dictionary to a named tuple, use the double-star-operator
1023 (as described in :ref:`tut-unpacking-arguments`):
1024
1025 >>> d = {'x': 11, 'y': 22}
1026 >>> Point(**d)
1027 Point(x=11, y=22)
1028
1029 Since a named tuple is a regular Python class, it is easy to add or change
1030 functionality with a subclass. Here is how to add a calculated field and
1031 a fixed-width print format:
1032
1033 .. doctest::
1034
1035 >>> class Point(namedtuple('Point', ['x', 'y'])):
1036 ... __slots__ = ()
1037 ... @property
1038 ... def hypot(self):
1039 ... return (self.x ** 2 + self.y ** 2) ** 0.5
1040 ... def __str__(self):
1041 ... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
1042
1043 >>> for p in Point(3, 4), Point(14, 5/7):
1044 ... print(p)
1045 Point: x= 3.000 y= 4.000 hypot= 5.000
1046 Point: x=14.000 y= 0.714 hypot=14.018
1047
1048 The subclass shown above sets ``__slots__`` to an empty tuple. This helps
1049 keep memory requirements low by preventing the creation of instance dictionaries.
1050
1051 Subclassing is not useful for adding new, stored fields. Instead, simply
1052 create a new named tuple type from the :attr:`~somenamedtuple._fields` attribute:
1053
1054 >>> Point3D = namedtuple('Point3D', Point._fields + ('z',))
1055
1056 Docstrings can be customized by making direct assignments to the ``__doc__``
1057 fields:
1058
1059 >>> Book = namedtuple('Book', ['id', 'title', 'authors'])
1060 >>> Book.__doc__ += ': Hardcover book in active collection'
1061 >>> Book.id.__doc__ = '13-digit ISBN'
1062 >>> Book.title.__doc__ = 'Title of first printing'
1063 >>> Book.authors.__doc__ = 'List of authors sorted by last name'
1064
1065 .. versionchanged:: 3.5
1066 Property docstrings became writeable.
1067
1068 .. seealso::
1069
1070 * See :class:`typing.NamedTuple` for a way to add type hints for named
1071 tuples. It also provides an elegant notation using the :keyword:`class`
1072 keyword::
1073
1074 class Component(NamedTuple):
1075 part_number: int
1076 weight: float
1077 description: Optional[str] = None
1078
1079 * See :meth:`types.SimpleNamespace` for a mutable namespace based on an
1080 underlying dictionary instead of a tuple.
1081
1082 * The :mod:`dataclasses` module provides a decorator and functions for
1083 automatically adding generated special methods to user-defined classes.
1084
1085
1086 :class:`OrderedDict` objects
1087 ----------------------------
1088
1089 Ordered dictionaries are just like regular dictionaries but have some extra
1090 capabilities relating to ordering operations. They have become less
1091 important now that the built-in :class:`dict` class gained the ability
1092 to remember insertion order (this new behavior became guaranteed in
1093 Python 3.7).
1094
1095 Some differences from :class:`dict` still remain:
1096
1097 * The regular :class:`dict` was designed to be very good at mapping
1098 operations. Tracking insertion order was secondary.
1099
1100 * The :class:`OrderedDict` was designed to be good at reordering operations.
1101 Space efficiency, iteration speed, and the performance of update
1102 operations were secondary.
1103
1104 * The :class:`OrderedDict` algorithm can handle frequent reordering operations
1105 better than :class:`dict`. As shown in the recipes below, this makes it
1106 suitable for implementing various kinds of LRU caches.
1107
1108 * The equality operation for :class:`OrderedDict` checks for matching order.
1109
1110 A regular :class:`dict` can emulate the order sensitive equality test with
1111 ``p == q and all(k1 == k2 for k1, k2 in zip(p, q))``.
1112
1113 * The :meth:`~OrderedDict.popitem` method of :class:`OrderedDict` has a different
1114 signature. It accepts an optional argument to specify which item is popped.
1115
1116 A regular :class:`dict` can emulate OrderedDict's ``od.popitem(last=True)``
1117 with ``d.popitem()`` which is guaranteed to pop the rightmost (last) item.
1118
1119 A regular :class:`dict` can emulate OrderedDict's ``od.popitem(last=False)``
1120 with ``(k := next(iter(d)), d.pop(k))`` which will return and remove the
1121 leftmost (first) item if it exists.
1122
1123 * :class:`OrderedDict` has a :meth:`~OrderedDict.move_to_end` method to efficiently
1124 reposition an element to an endpoint.
1125
1126 A regular :class:`dict` can emulate OrderedDict's ``od.move_to_end(k,
1127 last=True)`` with ``d[k] = d.pop(k)`` which will move the key and its
1128 associated value to the rightmost (last) position.
1129
1130 A regular :class:`dict` does not have an efficient equivalent for
1131 OrderedDict's ``od.move_to_end(k, last=False)`` which moves the key
1132 and its associated value to the leftmost (first) position.
1133
1134 * Until Python 3.8, :class:`dict` lacked a :meth:`~object.__reversed__` method.
1135
1136
1137 .. class:: OrderedDict([items])
1138
1139 Return an instance of a :class:`dict` subclass that has methods
1140 specialized for rearranging dictionary order.
1141
1142 .. versionadded:: 3.1
1143
1144 .. method:: popitem(last=True)
1145
1146 The :meth:`popitem` method for ordered dictionaries returns and removes a
1147 (key, value) pair. The pairs are returned in
1148 :abbr:`LIFO (last-in, first-out)` order if *last* is true
1149 or :abbr:`FIFO (first-in, first-out)` order if false.
1150
1151 .. method:: move_to_end(key, last=True)
1152
1153 Move an existing *key* to either end of an ordered dictionary. The item
1154 is moved to the right end if *last* is true (the default) or to the
1155 beginning if *last* is false. Raises :exc:`KeyError` if the *key* does
1156 not exist:
1157
1158 .. doctest::
1159
1160 >>> d = OrderedDict.fromkeys('abcde')
1161 >>> d.move_to_end('b')
1162 >>> ''.join(d)
1163 'acdeb'
1164 >>> d.move_to_end('b', last=False)
1165 >>> ''.join(d)
1166 'bacde'
1167
1168 .. versionadded:: 3.2
1169
1170 In addition to the usual mapping methods, ordered dictionaries also support
1171 reverse iteration using :func:`reversed`.
1172
1173 .. _collections_OrderedDict__eq__:
1174
1175 Equality tests between :class:`OrderedDict` objects are order-sensitive
1176 and are roughly equivalent to ``list(od1.items())==list(od2.items())``.
1177
1178 Equality tests between :class:`OrderedDict` objects and other
1179 :class:`~collections.abc.Mapping` objects are order-insensitive like regular
1180 dictionaries. This allows :class:`OrderedDict` objects to be substituted
1181 anywhere a regular dictionary is used.
1182
1183 .. versionchanged:: 3.5
1184 The items, keys, and values :term:`views <dictionary view>`
1185 of :class:`OrderedDict` now support reverse iteration using :func:`reversed`.
1186
1187 .. versionchanged:: 3.6
1188 With the acceptance of :pep:`468`, order is retained for keyword arguments
1189 passed to the :class:`OrderedDict` constructor and its :meth:`~dict.update`
1190 method.
1191
1192 .. versionchanged:: 3.9
1193 Added merge (``|``) and update (``|=``) operators, specified in :pep:`584`.
1194
1195
1196 :class:`OrderedDict` Examples and Recipes
1197 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1198
1199 It is straightforward to create an ordered dictionary variant
1200 that remembers the order the keys were *last* inserted.
1201 If a new entry overwrites an existing entry, the
1202 original insertion position is changed and moved to the end::
1203
1204 class LastUpdatedOrderedDict(OrderedDict):
1205 'Store items in the order the keys were last added'
1206
1207 def __setitem__(self, key, value):
1208 super().__setitem__(key, value)
1209 self.move_to_end(key)
1210
1211 An :class:`OrderedDict` would also be useful for implementing
1212 variants of :func:`functools.lru_cache`:
1213
1214 .. testcode::
1215
1216 from collections import OrderedDict
1217 from time import time
1218
1219 class TimeBoundedLRU:
1220 "LRU Cache that invalidates and refreshes old entries."
1221
1222 def __init__(self, func, maxsize=128, maxage=30):
1223 self.cache = OrderedDict() # { args : (timestamp, result)}
1224 self.func = func
1225 self.maxsize = maxsize
1226 self.maxage = maxage
1227
1228 def __call__(self, *args):
1229 if args in self.cache:
1230 self.cache.move_to_end(args)
1231 timestamp, result = self.cache[args]
1232 if time() - timestamp <= self.maxage:
1233 return result
1234 result = self.func(*args)
1235 self.cache[args] = time(), result
1236 if len(self.cache) > self.maxsize:
1237 self.cache.popitem(last=False)
1238 return result
1239
1240
1241 .. testcode::
1242
1243 class MultiHitLRUCache:
1244 """ LRU cache that defers caching a result until
1245 it has been requested multiple times.
1246
1247 To avoid flushing the LRU cache with one-time requests,
1248 we don't cache until a request has been made more than once.
1249
1250 """
1251
1252 def __init__(self, func, maxsize=128, maxrequests=4096, cache_after=1):
1253 self.requests = OrderedDict() # { uncached_key : request_count }
1254 self.cache = OrderedDict() # { cached_key : function_result }
1255 self.func = func
1256 self.maxrequests = maxrequests # max number of uncached requests
1257 self.maxsize = maxsize # max number of stored return values
1258 self.cache_after = cache_after
1259
1260 def __call__(self, *args):
1261 if args in self.cache:
1262 self.cache.move_to_end(args)
1263 return self.cache[args]
1264 result = self.func(*args)
1265 self.requests[args] = self.requests.get(args, 0) + 1
1266 if self.requests[args] <= self.cache_after:
1267 self.requests.move_to_end(args)
1268 if len(self.requests) > self.maxrequests:
1269 self.requests.popitem(last=False)
1270 else:
1271 self.requests.pop(args, None)
1272 self.cache[args] = result
1273 if len(self.cache) > self.maxsize:
1274 self.cache.popitem(last=False)
1275 return result
1276
1277 .. doctest::
1278 :hide:
1279
1280 >>> def square(x):
1281 ... return x * x
1282 ...
1283 >>> f = MultiHitLRUCache(square, maxsize=4, maxrequests=6)
1284 >>> list(map(f, range(10))) # First requests, don't cache
1285 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
1286 >>> f(4) # Cache the second request
1287 16
1288 >>> f(6) # Cache the second request
1289 36
1290 >>> f(2) # The first request aged out, so don't cache
1291 4
1292 >>> f(6) # Cache hit
1293 36
1294 >>> f(4) # Cache hit and move to front
1295 16
1296 >>> list(f.cache.values())
1297 [36, 16]
1298 >>> set(f.requests).isdisjoint(f.cache)
1299 True
1300 >>> list(map(f, [9, 8, 7])) # Cache these second requests
1301 [81, 64, 49]
1302 >>> list(map(f, [7, 9])) # Cache hits
1303 [49, 81]
1304 >>> list(f.cache.values())
1305 [16, 64, 49, 81]
1306 >>> set(f.requests).isdisjoint(f.cache)
1307 True
1308
1309 :class:`UserDict` objects
1310 -------------------------
1311
1312 The class, :class:`UserDict` acts as a wrapper around dictionary objects.
1313 The need for this class has been partially supplanted by the ability to
1314 subclass directly from :class:`dict`; however, this class can be easier
1315 to work with because the underlying dictionary is accessible as an
1316 attribute.
1317
1318 .. class:: UserDict([initialdata])
1319
1320 Class that simulates a dictionary. The instance's contents are kept in a
1321 regular dictionary, which is accessible via the :attr:`data` attribute of
1322 :class:`UserDict` instances. If *initialdata* is provided, :attr:`data` is
1323 initialized with its contents; note that a reference to *initialdata* will not
1324 be kept, allowing it to be used for other purposes.
1325
1326 In addition to supporting the methods and operations of mappings,
1327 :class:`UserDict` instances provide the following attribute:
1328
1329 .. attribute:: data
1330
1331 A real dictionary used to store the contents of the :class:`UserDict`
1332 class.
1333
1334
1335
1336 :class:`UserList` objects
1337 -------------------------
1338
1339 This class acts as a wrapper around list objects. It is a useful base class
1340 for your own list-like classes which can inherit from them and override
1341 existing methods or add new ones. In this way, one can add new behaviors to
1342 lists.
1343
1344 The need for this class has been partially supplanted by the ability to
1345 subclass directly from :class:`list`; however, this class can be easier
1346 to work with because the underlying list is accessible as an attribute.
1347
1348 .. class:: UserList([list])
1349
1350 Class that simulates a list. The instance's contents are kept in a regular
1351 list, which is accessible via the :attr:`data` attribute of :class:`UserList`
1352 instances. The instance's contents are initially set to a copy of *list*,
1353 defaulting to the empty list ``[]``. *list* can be any iterable, for
1354 example a real Python list or a :class:`UserList` object.
1355
1356 In addition to supporting the methods and operations of mutable sequences,
1357 :class:`UserList` instances provide the following attribute:
1358
1359 .. attribute:: data
1360
1361 A real :class:`list` object used to store the contents of the
1362 :class:`UserList` class.
1363
1364 **Subclassing requirements:** Subclasses of :class:`UserList` are expected to
1365 offer a constructor which can be called with either no arguments or one
1366 argument. List operations which return a new sequence attempt to create an
1367 instance of the actual implementation class. To do so, it assumes that the
1368 constructor can be called with a single parameter, which is a sequence object
1369 used as a data source.
1370
1371 If a derived class does not wish to comply with this requirement, all of the
1372 special methods supported by this class will need to be overridden; please
1373 consult the sources for information about the methods which need to be provided
1374 in that case.
1375
1376 :class:`UserString` objects
1377 ---------------------------
1378
1379 The class, :class:`UserString` acts as a wrapper around string objects.
1380 The need for this class has been partially supplanted by the ability to
1381 subclass directly from :class:`str`; however, this class can be easier
1382 to work with because the underlying string is accessible as an
1383 attribute.
1384
1385 .. class:: UserString(seq)
1386
1387 Class that simulates a string object. The instance's
1388 content is kept in a regular string object, which is accessible via the
1389 :attr:`data` attribute of :class:`UserString` instances. The instance's
1390 contents are initially set to a copy of *seq*. The *seq* argument can
1391 be any object which can be converted into a string using the built-in
1392 :func:`str` function.
1393
1394 In addition to supporting the methods and operations of strings,
1395 :class:`UserString` instances provide the following attribute:
1396
1397 .. attribute:: data
1398
1399 A real :class:`str` object used to store the contents of the
1400 :class:`UserString` class.
1401
1402 .. versionchanged:: 3.5
1403 New methods ``__getnewargs__``, ``__rmod__``, ``casefold``,
1404 ``format_map``, ``isprintable``, and ``maketrans``.