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