o occurred").with_traceback(tracebackobj)

The "from" clause is used for exception chaining: if given, the second
*expression* must be another exception class or instance. If the
second expression is an exception instance, it will be attached to the
raised exception as the "__cause__" attribute (which is writable). If
the expression is an exception class, the class will be instantiated
and the resulting exception instance will be attached to the raised
exception as the "__cause__" attribute. If the raised exception is not
handled, both exceptions will be printed:

   >>> try:
   ...     print(1 / 0)
   ... except Exception as exc:
   ...     raise RuntimeError("Something bad happened") from exc
   ...
   Traceback (most recent call last):
     File "<stdin>", line 2, in <module>
       print(1 / 0)
             ~~^~~
   ZeroDivisionError: division by zero

   The above exception was the direct cause of the following exception:

   Traceback (most recent call last):
     File "<stdin>", line 4, in <module>
       raise RuntimeError("Something bad happened") from exc
   RuntimeError: Something bad happened

A similar mechanism works implicitly if a new exception is raised when
an exception is already being handled.  An exception may be handled
when an "except" or "finally" clause, or a "with" statement, is used.
The previous exception is then attached as the new exception’s
"__context__" attribute:

   >>> try:
   ...     print(1 / 0)
   ... except:
   ...     raise RuntimeError("Something bad happened")
   ...
   Traceback (most recent call last):
     File "<stdin>", line 2, in <module>
       print(1 / 0)
             ~~^~~
   ZeroDivisionError: division by zero

   During handling of the above exception, another exception occurred:

   Traceback (most recent call last):
     File "<stdin>", line 4, in <module>
       raise RuntimeError("Something bad happened")
   RuntimeError: Something bad happened

Exception chaining can be explicitly suppressed by specifying "None"
in the "from" clause:

   >>> try:
   ...     print(1 / 0)
   ... except:
   ...     raise RuntimeError("Something bad happened") from None
   ...
   Traceback (most recent call last):
     File "<stdin>", line 4, in <module>
   RuntimeError: Something bad happened

Additional information on exceptions can be found in section
Exceptions, and information about handling exceptions is in section
The try statement.

Changed in version 3.3: "None" is now permitted as "Y" in "raise X
from Y".Added the "__suppress_context__" attribute to suppress
automatic display of the exception context.

Changed in version 3.11: If the traceback of the active exception is
modified in an "except" clause, a subsequent "raise" statement re-
raises the exception with the modified traceback. Previously, the
exception was re-raised with the traceback it had when it was caught.
''',
    'return': r'''The "return" statement
**********************

   return_stmt ::= "return" [expression_list]

"return" may only occur syntactically nested in a function definition,
not within a nested class definition.

If an expression list is present, it is evaluated, else "None" is
substituted.

"return" leaves the current function call with the expression list (or
"None") as return value.

When "return" passes control out of a "try" statement with a "finally"
clause, that "finally" clause is executed before really leaving the
function.

In a generator function, the "return" statement indicates that the
generator is done and will cause "StopIteration" to be raised. The
returned value (if any) is used as an argument to construct
"StopIteration" and becomes the "StopIteration.value" attribute.

In an asynchronous generator function, an empty "return" statement
indicates that the asynchronous generator is done and will cause
"StopAsyncIteration" to be raised.  A non-empty "return" statement is
a syntax error in an asynchronous generator function.
''',
    'sequence-types': r'''Emulating container types
*************************

The following methods can be defined to implement container objects.
None of them are provided by the "object" class itself. Containers
usually are *sequences* (such as "lists" or "tuples") or *mappings*
(like *dictionaries*), but can represent other containers as well.
The first set of methods is used either to emulate a sequence or to
emulate a mapping; the difference is that for a sequence, the
allowable keys should be the integers *k* for which "0 <= k < N" where
*N* is the length of the sequence, or "slice" objects, which define a
range of items.  It is also recommended that mappings provide the
methods "keys()", "values()", "items()", "get()", "clear()",
"setdefault()", "pop()", "popitem()", "copy()", and "update()"
behaving similar to those for Python’s standard "dictionary" objects.
The "collections.abc" module provides a "MutableMapping" *abstract
base class* to help create those methods from a base set of
"__getitem__()", "__setitem__()", "__delitem__()", and "keys()".
Mutable sequences should provide methods "append()", "count()",
"index()", "extend()", "insert()", "pop()", "remove()", "reverse()"
and "sort()", like Python standard "list" objects. Finally, sequence
types should implement addition (meaning concatenation) and
multiplication (meaning repetition) by defining the methods
"__add__()", "__radd__()", "__iadd__()", "__mul__()", "__rmul__()" and
"__imul__()" described below; they should not define other numerical
operators.  It is recommended that both mappings and sequences
implement the "__contains__()" method to allow efficient use of the
"in" operator; for mappings, "in" should search the mapping’s keys;
for sequences, it should search through the values.  It is further
recommended that both mappings and sequences implement the
"__iter__()" method to allow efficient iteration through the
container; for mappings, "__iter__()" should iterate through the
object’s keys; for sequences, it should iterate through the values.

object.__len__(self)

   Called to implement the built-in function "len()".  Should return
   the length of the object, an integer ">=" 0.  Also, an object that
   doesn’t define a "__bool__()" method and whose "__len__()" method
   returns zero is considered to be false in a Boolean context.

   **CPython implementation detail:** In CPython, the length is
   required to be at most "sys.maxsize". If the length is larger than
   "sys.maxsize" some features (such as "len()") may raise
   "OverflowError".  To prevent raising "OverflowError" by truth value
   testing, an object must define a "__bool__()" method.

object.__length_hint__(self)

   Called to implement "operator.length_hint()". Should return an
   estimated length for the object (which may be greater or less than
   the actual length). The length must be an integer ">=" 0. The
   return value may also be "NotImplemented", which is treated the
   same as if the "__length_hint__" method didn’t exist at all. This
   method is purely an optimization and is never required for
   correctness.

   Added in version 3.4.

Note:

  Slicing is done exclusively with the following three methods.  A
  call like

     a[1:2] = b

  is translated to

     a[slice(1, 2, None)] = b

  and so forth.  Missing slice items are always filled in with "None".

object.__getitem__(self, key)

   Called to implement evaluation of "self[key]". For *sequence*
   types, the accepted keys should be integers. Optionally, they may
   support "slice" objects as well.  Negative index support is also
   optional. If *key* is of an inappropriate type, "TypeError" may be
   raised; if *key* is a value outside the set of indexes for the
   sequence (after any special interpretation of negative values),
   "IndexError" should be raised. For *mapping* types, if *key* is
   missing (not in the container), "KeyError" should be raised.

   Note:

     "for" loops expect that an "IndexError" will be raised for
     illegal indexes to allow proper detection of the end of the
     sequence.

   Note:

     When subscripting a *class*, the special class method
     "__class_getitem__()" may be called instead of "__getitem__()".
     See __class_getitem__ versus __getitem__ for more details.

object.__setitem__(self, key, value)

   Called to implement assignment to "self[key]".  Same note as for
   "__getitem__()".  This should only be implemented for mappings if
   the objects support changes to the values for keys, or if new keys
   can be added, or for sequences if elements can be replaced.  The
   same exceptions should be raised for improper *key* values as for
   the "__getitem__()" method.

object.__delitem__(self, key)

   Called to implement deletion of "self[key]".  Same note as for
   "__getitem__()".  This should only be implemented for mappings if
   the objects support removal of keys, or for sequences if elements
   can be removed from the sequence.  The same exceptions should be
   raised for improper *key* values as for the "__getitem__()" method.

object.__missing__(self, key)

   Called by "dict"."__getitem__()" to implement "self[key]" for dict
   subclasses when key is not in the dictionary.

object.__iter__(self)

   This method is called when an *iterator* is required for a
   container. This method should return a new iterator object that can
   iterate over all the objects in the container.  For mappings, it
   should iterate over the keys of the container.

object.__reversed__(self)

   Called (if present) by the "reversed()" built-in to implement
   reverse iteration.  It should return a new iterator object that
   iterates over all the objects in the container in reverse order.

   If the "__reversed__()" method is not provided, the "reversed()"
   built-in will fall back to using the sequence protocol ("__len__()"
   and "__getitem__()").  Objects that support the sequence protocol
   should only provide "__reversed__()" if they can provide an
   implementation that is more efficient than the one provided by
   "reversed()".

The membership test operators ("in" and "not in") are normally
implemented as an iteration through a container. However, container
objects can supply the following special method with a more efficient
implementation, which also does not require the object be iterable.

object.__contains__(self, item)

   Called to implement membership test operators.  Should return true
   if *item* is in *self*, false otherwise.  For mapping objects, this
   should consider the keys of the mapping rather than the values or
   the key-item pairs.

   For objects that don’t define "__contains__()", the membership test
   first tries iteration via "__iter__()", then the old sequence
   iteration protocol via "__getitem__()", see this section in the
   language reference.
''',
    'shifting': r'''Shifting operations
*******************

The shifting operations have lower priority than the arithmetic
operations:

   shift_expr ::= a_expr | shift_expr ("<<" | ">>") a_expr

These operators accept integers as arguments.  They shift the first
argument to the left or right by the number of bits given by the
second argument.

The left shift operation can be customized using the special
"__lshift__()" and "__rlshift__()" methods. The right shift operation
can be customized using the special "__rshift__()" and "__rrshift__()"
methods.

A right shift by *n* bits is defined as floor division by "pow(2,n)".
A left shift by *n* bits is defined as multiplication with "pow(2,n)".
''',
    'slicings': r'''Slicings
********

A slicing selects a range of items in a sequence object (e.g., a
string, tuple or list).  Slicings may be used as expressions or as
targets in assignment or "del" statements.  The syntax for a slicing:

   slicing      ::= primary "[" slice_list "]"
   slice_list   ::= slice_item ("," slice_item)* [","]
   slice_item   ::= expression | proper_slice
   proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
   lower_bound  ::= expression
   upper_bound  ::= expression
   stride       ::= expression

There is ambiguity in the formal syntax here: anything that looks like
an expression list also looks like a slice list, so any subscription
can be interpreted as a slicing.  Rather than further complicating the
syntax, this is disambiguated by defining that in this case the
interpretation as a subscription takes priority over the
interpretation as a slicing (this is the case if the slice list
contains no proper slice).

The semantics for a slicing are as follows.  The primary is indexed
(using the same "__getitem__()" method as normal subscription) with a
key that is constructed from the slice list, as follows.  If the slice
list contains at least one comma, the key is a tuple containing the
conversion of the slice items; otherwise, the conversion of the lone
slice item is the key.  The conversion of a slice item that is an
expression is that expression.  The conversion of a proper slice is a
slice object (see section The standard type hierarchy) whose "start",
"stop" and "step" attributes are the values of the expressions given
as lower bound, upper bound and stride, respectively, substituting
"None" for missing expressions.
''',
    'specialattrs': r'''Special Attributes
******************

The implementation adds a few special read-only attributes to several
object types, where they are relevant.  Some of these are not reported
by the "dir()" built-in function.

definition.__name__

   The name of the class, function, method, descriptor, or generator
   instance.

definition.__qualname__

   The *qualified name* of the class, function, method, descriptor, or
   generator instance.

   Added in version 3.3.

definition.__module__

   The name of the module in which a class or function was defined.

definition.__doc__

   The documentation string of a class or function, or "None" if
   undefined.

definition.__type_params__

   The type parameters of generic classes, functions, and type
   aliases. For classes and functions that are not generic, this will
   be an empty tuple.

   Added in version 3.12.
''',
    'specialnames': r'''Special method names
********************

A class can implement certain operations that are invoked by special
syntax (such as arithmetic operations or subscripting and slicing) by
defining methods with special names. This is Python’s approach to
*operator overloading*, allowing classes to define their own behavior
with respect to language operators.  For instance, if a class defines
a method named "__getitem__()", and "x" is an instance of this class,
then "x[i]" is roughly equivalent to "type(x).__getitem__(x, i)".
Except where mentioned, attempts to execute an operation raise an
exception when no appropriate method is defined (typically
"AttributeError" or "TypeError").

Setting a special method to "None" indicates that the corresponding
operation is not available.  For example, if a class sets "__iter__()"
to "None", the class is not iterable, so calling "iter()" on its
instances will raise a "TypeError" (without falling back to
"__getitem__()"). [2]

When implementing a class that emulates any built-in type, it is
important that the emulation only be implemented to the degree that it
makes sense for the object being modelled.  For example, some
sequences may work well with retrieval of individual elements, but
extracting a slice may not make sense.  (One example of this is the
"NodeList" interface in the W3C’s Document Object Model.)


Basic customization
===================

object.__new__(cls[, ...])

   Called to create a new instance of class *cls*.  "__new__()" is a
   static method (special-cased so you need not declare it as such)
   that takes the class of which an instance was requested as its
   first argument.  The remaining arguments are those passed to the
   object constructor expression (the call to the class).  The return
   value of "__new__()" should be the new object instance (usually an
   instance of *cls*).

   Typical implementations create a new instance of the class by
   invoking the superclass’s "__new__()" method using
   "super().__new__(cls[, ...])" with appropriate arguments and then
   modifying the newly created instance as necessary before returning
   it.

   If "__new__()" is invoked during object construction and it returns
   an instance of *cls*, then the new instance’s "__init__()" method
   will be invoked like "__init__(self[, ...])", where *self* is the
   new instance and the remaining arguments are the same as were
   passed to the object constructor.

   If "__new__()" does not return an instance of *cls*, then the new
   instance’s "__init__()" method will not be invoked.

   "__new__()" is intended mainly to allow subclasses of immutable
   types (like int, str, or tuple) to customize instance creation.  It
   is also commonly overridden in custom metaclasses in order to
   customize class creation.

object.__init__(self[, ...])

   Called after the instance has been created (by "__new__()"), but
   before it is returned to the caller.  The arguments are those
   passed to the class constructor expression.  If a base class has an
   "__init__()" method, the derived class’s "__init__()" method, if
   any, must explicitly call it to ensure proper initialization of the
   base class part of the instance; for example:
   "super().__init__([args...])".

   Because "__new__()" and "__init__()" work together in constructing
   objects ("__new__()" to create it, and "__init__()" to customize
   it), no non-"None" value may be returned by "__init__()"; doing so
   will cause a "TypeError" to be raised at runtime.

object.__del__(self)

   Called when the instance is about to be destroyed.  This is also
   called a finalizer or (improperly) a destructor.  If a base class
   has a "__del__()" method, the derived class’s "__del__()" method,
   if any, must explicitly call it to ensure proper deletion of the
   base class part of the instance.

   It is possible (though not recommended!) for the "__del__()" method
   to postpone destruction of the instance by creating a new reference
   to it.  This is called object *resurrection*.  It is
   implementation-dependent whether "__del__()" is called a second
   time when a resurrected object is about to be destroyed; the
   current *CPython* implementation only calls it once.

   It is not guaranteed that "__del__()" methods are called for
   objects that still exist when the interpreter exits.
   "weakref.finalize" provides a straightforward way to register a
   cleanup function to be called when an object is garbage collected.

   Note:

     "del x" doesn’t directly call "x.__del__()" — the former
     decrements the reference count for "x" by one, and the latter is
     only called when "x"’s reference count reaches zero.

   **CPython implementation detail:** It is possible for a reference
   cycle to prevent the reference count of an object from going to
   zero.  In this case, the cycle will be later detected and deleted
   by the *cyclic garbage collector*.  A common cause of reference
   cycles is when an exception has been caught in a local variable.
   The frame’s locals then reference the exception, which references
   its own traceback, which references the locals of all frames caught
   in the traceback.

   See also: Documentation for the "gc" module.

   Warning:

     Due to the precarious circumstances under which "__del__()"
     methods are invoked, exceptions that occur during their execution
     are ignored, and a warning is printed to "sys.stderr" instead.
     In particular:

     * "__del__()" can be invoked when arbitrary code is being
       executed, including from any arbitrary thread.  If "__del__()"
       needs to take a lock or invoke any other blocking resource, it
       may deadlock as the resource may already be taken by the code
       that gets interrupted to execute "__del__()".

     * "__del__()" can be executed during interpreter shutdown.  As a
       consequence, the global variables it needs to access (including
       other modules) may already have been deleted or set to "None".
       Python guarantees that globals whose name begins with a single
       underscore are deleted from their module before other globals
       are deleted; if no other references to such globals exist, this
       may help in assuring that imported modules are still available
       at the time when the "__del__()" method is called.

object.__repr__(self)

   Called by the "repr()" built-in function to compute the “official”
   string representation of an object.  If at all possible, this
   should look like a valid Python expression that could be used to
   recreate an object with the same value (given an appropriate
   environment).  If this is not possible, a string of the form
   "<...some useful description...>" should be returned. The return
   value must be a string object. If a class defines "__repr__()" but
   not "__str__()", then "__repr__()" is also used when an “informal”
   string representation of instances of that class is required.

   This is typically used for debugging, so it is important that the
   representation is information-rich and unambiguous. A default
   implementation is provided by the "object" class itself.

object.__str__(self)

   Called by "str(object)", the default "__format__()" implementation,
   and the built-in function "print()", to compute the “informal” or
   nicely printable string representation of an object.  The return
   value must be a str object.

   This method differs from "object.__repr__()" in that there is no
   expectation that "__str__()" return a valid Python expression: a
   more convenient or concise representation can be used.

   The default implementation defined by the built-in type "object"
   calls "object.__repr__()".

object.__bytes__(self)

   Called by bytes to compute a byte-string representation of an
   object. This should return a "bytes" object. The "object" class
   itself does not provide this method.

object.__format__(self, format_spec)

   Called by the "format()" built-in function, and by extension,
   evaluation of formatted string literals and the "str.format()"
   method, to produce a “formatted” string representation of an
   object. The *format_spec* argument is a string that contains a
   description of the formatting options desired. The interpretation
   of the *format_spec* argument is up to the type implementing
   "__format__()", however most classes will either delegate
   formatting to one of the built-in types, or use a similar
   formatting option syntax.

   See Format Specification Mini-Language for a description of the
   standard formatting syntax.

   The return value must be a string object.

   The default implementation by the "object" class should be given an
   empty *format_spec* string. It delegates to "__str__()".

   Changed in version 3.4: The __format__ method of "object" itself
   raises a "TypeError" if passed any non-empty string.

   Changed in version 3.7: "object.__format__(x, '')" is now
   equivalent to "str(x)" rather than "format(str(x), '')".

object.__lt__(self, other)
object.__le__(self, other)
object.__eq__(self, other)
object.__ne__(self, other)
object.__gt__(self, other)
object.__ge__(self, other)

   These are the so-called “rich comparison” methods. The
   correspondence between operator symbols and method names is as
   follows: "x<y" calls "x.__lt__(y)", "x<=y" calls "x.__le__(y)",
   "x==y" calls "x.__eq__(y)", "x!=y" calls "x.__ne__(y)", "x>y" calls
   "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".

   A rich comparison method may return the singleton "NotImplemented"
   if it does not implement the operation for a given pair of
   arguments. By convention, "False" and "True" are returned for a
   successful comparison. However, these methods can return any value,
   so if the comparison operator is used in a Boolean context (e.g.,
   in the condition of an "if" statement), Python will call "bool()"
   on the value to determine if the result is true or false.

   By default, "object" implements "__eq__()" by using "is", returning
   "NotImplemented" in the case of a false comparison: "True if x is y
   else NotImplemented". For "__ne__()", by default it delegates to
   "__eq__()" and inverts the result unless it is "NotImplemented".
   There are no other implied relationships among the comparison
   operators or default implementations; for example, the truth of
   "(x<y or x==y)" does not imply "x<=y". To automatically generate
   ordering operations from a single root operation, see
   "functools.total_ordering()".

   By default, the "object" class provides implementations consistent
   with Value comparisons: equality compares according to object
   identity, and order comparisons raise "TypeError". Each default
   method may generate these results directly, but may also return
   "NotImplemented".

   See the paragraph on "__hash__()" for some important notes on
   creating *hashable* objects which support custom comparison
   operations and are usable as dictionary keys.

   There are no swapped-argument versions of these methods (to be used
   when the left argument does not support the operation but the right
   argument does); rather, "__lt__()" and "__gt__()" are each other’s
   reflection, "__le__()" and "__ge__()" are each other’s reflection,
   and "__eq__()" and "__ne__()" are their own reflection. If the
   operands are of different types, and the right operand’s type is a
   direct or indirect subclass of the left operand’s type, the
   reflected method of the right operand has priority, otherwise the
   left operand’s method has priority.  Virtual subclassing is not
   considered.

   When no appropriate method returns any value other than
   "NotImplemented", the "==" and "!=" operators will fall back to
   "is" and "is not", respectively.

object.__hash__(self)

   Called by built-in function "hash()" and for operations on members
   of hashed collections including "set", "frozenset", and "dict".
   The "__hash__()" method should return an integer. The only required
   property is that objects which compare equal have the same hash
   value; it is advised to mix together the hash values of the
   components of the object that also play a part in comparison of
   objects by packing them into a tuple and hashing the tuple.
   Example:

      def __hash__(self):
          return hash((self.name, self.nick, self.color))

   Note:

     "hash()" truncates the value returned from an object’s custom
     "__hash__()" method to the size of a "Py_ssize_t".  This is
     typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds.
     If an object’s   "__hash__()" must interoperate on builds of
     different bit sizes, be sure to check the width on all supported
     builds.  An easy way to do this is with "python -c "import sys;
     print(sys.hash_info.width)"".

   If a class does not define an "__eq__()" method it should not
   define a "__hash__()" operation either; if it defines "__eq__()"
   but not "__hash__()", its instances will not be usable as items in
   hashable collections.  If a class defines mutable objects and
   implements an "__eq__()" method, it should not implement
   "__hash__()", since the implementation of *hashable* collections
   requires that a key’s hash value is immutable (if the object’s hash
   value changes, it will be in the wrong hash bucket).

   User-defined classes have "__eq__()" and "__hash__()" methods by
   default (inherited from the "object" class); with them, all objects
   compare unequal (except with themselves) and "x.__hash__()" returns
   an appropriate value such that "x == y" implies both that "x is y"
   and "hash(x) == hash(y)".

   A class that overrides "__eq__()" and does not define "__hash__()"
   will have its "__hash__()" implicitly set to "None".  When the
   "__hash__()" method of a class is "None", instances of the class
   will raise an appropriate "TypeError" when a program attempts to
   retrieve their hash value, and will also be correctly identified as
   unhashable when checking "isinstance(obj,
   collections.abc.Hashable)".

   If a class that overrides "__eq__()" needs to retain the
   implementation of "__hash__()" from a parent class, the interpreter
   must be told this explicitly by setting "__hash__ =
   <ParentClass>.__hash__".

   If a class that does not override "__eq__()" wishes to suppress
   hash support, it should include "__hash__ = None" in the class
   definition. A class which defines its own "__hash__()" that
   explicitly raises a "TypeError" would be incorrectly identified as
   hashable by an "isinstance(obj, collections.abc.Hashable)" call.

   Note:

     By default, the "__hash__()" values of str and bytes objects are
     “salted” with an unpredictable random value.  Although they
     remain constant within an individual Python process, they are not
     predictable between repeated invocations of Python.This is
     intended to provide protection against a denial-of-service caused
     by carefully chosen inputs that exploit the worst case
     performance of a dict insertion, *O*(*n*^2) complexity.  See
     http://ocert.org/advisories/ocert-2011-003.html for
     details.Changing hash values affects the iteration order of sets.
     Python has never made guarantees about this ordering (and it
     typically varies between 32-bit and 64-bit builds).See also
     "PYTHONHASHSEED".

   Changed in version 3.3: Hash randomization is enabled by default.

object.__bool__(self)

   Called to implement truth value testing and the built-in operation
   "bool()"; should return "False" or "True".  When this method is not
   defined, "__len__()" is called, if it is defined, and the object is
   considered true if its result is nonzero.  If a class defines
   neither "__len__()" nor "__bool__()" (which is true of the "object"
   class itself), all its instances are considered true.


Customizing attribute access
============================

The following methods can be defined to customize the meaning of
attribute access (use of, assignment to, or deletion of "x.name") for
class instances.

object.__getattr__(self, name)

   Called when the default attribute access fails with an
   "AttributeError" (either "__getattribute__()" raises an
   "AttributeError" because *name* is not an instance attribute or an
   attribute in the class tree for "self"; or "__get__()" of a *name*
   property raises "AttributeError").  This method should either
   return the (computed) attribute value or raise an "AttributeError"
   exception. The "object" class itself does not provide this method.

   Note that if the attribute is found through the normal mechanism,
   "__getattr__()" is not called.  (This is an intentional asymmetry
   between "__getattr__()" and "__setattr__()".) This is done both for
   efficiency reasons and because otherwise "__getattr__()" would have
   no way to access other attributes of the instance.  Note that at
   least for instance variables, you can fake total control by not
   inserting any values in the instance attribute dictionary (but
   instead inserting them in another object).  See the
   "__getattribute__()" method below for a way to actually get total
   control over attribute access.

object.__getattribute__(self, name)

   Called unconditionally to implement attribute accesses for
   instances of the class. If the class also defines "__getattr__()",
   the latter will not be called unless "__getattribute__()" either
   calls it explicitly or raises an "AttributeError". This method
   should return the (computed) attribute value or raise an
   "AttributeError" exception. In order to avoid infinite recursion in
   this method, its implementation should always call the base class
   method with the same name to access any attributes it needs, for
   example, "object.__getattribute__(self, name)".

   Note:

     This method may still be bypassed when looking up special methods
     as the result of implicit invocation via language syntax or
     built-in functions. See Special method lookup.

   For certain sensitive attribute accesses, raises an auditing event
   "object.__getattr__" with arguments "obj" and "name".

object.__setattr__(self, name, value)

   Called when an attribute assignment is attempted.  This is called
   instead of the normal mechanism (i.e. store the value in the
   instance dictionary). *name* is the attribute name, *value* is the
   value to be assigned to it.

   If "__setattr__()" wants to assign to an instance attribute, it
   should call the base class method with the same name, for example,
   "object.__setattr__(self, name, value)".

   For certain sensitive attribute assignments, raises an auditing
   event "object.__setattr__" with arguments "obj", "name", "value".

object.__delattr__(self, name)

   Like "__setattr__()" but for attribute deletion instead of
   assignment.  This should only be implemented if "del obj.name" is
   meaningful for the object.

   For certain sensitive attribute deletions, raises an auditing event
   "object.__delattr__" with arguments "obj" and "name".

object.__dir__(self)

   Called when "dir()" is called on the object. An iterable must be
   returned. "dir()" converts the returned iterable to a list and
   sorts it.


Customizing module attribute access
-----------------------------------

Special names "__getattr__" and "__dir__" can be also used to
customize access to module attributes. The "__getattr__" function at
the module level should accept one argument which is the name of an
attribute and return the computed value or raise an "AttributeError".
If an attribute is not found on a module object through the normal
lookup, i.e. "object.__getattribute__()", then "__getattr__" is
searched in the module "__dict__" before raising an "AttributeError".
If found, it is called with the attribute name and the result is
returned.

The "__dir__" function should accept no arguments, and return an
iterable of strings that represents the names accessible on module. If
present, this function overrides the standard "dir()" search on a
module.

For a more fine grained customization of the module behavior (setting
attributes, properties, etc.), one can set the "__class__" attribute
of a module object to a subclass of "types.ModuleType". For example:

   import sys
   from types import ModuleType

   class VerboseModule(ModuleType):
       def __repr__(self):
           return f'Verbose {self.__name__}'

       def __setattr__(self, attr, value):
           print(f'Setting {attr}...')
           super().__setattr__(attr, value)

   sys.modules[__name__].__class__ = VerboseModule

Note:

  Defining module "__getattr__" and setting module "__class__" only
  affect lookups made using the attribute access syntax – directly
  accessing the module globals (whether by code within the module, or
  via a reference to the module’s globals dictionary) is unaffected.

Changed in version 3.5: "__class__" module attribute is now writable.

Added in version 3.7: "__getattr__" and "__dir__" module attributes.

See also:

  **PEP 562** - Module __getattr__ and __dir__
     Describes the "__getattr__" and "__dir__" functions on modules.


Implementing Descriptors
------------------------

The following methods only apply when an instance of the class
containing the method (a so-called *descriptor* class) appears in an
*owner* class (the descriptor must be in either the owner’s class
dictionary or in the class dictionary for one of its parents).  In the
examples below, “the attribute” refers to the attribute whose name is
the key of the property in the owner class’ "__dict__".  The "object"
class itself does not implement any of these protocols.

object.__get__(self, instance, owner=None)

   Called to get the attribute of the owner class (class attribute
   access) or of an instance of that class (instance attribute
   access). The optional *owner* argument is the owner class, while
   *instance* is the instance that the attribute was accessed through,
   or "None" when the attribute is accessed through the *owner*.

   This method should return the computed attribute value or raise an
   "AttributeError" exception.

   **PEP 252** specifies that "__get__()" is callable with one or two
   arguments.  Python’s own built-in descriptors support this
   specification; however, it is likely that some third-party tools
   have descriptors that require both arguments.  Python’s own
   "__getattribute__()" implementation always passes in both arguments
   whether they are required or not.

object.__set__(self, instance, value)

   Called to set the attribute on an instance *instance* of the owner
   class to a new value, *value*.

   Note, adding "__set__()" or "__delete__()" changes the kind of
   descriptor to a “data descriptor”.  See Invoking Descriptors for
   more details.

object.__delete__(self, instance)

   Called to delete the attribute on an instance *instance* of the
   owner class.

Instances of descriptors may also have the "__objclass__" attribute
present:

object.__objclass__

   The attribute "__objclass__" is interpreted by the "inspect" module
   as specifying the class where this object was defined (setting this
   appropriately can assist in runtime introspection of dynamic class
   attributes). For callables, it may indicate that an instance of the
   given type (or a subclass) is expected or required as the first
   positional argument (for example, CPython sets this attribute for
   unbound methods that are implemented in C).


Invoking Descriptors
--------------------

In general, a descriptor is an object attribute with “binding
behavior”, one whose attribute access has been overridden by methods
in the descriptor protocol:  "__get__()", "__set__()", and
"__delete__()". If any of those methods are defined for an object, it
is said to be a descriptor.

The default behavior for attribute access is to get, set, or delete
the attribute from an object’s dictionary. For instance, "a.x" has a
lookup chain starting with "a.__dict__['x']", then
"type(a).__dict__['x']", and continuing through the base classes of
"type(a)" excluding metaclasses.

However, if the looked-up value is an object defining one of the
descriptor methods, then Python may override the default behavior and
invoke the descriptor method instead.  Where this occurs in the
precedence chain depends on which descriptor methods were defined and
how they were called.

The starting point for descriptor invocation is a binding, "a.x". How
the arguments are assembled depends on "a":

Direct Call
   The simplest and least common call is when user code directly
   invokes a descriptor method:    "x.__get__(a)".

Instance Binding
   If binding to an object instance, "a.x" is transformed into the
   call: "type(a).__dict__['x'].__get__(a, type(a))".

Class Binding
   If binding to a class, "A.x" is transformed into the call:
   "A.__dict__['x'].__get__(None, A)".

Super Binding
   A dotted lookup such as "super(A, a).x" searches
   "a.__class__.__mro__" for a base class "B" following "A" and then
   returns "B.__dict__['x'].__get__(a, A)".  If not a descriptor, "x"
   is returned unchanged.

For instance bindings, the precedence of descriptor invocation depends
on which descriptor methods are defined.  A descriptor can define any
combination of "__get__()", "__set__()" and "__delete__()".  If it
does not define "__get__()", then accessing the attribute will return
the descriptor object itself unless there is a value in the object’s
instance dictionary.  If the descriptor defines "__set__()" and/or
"__delete__()", it is a data descriptor; if it defines neither, it is
a non-data descriptor.  Normally, data descriptors define both
"__get__()" and "__set__()", while non-data descriptors have just the
"__get__()" method.  Data descriptors with "__get__()" and "__set__()"
(and/or "__delete__()") defined always override a redefinition in an
instance dictionary.  In contrast, non-data descriptors can be
overridden by instances.

Python methods (including those decorated with "@staticmethod" and
"@classmethod") are implemented as non-data descriptors.  Accordingly,
instances can redefine and override methods.  This allows individual
instances to acquire behaviors that differ from other instances of the
same class.

The "property()" function is implemented as a data descriptor.
Accordingly, instances cannot override the behavior of a property.


__slots__
---------

*__slots__* allow us to explicitly declare data members (like
properties) and deny the creation of "__dict__" and *__weakref__*
(unless explicitly declared in *__slots__* or available in a parent.)

The space saved over using "__dict__" can be significant. Attribute
lookup speed can be significantly improved as well.

object.__slots__

   This class variable can be assigned a string, iterable, or sequence
   of strings with variable names used by instances.  *__slots__*
   reserves space for the declared variables and prevents the
   automatic creation of "__dict__" and *__weakref__* for each
   instance.

Notes on using *__slots__*:

* When inheriting from a class without *__slots__*, the "__dict__" and
  *__weakref__* attribute of the instances will always be accessible.

* Without a "__dict__" variable, instances cannot be assigned new
  variables not listed in the *__slots__* definition.  Attempts to
  assign to an unlisted variable name raises "AttributeError". If
  dynamic assignment of new variables is desired, then add
  "'__dict__'" to the sequence of strings in the *__slots__*
  declaration.

* Without a *__weakref__* variable for each instance, classes defining
  *__slots__* do not support "weak references" to its instances. If
  weak reference support is needed, then add "'__weakref__'" to the
  sequence of strings in the *__slots__* declaration.

* *__slots__* are implemented at the class level by creating
  descriptors for each variable name.  As a result, class attributes
  cannot be used to set default values for instance variables defined
  by *__slots__*; otherwise, the class attribute would overwrite the
  descriptor assignment.

* The action of a *__slots__* declaration is not limited to the class
  where it is defined.  *__slots__* declared in parents are available
  in child classes. However, instances of a child subclass will get a
  "__dict__" and *__weakref__* unless the subclass also defines
  *__slots__* (which should only contain names of any *additional*
  slots).

* If a class defines a slot also defined in a base class, the instance
  variable defined by the base class slot is inaccessible (except by
  retrieving its descriptor directly from the base class). This
  renders the meaning of the program undefined.  In the future, a
  check may be added to prevent this.

* "TypeError" will be raised if nonempty *__slots__* are defined for a
  class derived from a ""variable-length" built-in type" such as
  "int", "bytes", and "tuple".

* Any non-string *iterable* may be assigned to *__slots__*.

* If a "dictionary" is used to assign *__slots__*, the dictionary keys
  will be used as the slot names. The values of the dictionary can be
  used to provide per-attribute docstrings that will be recognised by
  "inspect.getdoc()" and displayed in the output of "help()".

* "__class__" assignment works only if both classes have the same
  *__slots__*.

* Multiple inheritance with multiple slotted parent classes can be
  used, but only one parent is allowed to have attributes created by
  slots (the other bases must have empty slot layouts) - violations
  raise "TypeError".

* If an *iterator* is used for *__slots__* then a *descriptor* is
  created for each of the iterator’s values. However, the *__slots__*
  attribute will be an empty iterator.


Customizing class creation
==========================

Whenever a class inherits from another class, "__init_subclass__()" is
called on the parent class. This way, it is possible to write classes
which change the behavior of subclasses. This is closely related to
class decorators, but where class decorators only affect the specific
class they’re applied to, "__init_subclass__" solely applies to future
subclasses of the class defining the method.

classmethod object.__init_subclass__(cls)

   This method is called whenever the containing class is subclassed.
   *cls* is then the new subclass. If defined as a normal instance
   method, this method is implicitly converted to a class method.

   Keyword arguments which are given to a new class are passed to the
   parent class’s "__init_subclass__". For compatibility with other
   classes using "__init_subclass__", one should take out the needed
   keyword arguments and pass the others over to the base class, as
   in:

      class Philosopher:
          def __init_subclass__(cls, /, default_name, **kwargs):
              super().__init_subclass__(**kwargs)
              cls.default_name = default_name

      class AustralianPhilosopher(Philosopher, default_name="Bruce"):
          pass

   The default implementation "object.__init_subclass__" does nothing,
   but raises an error if it is called with any arguments.

   Note:

     The metaclass hint "metaclass" is consumed by the rest of the
     type machinery, and is never passed to "__init_subclass__"
     implementations. The actual metaclass (rather than the explicit
     hint) can be accessed as "type(cls)".

   Added in version 3.6.

When a class is created, "type.__new__()" scans the class variables
and makes callbacks to those with a "__set_name__()" hook.

object.__set_name__(self, owner, name)

   Automatically called at the time the owning class *owner* is
   created. The object has been assigned to *name* in that class:

      class A:
          x = C()  # Automatically calls: x.__set_name__(A, 'x')

   If the class variable is assigned after the class is created,
   "__set_name__()" will not be called automatically. If needed,
   "__set_name__()" can be called directly:

      class A:
         pass

      c = C()
      A.x = c                  # The hook is not called
      c.__set_name__(A, 'x')   # Manually invoke the hook

   See Creating the class object for more details.

   Added in version 3.6.


Metaclasses
-----------

By default, classes are constructed using "type()". The class body is
executed in a new namespace and the class name is bound locally to the
result of "type(name, bases, namespace)".

The class creation process can be customized by passing the
"metaclass" keyword argument in the class definition line, or by
inheriting from an existing class that included such an argument. In
the following example, both "MyClass" and "MySubclass" are instances
of "Meta":

   class Meta(type):
       pass

   class MyClass(metaclass=Meta):
       pass

   class MySubclass(MyClass):
       pass

Any other keyword arguments that are specified in the class definition
are passed through to all metaclass operations described below.

When a class definition is executed, the following steps occur:

* MRO entries are resolved;

* the appropriate metaclass is determined;

* the class namespace is prepared;

* the class body is executed;

* the class object is created.


Resolving MRO entries
---------------------

object.__mro_entries__(self, bases)

   If a base that appears in a class definition is not an instance of
   "type", then an "__mro_entries__()" method is searched on the base.
   If an "__mro_entries__()" method is found, the base is substituted
   with the result of a call to "__mro_entries__()" when creating the
   class. The method is called with the original bases tuple passed to
   the *bases* parameter, and must return a tuple of classes that will
   be used instead of the base. The returned tuple may be empty: in
   these cases, the original base is ignored.

See also:

  "types.resolve_bases()"
     Dynamically resolve bases that are not instances of "type".

  "types.get_original_bases()"
     Retrieve a class’s “original bases” prior to modifications by
     "__mro_entries__()".

  **PEP 560**
     Core support for typing module and generic types.


Determining the appropriate metaclass
-------------------------------------

The appropriate metaclass for a class definition is determined as
follows:

* if no bases and no explicit metaclass are given, then "type()" is
  used;

* if an explicit metaclass is given and it is *not* an instance of
  "type()", then it is used directly as the metaclass;

* if an instance of "type()" is given as the explicit metaclass, or
  bases are defined, then the most derived metaclass is used.

The most derived metaclass is selected from the explicitly specified
metaclass (if any) and the metaclasses (i.e. "type(cls)") of all
specified base classes. The most derived metaclass is one which is a
subtype of *all* of these candidate metaclasses. If none of the
candidate metaclasses meets that criterion, then the class definition
will fail with "TypeError".


Preparing the class namespace
-----------------------------

Once the appropriate metaclass has been identified, then the class
namespace is prepared. If the metaclass has a "__prepare__" attribute,
it is called as "namespace = metaclass.__prepare__(name, bases,
**kwds)" (where the additional keyword arguments, if any, come from
the class definition). The "__prepare__" method should be implemented
as a "classmethod". The namespace returned by "__prepare__" is passed
in to "__new__", but when the final class object is created the
namespace is copied into a new "dict".

If the metaclass has no "__prepare__" attribute, then the class
namespace is initialised as an empty ordered mapping.

See also:

  **PEP 3115** - Metaclasses in Python 3000
     Introduced the "__prepare__" namespace hook


Executing the class body
------------------------

The class body is executed (approximately) as "exec(body, globals(),
namespace)". The key difference from a normal call to "exec()" is that
lexical scoping allows the class body (including any methods) to
reference names from the current and outer scopes when the class
definition occurs inside a function.

However, even when the class definition occurs inside the function,
methods defined inside the class still cannot see names defined at the
class scope. Class variables must be accessed through the first
parameter of instance or class methods, or through the implicit
lexically scoped "__class__" reference described in the next section.


Creating the class object
-------------------------

Once the class namespace has been populated by executing the class
body, the class object is created by calling "metaclass(name, bases,
namespace, **kwds)" (the additional keywords passed here are the same
as those passed to "__prepare__").

This class object is the one that will be referenced by the zero-
argument form of "super()". "__class__" is an implicit closure
reference created by the compiler if any methods in a class body refer
to either "__class__" or "super". This allows the zero argument form
of "super()" to correctly identify the class being defined based on
lexical scoping, while the class or instance that was used to make the
current call is identified based on the first argument passed to the
method.

**CPython implementation detail:** In CPython 3.6 and later, the
"__class__" cell is passed to the metaclass as a "__classcell__" entry
in the class namespace. If present, this must be propagated up to the
"type.__new__" call in order for the class to be initialised
correctly. Failing to do so will result in a "RuntimeError" in Python
3.8.

When using the default metaclass "type", or any metaclass that
ultimately calls "type.__new__", the following additional
customization steps are invoked after creating the class object:

1. The "type.__new__" method collects all of the attributes in the
   class namespace that define a "__set_name__()" method;

2. Those "__set_name__" methods are called with the class being
   defined and the assigned name of that particular attribute;

3. The "__init_subclass__()" hook is called on the immediate parent of
   the new class in its method resolution order.

After the class object is created, it is passed to the class
decorators included in the class definition (if any) and the resulting
object is bound in the local namespace as the defined class.

When a new class is created by "type.__new__", the object provided as
the namespace parameter is copied to a new ordered mapping and the
original object is discarded. The new copy is wrapped in a read-only
proxy, which becomes the "__dict__" attribute of the class object.

See also:

  **PEP 3135** - New super
     Describes the implicit "__class__" closure reference


Uses for metaclasses
--------------------

The potential uses for metaclasses are boundless. Some ideas that have
been explored include enum, logging, interface checking, automatic
delegation, automatic property creation, proxies, frameworks, and
automatic resource locking/synchronization.


Customizing instance and subclass checks
========================================

The following methods are used to override the default behavior of the
"isinstance()" and "issubclass()" built-in functions.

In particular, the metaclass "abc.ABCMeta" implements these methods in
order to allow the addition of Abstract Base Classes (ABCs) as
“virtual base classes” to any class or type (including built-in
types), including other ABCs.

type.__instancecheck__(self, instance)

   Return true if *instance* should be considered a (direct or
   indirect) instance of *class*. If defined, called to implement
   "isinstance(instance, class)".

type.__subclasscheck__(self, subclass)

   Return true if *subclass* should be considered a (direct or
   indirect) subclass of *class*.  If defined, called to implement
   "issubclass(subclass, class)".

Note that these methods are looked up on the type (metaclass) of a
class.  They cannot be defined as class methods in the actual class.
This is consistent with the lookup of special methods that are called
on instances, only in this case the instance is itself a class.

See also:

  **PEP 3119** - Introducing Abstract Base Classes
     Includes the specification for customizing "isinstance()" and
     "issubclass()" behavior through "__instancecheck__()" and
     "__subclasscheck__()", with motivation for this functionality in
     the context of adding Abstract Base Classes (see the "abc"
     module) to the language.


Emulating generic types
=======================

When using *type annotations*, it is often useful to *parameterize* a
*generic type* using Python’s square-brackets notation. For example,
the annotation "list[int]" might be used to signify a "list" in which
all the elements are of type "int".

See also:

  **PEP 484** - Type Hints
     Introducing Python’s framework for type annotations

  Generic Alias Types
     Documentation for objects representing parameterized generic
     classes

  Generics, user-defined generics and "typing.Generic"
     Documentation on how to implement generic classes that can be
     parameterized at runtime and understood by static type-checkers.

A class can *generally* only be parameterized if it defines the
special class method "__class_getitem__()".

classmethod object.__class_getitem__(cls, key)

   Return an object representing the specialization of a generic class
   by type arguments found in *key*.

   When defined on a class, "__class_getitem__()" is automatically a
   class method. As such, there is no need for it to be decorated with
   "@classmethod" when it is defined.


The purpose of *__class_getitem__*
----------------------------------

The purpose of "__class_getitem__()" is to allow runtime
parameterization of standard-library generic classes in order to more
easily apply *type hints* to these classes.

To implement custom generic classes that can be parameterized at
runtime and understood by static type-checkers, users should either
inherit from a standard library class that already implements
"__class_getitem__()", or inherit from "typing.Generic", which has its
own implementation of "__class_getitem__()".

Custom implementations of "__class_getitem__()" on classes defined
outside of the standard library may not be understood by third-party
type-checkers such as mypy. Using "__class_getitem__()" on any class
for purposes other than type hinting is discouraged.


*__class_getitem__* versus *__getitem__*
----------------------------------------

Usually, the subscription of an object using square brackets will call
the "__getitem__()" instance method defined on the object’s class.
However, if the object being subscribed is itself a class, the class
method "__class_getitem__()" may be called instead.
"__class_getitem__()" should return a GenericAlias object if it is
properly defined.

Presented with the *expression* "obj[x]", the Python interpreter
follows something like the following process to decide whether
"__getitem__()" or "__class_getitem__()" should be called:

   from inspect import isclass

   def subscribe(obj, x):
       """Return the result of the expression 'obj[x]'"""

       class_of_obj = type(obj)

       # If the class of obj defines __getitem__,
       # call class_of_obj.__getitem__(obj, x)
       if hasattr(class_of_obj, '__getitem__'):
           return class_of_obj.__getitem__(obj, x)

       # Else, if obj is a class and defines __class_getitem__,
       # call obj.__class_getitem__(x)
       elif isclass(obj) and hasattr(obj, '__class_getitem__'):
           return obj.__class_getitem__(x)

       # Else, raise an exception
       else:
           raise TypeError(
               f"'{class_of_obj.__name__}' object is not subscriptable"
           )

In Python, all classes are themselves instances of other classes. The
class of a class is known as that class’s *metaclass*, and most
classes have the "type" class as their metaclass. "type" does not
define "__getitem__()", meaning that expressions such as "list[int]",
"dict[str, float]" and "tuple[str, bytes]" all result in
"__class_getitem__()" being called:

   >>> # list has class "type" as its metaclass, like most classes:
   >>> type(list)
   <class 'type'>
   >>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes)
   True
   >>> # "list[int]" calls "list.__class_getitem__(int)"
   >>> list[int]
   list[int]
   >>> # list.__class_getitem__ returns a GenericAlias object:
   >>> type(list[int])
   <class 'types.GenericAlias'>

However, if a class has a custom metaclass that defines
"__getitem__()", subscribing the class may result in different
behaviour. An example of this can be found in the "enum" module:

   >>> from enum import Enum
   >>> class Menu(Enum):
   ...     """A breakfast menu"""
   ...     SPAM = 'spam'
   ...     BACON = 'bacon'
   ...
   >>> # Enum classes have a custom metaclass:
   >>> type(Menu)
   <class 'enum.EnumMeta'>
   >>> # EnumMeta defines __getitem__,
   >>> # so __class_getitem__ is not called,
   >>> # and the result is not a GenericAlias object:
   >>> Menu['SPAM']
   <Menu.SPAM: 'spam'>
   >>> type(Menu['SPAM'])
   <enum 'Menu'>

See also:

  **PEP 560** - Core Support for typing module and generic types
     Introducing "__class_getitem__()", and outlining when a
     subscription results in "__class_getitem__()" being called
     instead of "__getitem__()"


Emulating callable objects
==========================

object.__call__(self[, args...])

   Called when the instance is “called” as a function; if this method
   is defined, "x(arg1, arg2, ...)" roughly translates to
   "type(x).__call__(x, arg1, ...)". The "object" class itself does
   not provide this method.


Emulating container types
=========================

The following methods can be defined to implement container objects.
None of them are provided by the "object" class itself. Containers
usually are *sequences* (such as "lists" or "tuples") or *mappings*
(like *dictionaries*), but can represent other containers as well.
The first set of methods is used either to emulate a sequence or to
emulate a mapping; the difference is that for a sequence, the
allowable keys should be the integers *k* for which "0 <= k < N" where
*N* is the length of the sequence, or "slice" objects, which define a
range of items.  It is also recommended that mappings provide the
methods "keys()", "values()", "items()", "get()", "clear()",
"setdefault()", "pop()", "popitem()", "copy()", and "update()"
behaving similar to those for Python’s standard "dictionary" objects.
The "collections.abc" module provides a "MutableMapping" *abstract
base class* to help create those methods from a base set of
"__getitem__()", "__setitem__()", "__delitem__()", and "keys()".
Mutable sequences should provide methods "append()", "count()",
"index()", "extend()", "insert()", "pop()", "remove()", "reverse()"
and "sort()", like Python standard "list" objects. Finally, sequence
types should implement addition (meaning concatenation) and
multiplication (meaning repetition) by defining the methods
"__add__()", "__radd__()", "__iadd__()", "__mul__()", "__rmul__()" and
"__imul__()" described below; they should not define other numerical
operators.  It is recommended that both mappings and sequences
implement the "__contains__()" method to allow efficient use of the
"in" operator; for mappings, "in" should search the mapping’s keys;
for sequences, it should search through the values.  It is further
recommended that both mappings and sequences implement the
"__iter__()" method to allow efficient iteration through the
container; for mappings, "__iter__()" should iterate through the
object’s keys; for sequences, it should iterate through the values.

object.__len__(self)

   Called to implement the built-in function "len()".  Should return
   the length of the object, an integer ">=" 0.  Also, an object that
   doesn’t define a "__bool__()" method and whose "__len__()" method
   returns zero is considered to be false in a Boolean context.

   **CPython implementation detail:** In CPython, the length is
   required to be at most "sys.maxsize". If the length is larger than
   "sys.maxsize" some features (such as "len()") may raise
   "OverflowError".  To prevent raising "OverflowError" by truth value
   testing, an object must define a "__bool__()" method.

object.__length_hint__(self)

   Called to implement "operator.length_hint()". Should return an
   estimated length for the object (which may be greater or less than
   the actual length). The length must be an integer ">=" 0. The
   return value may also be "NotImplemented", which is treated the
   same as if the "__length_hint__" method didn’t exist at all. This
   method is purely an optimization and is never required for
   correctness.

   Added in version 3.4.

Note:

  Slicing is done exclusively with the following three methods.  A
  call like

     a[1:2] = b

  is translated to

     a[slice(1, 2, None)] = b

  and so forth.  Missing slice items are always filled in with "None".

object.__getitem__(self, key)

   Called to implement evaluation of "self[key]". For *sequence*
   types, the accepted keys should be integers. Optionally, they may
   support "slice" objects as well.  Negative index support is also
   optional. If *key* is of an inappropriate type, "TypeError" may be
   raised; if *key* is a value outside the set of indexes for the
   sequence (after any special interpretation of negative values),
   "IndexError" should be raised. For *mapping* types, if *key* is
   missing (not in the container), "KeyError" should be raised.

   Note:

     "for" loops expect that an "IndexError" will be raised for
     illegal indexes to allow proper detection of the end of the
     sequence.

   Note:

     When subscripting a *class*, the special class method
     "__class_getitem__()" may be called instead of "__getitem__()".
     See __class_getitem__ versus __getitem__ for more details.

object.__setitem__(self, key, value)

   Called to implement assignment to "self[key]".  Same note as for
   "__getitem__()".  This should only be implemented for mappings if
   the objects support changes to the values for keys, or if new keys
   can be added, or for sequences if elements can be replaced.  The
   same exceptions should be raised for improper *key* values as for
   the "__getitem__()" method.

object.__delitem__(self, key)

   Called to implement deletion of "self[key]".  Same note as for
   "__getitem__()".  This should only be implemented for mappings if
   the objects support removal of keys, or for sequences if elements
   can be removed from the sequence.  The same exceptions should be
   raised for improper *key* values as for the "__getitem__()" method.

object.__missing__(self, key)

   Called by "dict"."__getitem__()" to implement "self[key]" for dict
   subclasses when key is not in the dictionary.

object.__iter__(self)

   This method is called when an *iterator* is required for a
   container. This method should return a new iterator object that can
   iterate over all the objects in the container.  For mappings, it
   should iterate over the keys of the container.

object.__reversed__(self)

   Called (if present) by the "reversed()" built-in to implement
   reverse iteration.  It should return a new iterator object that
   iterates over all the objects in the container in reverse order.

   If the "__reversed__()" method is not provided, the "reversed()"
   built-in will fall back to using the sequence protocol ("__len__()"
   and "__getitem__()").  Objects that support the sequence protocol
   should only provide "__reversed__()" if they can provide an
   implementation that is more efficient than the one provided by
   "reversed()".

The membership test operators ("in" and "not in") are normally
implemented as an iteration through a container. However, container
objects can supply the following special method with a more efficient
implementation, which also does not require the object be iterable.

object.__contains__(self, item)

   Called to implement membership test operators.  Should return true
   if *item* is in *self*, false otherwise.  For mapping objects, this
   should consider the keys of the mapping rather than the values or
   the key-item pairs.

   For objects that don’t define "__contains__()", the membership test
   first tries iteration via "__iter__()", then the old sequence
   iteration protocol via "__getitem__()", see this section in the
   language reference.


Emulating numeric types
=======================

The following methods can be defined to emulate numeric objects.
Methods corresponding to operations that are not supported by the
particular kind of number implemented (e.g., bitwise operations for
non-integral numbers) should be left undefined.

object.__add__(self, other)
object.__sub__(self, other)
object.__mul__(self, other)
object.__matmul__(self, other)
object.__truediv__(self, other)
object.__floordiv__(self, other)
object.__mod__(self, other)
object.__divmod__(self, other)
object.__pow__(self, other[, modulo])
object.__lshift__(self, other)
object.__rshift__(self, other)
object.__and__(self, other)
object.__xor__(self, other)
object.__or__(self, other)

   These methods are called to implement the binary arithmetic
   operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
   "pow()", "**", "<<", ">>", "&", "^", "|").  For instance, to
   evaluate the expression "x + y", where *x* is an instance of a
   class that has an "__add__()" method, "type(x).__add__(x, y)" is
   called.  The "__divmod__()" method should be the equivalent to
   using "__floordiv__()" and "__mod__()"; it should not be related to
   "__truediv__()".  Note that "__pow__()" should be defined to accept
   an optional third argument if the ternary version of the built-in
   "pow()" function is to be supported.

   If one of those methods does not support the operation with the
   supplied arguments, it should return "NotImplemented".

object.__radd__(self, other)
object.__rsub__(self, other)
object.__rmul__(self, other)
object.__rmatmul__(self, other)
object.__rtruediv__(self, other)
object.__rfloordiv__(self, other)
object.__rmod__(self, other)
object.__rdivmod__(self, other)
object.__rpow__(self, other[, modulo])
object.__rlshift__(self, other)
object.__rrshift__(self, other)
object.__rand__(self, other)
object.__rxor__(self, other)
object.__ror__(self, other)

   These methods are called to implement the binary arithmetic
   operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
   "pow()", "**", "<<", ">>", "&", "^", "|") with reflected (swapped)
   operands.  These functions are only called if the left operand does
   not support the corresponding operation [3] and the operands are of
   different types. [4] For instance, to evaluate the expression "x -
   y", where *y* is an instance of a class that has an "__rsub__()"
   method, "type(y).__rsub__(y, x)" is called if "type(x).__sub__(x,
   y)" returns "NotImplemented".

   Note that ternary "pow()" will not try calling "__rpow__()" (the
   coercion rules would become too complicated).

   Note:

     If the right operand’s type is a subclass of the left operand’s
     type and that subclass provides a different implementation of the
     reflected method for the operation, this method will be called
     before the left operand’s non-reflected method. This behavior
     allows subclasses to override their ancestors’ operations.

object.__iadd__(self, other)
object.__isub__(self, other)
object.__imul__(self, other)
object.__imatmul__(self, other)
object.__itruediv__(self, other)
object.__ifloordiv__(self, other)
object.__imod__(self, other)
object.__ipow__(self, other[, modulo])
object.__ilshift__(self, other)
object.__irshift__(self, other)
object.__iand__(self, other)
object.__ixor__(self, other)
object.__ior__(self, other)

   These methods are called to implement the augmented arithmetic
   assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", "**=",
   "<<=", ">>=", "&=", "^=", "|=").  These methods should attempt to
   do the operation in-place (modifying *self*) and return the result
   (which could be, but does not have to be, *self*).  If a specific
   method is not defined, or if that method returns "NotImplemented",
   the augmented assignment falls back to the normal methods.  For
   instance, if *x* is an instance of a class with an "__iadd__()"
   method, "x += y" is equivalent to "x = x.__iadd__(y)" . If
   "__iadd__()" does not exist, or if "x.__iadd__(y)" returns
   "NotImplemented", "x.__add__(y)" and "y.__radd__(x)" are
   considered, as with the evaluation of "x + y". In certain
   situations, augmented assignment can result in unexpected errors
   (see Why does a_tuple[i] += [‘item’] raise an exception when the
   addition works?), but this behavior is in fact part of the data
   model.

object.__neg__(self)
object.__pos__(self)
object.__abs__(self)
object.__invert__(self)

   Called to implement the unary arithmetic operations ("-", "+",
   "abs()" and "~").

object.__complex__(self)
object.__int__(self)
object.__float__(self)

   Called to implement the built-in functions "complex()", "int()" and
   "float()".  Should return a value of the appropriate type.

object.__index__(self)

   Called to implement "operator.index()", and whenever Python needs
   to losslessly convert the numeric object to an integer object (such
   as in slicing, or in the built-in "bin()", "hex()" and "oct()"
   functions). Presence of this method indicates that the numeric
   object is an integer type.  Must return an integer.

   If "__int__()", "__float__()" and "__complex__()" are not defined
   then corresponding built-in functions "int()", "float()" and
   "complex()" fall back to "__index__()".

object.__round__(self[, ndigits])
object.__trunc__(self)
object.__floor__(self)
object.__ceil__(self)

   Called to implement the built-in function "round()" and "math"
   functions "trunc()", "floor()" and "ceil()". Unless *ndigits* is
   passed to "__round__()" all these methods should return the value
   of the object truncated to an "Integral" (typically an "int").

   The built-in function "int()" falls back to "__trunc__()" if
   neither "__int__()" nor "__index__()" is defined.

   Changed in version 3.11: The delegation of "int()" to "__trunc__()"
   is deprecated.


With Statement Context Managers
===============================

A *context manager* is an object that defines the runtime context to
be established when executing a "with" statement. The context manager
handles the entry into, and the exit from, the desired runtime context
for the execution of the block of code.  Context managers are normally
invoked using the "with" statement (described in section The with
statement), but can also be used by directly invoking their methods.

Typical uses of context managers include saving and restoring various
kinds of global state, locking and unlocking resources, closing opened
files, etc.

For more information on context managers, see Context Manager Types.
The "object" class itself does not provide the context manager
methods.

object.__enter__(self)

   Enter the runtime context related to this object. The "with"
   statement will bind this method’s return value to the target(s)
   specified in the "as" clause of the statement, if any.

object.__exit__(self, exc_type, exc_value, traceback)

   Exit the runtime context related to this object. The parameters
   describe the exception that caused the context to be exited. If the
   context was exited without an exception, all three arguments will
   be "None".

   If an exception is supplied, and the method wishes to suppress the
   exception (i.e., prevent it from being propagated), it should
   return a true value. Otherwise, the exception will be processed
   normally upon exit from this method.

   Note that "__exit__()" methods should not reraise the passed-in
   exception; this is the caller’s responsibility.

See also:

  **PEP 343** - The “with” statement
     The specification, background, and examples for the Python "with"
     statement.


Customizing positional arguments in class pattern matching
==========================================================

When using a class name in a pattern, positional arguments in the
pattern are not allowed by default, i.e. "case MyClass(x, y)" is
typically invalid without special support in "MyClass". To be able to
use that kind of pattern, the class needs to define a *__match_args__*
attribute.

object.__match_args__

   This class variable can be assigned a tuple of strings. When this
   class is used in a class pattern with positional arguments, each
   positional argument will be converted into a keyword argument,
   using the corresponding value in *__match_args__* as the keyword.
   The absence of this attribute is equivalent to setting it to "()".

For example, if "MyClass.__match_args__" is "("left", "center",
"right")" that means that "case MyClass(x, y)" is equivalent to "case
MyClass(left=x, center=y)". Note that the number of arguments in the
pattern must be smaller than or equal to the number of elements in
*__match_args__*; if it is larger, the pattern match attempt will
raise a "TypeError".

Added in version 3.10.

See also:

  **PEP 634** - Structural Pattern Matching
     The specification for the Python "match" statement.


Emulating buffer types
======================

The buffer protocol provides a way for Python objects to expose
efficient access to a low-level memory array. This protocol is
implemented by builtin types such as "bytes" and "memoryview", and
third-party libraries may define additional buffer types.

While buffer types are usually implemented in C, it is also possible
to implement the protocol in Python.

object.__buffer__(self, flags)

   Called when a buffer is requested from *self* (for example, by the
   "memoryview" constructor). The *flags* argument is an integer
   representing the kind of buffer requested, affecting for example
   whether the returned buffer is read-only or writable.
   "inspect.BufferFlags" provides a convenient way to interpret the
   flags. The method must return a "memoryview" object.

object.__release_buffer__(self, buffer)

   Called when a buffer is no longer needed. The *buffer* argument is
   a "memoryview" object that was previously returned by
   "__buffer__()". The method must release any resources associated
   with the buffer. This method should return "None". Buffer objects
   that do not need to perform any cleanup are not required to
   implement this method.

Added in version 3.12.

See also:

  **PEP 688** - Making the buffer protocol accessible in Python
     Introduces the Python "__buffer__" and "__release_buffer__"
     methods.

  "collections.abc.Buffer"
     ABC for buffer types.


Special method lookup
=====================

For custom classes, implicit invocations of special methods are only
guaranteed to work correctly if defined on an object’s type, not in
the object’s instance dictionary.  That behaviour is the reason why
the following code raises an exception:

   >>> class C:
   ...     pass
   ...
   >>> c = C()
   >>> c.__len__ = lambda: 5
   >>> len(c)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: object of type 'C' has no len()

The rationale behind this behaviour lies with a number of special
methods such as "__hash__()" and "__repr__()" that are implemented by
all objects, including type objects. If the implicit lookup of these
methods used the conventional lookup process, they would fail when
invoked on the type object itself:

   >>> 1 .__hash__() == hash(1)
   True
   >>> int.__hash__() == hash(int)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: descriptor '__hash__' of 'int' object needs an argument

Incorrectly attempting to invoke an unbound method of a class in this
way is sometimes referred to as ‘metaclass confusion’, and is avoided
by bypassing the instance when looking up special methods:

   >>> type(1).__hash__(1) == hash(1)
   True
   >>> type(int).__hash__(int) == hash(int)
   True

In addition to bypassing any instance attributes in the interest of
correctness, implicit special method lookup generally also bypasses
the "__getattribute__()" method even of the object’s metaclass:

   >>> class Meta(type):
   ...     def __getattribute__(*args):
   ...         print("Metaclass getattribute invoked")
   ...         return type.__getattribute__(*args)
   ...
   >>> class C(object, metaclass=Meta):
   ...     def __len__(self):
   ...         return 10
   ...     def __getattribute__(*args):
   ...         print("Class getattribute invoked")
   ...         return object.__getattribute__(*args)
   ...
   >>> c = C()
   >>> c.__len__()                 # Explicit lookup via instance
   Class getattribute invoked
   10
   >>> type(c).__len__(c)          # Explicit lookup via type
   Metaclass getattribute invoked
   10
   >>> len(c)                      # Implicit lookup
   10

Bypassing the "__getattribute__()" machinery in this fashion provides
significant scope for speed optimisations within the interpreter, at
the cost of some flexibility in the handling of special methods (the
special method *must* be set on the class object itself in order to be
consistently invoked by the interpreter).
''',
    'string-methods': r'''String Methods
**************

Strings implement all of the common sequence operations, along with
the additional methods described below.

Strings also support two styles of string formatting, one providing a
large degree of flexibility and customization (see "str.format()",
Format String Syntax and Custom String Formatting) and the other based
on C "printf" style formatting that handles a narrower range of types
and is slightly harder to use correctly, but is often faster for the
cases it can handle (printf-style String Formatting).

The Text Processing Services section of the standard library covers a
number of other modules that provide various text related utilities
(including regular expression support in the "re" module).

str.capitalize()

   Return a copy of the string with its first character capitalized
   and the rest lowercased.

   Changed in version 3.8: The first character is now put into
   titlecase rather than uppercase. This means that characters like
   digraphs will only have their first letter capitalized, instead of
   the full character.

str.casefold()

   Return a casefolded copy of the string. Casefolded strings may be
   used for caseless matching.

   Casefolding is similar to lowercasing but more aggressive because
   it is intended to remove all case distinctions in a string. For
   example, the German lowercase letter "'ß'" is equivalent to ""ss"".
   Since it is already lowercase, "lower()" would do nothing to "'ß'";
   "casefold()" converts it to ""ss"".

   The casefolding algorithm is described in section 3.13 ‘Default
   Case Folding’ of the Unicode Standard.

   Added in version 3.3.

str.center(width[, fillchar])

   Return centered in a string of length *width*. Padding is done
   using the specified *fillchar* (default is an ASCII space). The
   original string is returned if *width* is less than or equal to
   "len(s)".

str.count(sub[, start[, end]])

   Return the number of non-overlapping occurrences of substring *sub*
   in the range [*start*, *end*].  Optional arguments *start* and
   *end* are interpreted as in slice notation.

   If *sub* is empty, returns the number of empty strings between
   characters which is the length of the string plus one.

str.encode(encoding='utf-8', errors='strict')

   Return the string encoded to "bytes".

   *encoding* defaults to "'utf-8'"; see Standard Encodings for
   possible values.

   *errors* controls how encoding errors are handled. If "'strict'"
   (the default), a "UnicodeError" exception is raised. Other possible
   values are "'ignore'", "'replace'", "'xmlcharrefreplace'",
   "'backslashreplace'" and any other name registered via
   "codecs.register_error()". See Error Handlers for details.

   For performance reasons, the value of *errors* is not checked for
   validity unless an encoding error actually occurs, Python
   Development Mode is enabled or a debug build is used.

   Changed in version 3.1: Added support for keyword arguments.

   Changed in version 3.9: The value of the *errors* argument is now
   checked in Python Development Mode and in debug mode.

str.endswith(suffix[, start[, end]])

   Return "True" if the string ends with the specified *suffix*,
   otherwise return "False".  *suffix* can also be a tuple of suffixes
   to look for.  With optional *start*, test beginning at that
   position.  With optional *end*, stop comparing at that position.

str.expandtabs(tabsize=8)

   Return a copy of the string where all tab characters are replaced
   by one or more spaces, depending on the current column and the
   given tab size.  Tab positions occur every *tabsize* characters
   (default is 8, giving tab positions at columns 0, 8, 16 and so on).
   To expand the string, the current column is set to zero and the
   string is examined character by character.  If the character is a
   tab ("\t"), one or more space characters are inserted in the result
   until the current column is equal to the next tab position. (The
   tab character itself is not copied.)  If the character is a newline
   ("\n") or return ("\r"), it is copied and the current column is
   reset to zero.  Any other character is copied unchanged and the
   current column is incremented by one regardless of how the
   character is represented when printed.

   >>> '01\t012\t0123\t01234'.expandtabs()
   '01      012     0123    01234'
   >>> '01\t012\t0123\t01234'.expandtabs(4)
   '01  012 0123    01234'

str.find(sub[, start[, end]])

   Return the lowest index in the string where substring *sub* is
   found within the slice "s[start:end]".  Optional arguments *start*
   and *end* are interpreted as in slice notation.  Return "-1" if
   *sub* is not found.

   Note:

     The "find()" method should be used only if you need to know the
     position of *sub*.  To check if *sub* is a substring or not, use
     the "in" operator:

        >>> 'Py' in 'Python'
        True

str.format(*args, **kwargs)

   Perform a string formatting operation.  The string on which this
   method is called can contain literal text or replacement fields
   delimited by braces "{}".  Each replacement field contains either
   the numeric index of a positional argument, or the name of a
   keyword argument.  Returns a copy of the string where each
   replacement field is replaced with the string value of the
   corresponding argument.

   >>> "The sum of 1 + 2 is {0}".format(1+2)
   'The sum of 1 + 2 is 3'

   See Format String Syntax for a description of the various
   formatting options that can be specified in format strings.

   Note:

     When formatting a number ("int", "float", "complex",
     "decimal.Decimal" and subclasses) with the "n" type (ex:
     "'{:n}'.format(1234)"), the function temporarily sets the
     "LC_CTYPE" locale to the "LC_NUMERIC" locale to decode
     "decimal_point" and "thousands_sep" fields of "localeconv()" if
     they are non-ASCII or longer than 1 byte, and the "LC_NUMERIC"
     locale is different than the "LC_CTYPE" locale.  This temporary
     change affects other threads.

   Changed in version 3.7: When formatting a number with the "n" type,
   the function sets temporarily the "LC_CTYPE" locale to the
   "LC_NUMERIC" locale in some cases.

str.format_map(mapping)

   Similar to "str.format(**mapping)", except that "mapping" is used
   directly and not copied to a "dict".  This is useful if for example
   "mapping" is a dict subclass:

   >>> class Default(dict):
   ...     def __missing__(self, key):
   ...         return key
   ...
   >>> '{name} was born in {country}'.format_map(Default(name='Guido'))
   'Guido was born in country'

   Added in version 3.2.

str.index(sub[, start[, end]])

   Like "find()", but raise "ValueError" when the substring is not
   found.

str.isalnum()

   Return "True" if all characters in the string are alphanumeric and
   there is at least one character, "False" otherwise.  A character
   "c" is alphanumeric if one of the following returns "True":
   "c.isalpha()", "c.isdecimal()", "c.isdigit()", or "c.isnumeric()".

str.isalpha()

   Return "True" if all characters in the string are alphabetic and
   there is at least one character, "False" otherwise.  Alphabetic
   characters are those characters defined in the Unicode character
   database as “Letter”, i.e., those with general category property
   being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”.  Note that this is
   different from the Alphabetic property defined in the section 4.10
   ‘Letters, Alphabetic, and Ideographic’ of the Unicode Standard.

str.isascii()

   Return "True" if the string is empty or all characters in the
   string are ASCII, "False" otherwise. ASCII characters have code
   points in the range U+0000-U+007F.

   Added in version 3.7.

str.isdecimal()

   Return "True" if all characters in the string are decimal
   characters and there is at least one character, "False" otherwise.
   Decimal characters are those that can be used to form numbers in
   base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.  Formally a decimal
   character is a character in the Unicode General Category “Nd”.

str.isdigit()

   Return "True" if all characters in the string are digits and there
   is at least one character, "False" otherwise.  Digits include
   decimal characters and digits that need special handling, such as
   the compatibility superscript digits. This covers digits which
   cannot be used to form numbers in base 10, like the Kharosthi
   numbers.  Formally, a digit is a character that has the property
   value Numeric_Type=Digit or Numeric_Type=Decimal.

str.isidentifier()

   Return "True" if the string is a valid identifier according to the
   language definition, section Identifiers and keywords.

   "keyword.iskeyword()" can be used to test whether string "s" is a
   reserved identifier, such as "def" and "class".

   Example:

      >>> from keyword import iskeyword

      >>> 'hello'.isidentifier(), iskeyword('hello')
      (True, False)
      >>> 'def'.isidentifier(), iskeyword('def')
      (True, True)

str.islower()

   Return "True" if all cased characters [4] in the string are
   lowercase and there is at least one cased character, "False"
   otherwise.

str.isnumeric()

   Return "True" if all characters in the string are numeric
   characters, and there is at least one character, "False" otherwise.
   Numeric characters include digit characters, and all characters
   that have the Unicode numeric value property, e.g. U+2155, VULGAR
   FRACTION ONE FIFTH.  Formally, numeric characters are those with
   the property value Numeric_Type=Digit, Numeric_Type=Decimal or
   Numeric_Type=Numeric.

str.isprintable()

   Return true if all characters in the string are printable, false if
   it contains at least one non-printable character.

   Here “printable” means the character is suitable for "repr()" to
   use in its output; “non-printable” means that "repr()" on built-in
   types will hex-escape the character.  It has no bearing on the
   handling of strings written to "sys.stdout" or "sys.stderr".

   The printable characters are those which in the Unicode character
   database (see "unicodedata") have a general category in group
   Letter, Mark, Number, Punctuation, or Symbol (L, M, N, P, or S);
   plus the ASCII space 0x20. Nonprintable characters are those in
   group Separator or Other (Z or C), except the ASCII space.

str.isspace()

   Return "True" if there are only whitespace characters in the string
   and there is at least one character, "False" otherwise.

   A character is *whitespace* if in the Unicode character database
   (see "unicodedata"), either its general category is "Zs"
   (“Separator, space”), or its bidirectional class is one of "WS",
   "B", or "S".

str.istitle()

   Return "True" if the string is a titlecased string and there is at
   least one character, for example uppercase characters may only
   follow uncased characters and lowercase characters only cased ones.
   Return "False" otherwise.

str.isupper()

   Return "True" if all cased characters [4] in the string are
   uppercase and there is at least one cased character, "False"
   otherwise.

   >>> 'BANANA'.isupper()
   True
   >>> 'banana'.isupper()
   False
   >>> 'baNana'.isupper()
   False
   >>> ' '.isupper()
   False

str.join(iterable)

   Return a string which is the concatenation of the strings in
   *iterable*. A "TypeError" will be raised if there are any non-
   string values in *iterable*, including "bytes" objects.  The
   separator between elements is the string providing this method.

str.ljust(width[, fillchar])

   Return the string left justified in a string of length *width*.
   Padding is done using the specified *fillchar* (default is an ASCII
   space). The original string is returned if *width* is less than or
   equal to "len(s)".

str.lower()

   Return a copy of the string with all the cased characters [4]
   converted to lowercase.

   The lowercasing algorithm used is described in section 3.13
   ‘Default Case Folding’ of the Unicode Standard.

str.lstrip([chars])

   Return a copy of the string with leading characters removed.  The
   *chars* argument is a string specifying the set of characters to be
   removed.  If omitted or "None", the *chars* argument defaults to
   removing whitespace.  The *chars* argument is not a prefix; rather,
   all combinations of its values are stripped:

      >>> '   spacious   '.lstrip()
      'spacious   '
      >>> 'www.example.com'.lstrip('cmowz.')
      'example.com'

   See "str.removeprefix()" for a method that will remove a single
   prefix string rather than all of a set of characters.  For example:

      >>> 'Arthur: three!'.lstrip('Arthur: ')
      'ee!'
      >>> 'Arthur: three!'.removeprefix('Arthur: ')
      'three!'

static str.maketrans(x[, y[, z]])

   This static method returns a translation table usable for
   "str.translate()".

   If there is only one argument, it must be a dictionary mapping
   Unicode ordinals (integers) or characters (strings of length 1) to
   Unicode ordinals, strings (of arbitrary lengths) or "None".
   Character keys will then be converted to ordinals.

   If there are two arguments, they must be strings of equal length,
   and in the resulting dictionary, each character in x will be mapped
   to the character at the same position in y.  If there is a third
   argument, it must be a string, whose characters will be mapped to
   "None" in the result.

str.partition(sep)

   Split the string at the first occurrence of *sep*, and return a
   3-tuple containing the part before the separator, the separator
   itself, and the part after the separator.  If the separator is not
   found, return a 3-tuple containing the string itself, followed by
   two empty strings.

str.removeprefix(prefix, /)

   If the string starts with the *prefix* string, return
   "string[len(prefix):]". Otherwise, return a copy of the original
   string:

      >>> 'TestHook'.removeprefix('Test')
      'Hook'
      >>> 'BaseTestCase'.removeprefix('Test')
      'BaseTestCase'

   Added in version 3.9.

str.removesuffix(suffix, /)

   If the string ends with the *suffix* string and that *suffix* is
   not empty, return "string[:-len(suffix)]". Otherwise, return a copy
   of the original string:

      >>> 'MiscTests'.removesuffix('Tests')
      'Misc'
      >>> 'TmpDirMixin'.removesuffix('Tests')
      'TmpDirMixin'

   Added in version 3.9.

str.replace(old, new[, count])

   Return a copy of the string with all occurrences of substring *old*
   replaced by *new*.  If the optional argument *count* is given, only
   the first *count* occurrences are replaced.

str.rfind(sub[, start[, end]])

   Return the highest index in the string where substring *sub* is
   found, such that *sub* is contained within "s[start:end]".
   Optional arguments *start* and *end* are interpreted as in slice
   notation.  Return "-1" on failure.

str.rindex(sub[, start[, end]])

   Like "rfind()" but raises "ValueError" when the substring *sub* is
   not found.

str.rjust(width[, fillchar])

   Return the string right justified in a string of length *width*.
   Padding is done using the specified *fillchar* (default is an ASCII
   space). The original string is returned if *width* is less than or
   equal to "len(s)".

str.rpartition(sep)

   Split the string at the last occurrence of *sep*, and return a
   3-tuple containing the part before the separator, the separator
   itself, and the part after the separator.  If the separator is not
   found, return a 3-tuple containing two empty strings, followed by
   the string itself.

str.rsplit(sep=None, maxsplit=-1)

   Return a list of the words in the string, using *sep* as the
   delimiter string. If *maxsplit* is given, at most *maxsplit* splits
   are done, the *rightmost* ones.  If *sep* is not specified or
   "None", any whitespace string is a separator.  Except for splitting
   from the right, "rsplit()" behaves like "split()" which is
   described in detail below.

str.rstrip([chars])

   Return a copy of the string with trailing characters removed.  The
   *chars* argument is a string specifying the set of characters to be
   removed.  If omitted or "None", the *chars* argument defaults to
   removing whitespace.  The *chars* argument is not a suffix; rather,
   all combinations of its values are stripped:

      >>> '   spacious   '.rstrip()
      '   spacious'
      >>> 'mississippi'.rstrip('ipz')
      'mississ'

   See "str.removesuffix()" for a method that will remove a single
   suffix string rather than all of a set of characters.  For example:

      >>> 'Monty Python'.rstrip(' Python')
      'M'
      >>> 'Monty Python'.removesuffix(' Python')
      'Monty'

str.split(sep=None, maxsplit=-1)

   Return a list of the words in the string, using *sep* as the
   delimiter string.  If *maxsplit* is given, at most *maxsplit*
   splits are done (thus, the list will have at most "maxsplit+1"
   elements).  If *maxsplit* is not specified or "-1", then there is
   no limit on the number of splits (all possible splits are made).

   If *sep* is given, consecutive delimiters are not grouped together
   and are deemed to delimit empty strings (for example,
   "'1,,2'.split(',')" returns "['1', '', '2']").  The *sep* argument
   may consist of multiple characters as a single delimiter (to split
   with multiple delimiters, use "re.split()"). Splitting an empty
   string with a specified separator returns "['']".

   For example:

      >>> '1,2,3'.split(',')
      ['1', '2', '3']
      >>> '1,2,3'.split(',', maxsplit=1)
      ['1', '2,3']
      >>> '1,2,,3,'.split(',')
      ['1', '2', '', '3', '']
      >>> '1<>2<>3<4'.split('<>')
      ['1', '2', '3<4']

   If *sep* is not specified or is "None", a different splitting
   algorithm is applied: runs of consecutive whitespace are regarded
   as a single separator, and the result will contain no empty strings
   at the start or end if the string has leading or trailing
   whitespace.  Consequently, splitting an empty string or a string
   consisting of just whitespace with a "None" separator returns "[]".

   For example:

      >>> '1 2 3'.split()
      ['1', '2', '3']
      >>> '1 2 3'.split(maxsplit=1)
      ['1', '2 3']
      >>> '   1   2   3   '.split()
      ['1', '2', '3']

str.splitlines(keepends=False)

   Return a list of the lines in the string, breaking at line
   boundaries.  Line breaks are not included in the resulting list
   unless *keepends* is given and true.

   This method splits on the following line boundaries.  In
   particular, the boundaries are a superset of *universal newlines*.

   +-------------------------+-------------------------------+
   | Representation          | Description                   |
   |=========================|===============================|
   | "\n"                    | Line Feed                     |
   +-------------------------+-------------------------------+
   | "\r"                    | Carriage Return               |
   +-------------------------+-------------------------------+
   | "\r\n"                  | Carriage Return + Line Feed   |
   +-------------------------+-------------------------------+
   | "\v" or "\x0b"          | Line Tabulation               |
   +-------------------------+-------------------------------+
   | "\f" or "\x0c"          | Form Feed                     |
   +-------------------------+-------------------------------+
   | "\x1c"                  | File Separator                |
   +-------------------------+-------------------------------+
   | "\x1d"                  | Group Separator               |
   +-------------------------+-------------------------------+
   | "\x1e"                  | Record Separator              |
   +-------------------------+-------------------------------+
   | "\x85"                  | Next Line (C1 Control Code)   |
   +-------------------------+-------------------------------+
   | "\u2028"                | Line Separator                |
   +-------------------------+-------------------------------+
   | "\u2029"                | Paragraph Separator           |
   +-------------------------+-------------------------------+

   Changed in version 3.2: "\v" and "\f" added to list of line
   boundaries.

   For example:

      >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
      ['ab c', '', 'de fg', 'kl']
      >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
      ['ab c\n', '\n', 'de fg\r', 'kl\r\n']

   Unlike "split()" when a delimiter string *sep* is given, this
   method returns an empty list for the empty string, and a terminal
   line break does not result in an extra line:

      >>> "".splitlines()
      []
      >>> "One line\n".splitlines()
      ['One line']

   For comparison, "split('\n')" gives:

      >>> ''.split('\n')
      ['']
      >>> 'Two lines\n'.split('\n')
      ['Two lines', '']

str.startswith(prefix[, start[, end]])

   Return "True" if string starts with the *prefix*, otherwise return
   "False". *prefix* can also be a tuple of prefixes to look for.
   With optional *start*, test string beginning at that position.
   With optional *end*, stop comparing string at that position.

str.strip([chars])

   Return a copy of the string with the leading and trailing
   characters removed. The *chars* argument is a string specifying the
   set of characters to be removed. If omitted or "None", the *chars*
   argument defaults to removing whitespace. The *chars* argument is
   not a prefix or suffix; rather, all combinations of its values are
   stripped:

      >>> '   spacious   '.strip()
      'spacious'
      >>> 'www.example.com'.strip('cmowz.')
      'example'

   The outermost leading and trailing *chars* argument values are
   stripped from the string. Characters are removed from the leading
   end until reaching a string character that is not contained in the
   set of characters in *chars*. A similar action takes place on the
   trailing end. For example:

      >>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
      >>> comment_string.strip('.#! ')
      'Section 3.2.1 Issue #32'

str.swapcase()

   Return a copy of the string with uppercase characters converted to
   lowercase and vice versa. Note that it is not necessarily true that
   "s.swapcase().swapcase() == s".

str.title()

   Return a titlecased version of the string where words start with an
   uppercase character and the remaining characters are lowercase.

   For example:

      >>> 'Hello world'.title()
      'Hello World'

   The algorithm uses a simple language-independent definition of a
   word as groups of consecutive letters.  The definition works in
   many contexts but it means that apostrophes in contractions and
   possessives form word boundaries, which may not be the desired
   result:

      >>> "they're bill's friends from the UK".title()
      "They'Re Bill'S Friends From The Uk"

   The "string.capwords()" function does not have this problem, as it
   splits words on spaces only.

   Alternatively, a workaround for apostrophes can be constructed
   using regular expressions:

      >>> import re
      >>> def titlecase(s):
      ...     return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
      ...                   lambda mo: mo.group(0).capitalize(),
      ...                   s)
      ...
      >>> titlecase("they're bill's friends.")
      "They're Bill's Friends."

str.translate(table)

   Return a copy of the string in which each character has been mapped
   through the given translation table.  The table must be an object
   that implements indexing via "__getitem__()", typically a *mapping*
   or *sequence*.  When indexed by a Unicode ordinal (an integer), the
   table object can do any of the following: return a Unicode ordinal
   or a string, to map the character to one or more other characters;
   return "None", to delete the character from the return string; or
   raise a "LookupError" exception, to map the character to itself.

   You can use "str.maketrans()" to create a translation map from
   character-to-character mappings in different formats.

   See also the "codecs" module for a more flexible approach to custom
   character mappings.

str.upper()

   Return a copy of the string with all the cased characters [4]
   converted to uppercase.  Note that "s.upper().isupper()" might be
   "False" if "s" contains uncased characters or if the Unicode
   category of the resulting character(s) is not “Lu” (Letter,
   uppercase), but e.g. “Lt” (Letter, titlecase).

   The uppercasing algorithm used is described in section 3.13
   ‘Default Case Folding’ of the Unicode Standard.

str.zfill(width)

   Return a copy of the string left filled with ASCII "'0'" digits to
   make a string of length *width*. A leading sign prefix
   ("'+'"/"'-'") is handled by inserting the padding *after* the sign
   character rather than before. The original string is returned if
   *width* is less than or equal to "len(s)".

   For example:

      >>> "42".zfill(5)
      '00042'
      >>> "-42".zfill(5)
      '-0042'
''',
    'strings': '''String and Bytes literals
*************************

String literals are described by the following lexical definitions:

   stringliteral   ::= [stringprefix](shortstring | longstring)
   stringprefix    ::= "r" | "u" | "R" | "U" | "f" | "F"
                       | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"
   shortstring     ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'
   longstring      ::= "\'\'\'" longstringitem* "\'\'\'" | '"""' longstringitem* '"""'
   shortstringitem ::= shortstringchar | stringescapeseq
   longstringitem  ::= longstringchar | stringescapeseq
   shortstringchar ::= <any source character except "\\" or newline or the quote>
   longstringchar  ::= <any source character except "\\">
   stringescapeseq ::= "\\" <any source character>

   bytesliteral   ::= bytesprefix(shortbytes | longbytes)
   bytesprefix    ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
   shortbytes     ::= "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
   longbytes      ::= "\'\'\'" longbytesitem* "\'\'\'" | '"""' longbytesitem* '"""'
   shortbytesitem ::= shortbyteschar | bytesescapeseq
   longbytesitem  ::= longbyteschar | bytesescapeseq
   shortbyteschar ::= <any ASCII character except "\\" or newline or the quote>
   longbyteschar  ::= <any ASCII character except "\\">
   bytesescapeseq ::= "\\" <any ASCII character>

One syntactic restriction not indicated by these productions is that
whitespace is not allowed between the "stringprefix" or "bytesprefix"
and the rest of the literal. The source character set is defined by
the encoding declaration; it is UTF-8 if no encoding declaration is
given in the source file; see section Encoding declarations.

In plain English: Both types of literals can be enclosed in matching
single quotes ("'") or double quotes (""").  They can also be enclosed
in matching groups of three single or double quotes (these are
generally referred to as *triple-quoted strings*). The backslash ("\\")
character is used to give special meaning to otherwise ordinary
characters like "n", which means ‘newline’ when escaped ("\\n"). It can
also be used to escape characters that otherwise have a special
meaning, such as newline, backslash itself, or the quote character.
See escape sequences below for examples.

Bytes literals are always prefixed with "'b'" or "'B'"; they produce
an instance of the "bytes" type instead of the "str" type.  They may
only contain ASCII characters; bytes with a numeric value of 128 or
greater must be expressed with escapes.

Both string and bytes literals may optionally be prefixed with a
letter "'r'" or "'R'"; such constructs are called *raw string
literals* and *raw bytes literals* respectively and treat backslashes
as literal characters.  As a result, in raw string literals, "'\\U'"
and "'\\u'" escapes are not treated specially.

Added in version 3.3: The "'rb'" prefix of raw bytes literals has been
added as a synonym of "'br'".Support for the unicode legacy literal
("u'value'") was reintroduced to simplify the maintenance of dual
Python 2.x and 3.x codebases. See **PEP 414** for more information.

A string literal with "'f'" or "'F'" in its prefix is a *formatted
string literal*; see f-strings.  The "'f'" may be combined with "'r'",
but not with "'b'" or "'u'", therefore raw formatted strings are
possible, but formatted bytes literals are not.

In triple-quoted literals, unescaped newlines and quotes are allowed
(and are retained), except that three unescaped quotes in a row
terminate the literal.  (A “quote” is the character used to open the
literal, i.e. either "'" or """.)


Escape sequences
================

Unless an "'r'" or "'R'" prefix is present, escape sequences in string
and bytes literals are interpreted according to rules similar to those
used by Standard C.  The recognized escape sequences are:

+---------------------------+-----------------------------------+---------+
| Escape Sequence           | Meaning                           | Notes   |
|===========================|===================================|=========|
| "\\"<newline>              | Backslash and newline ignored     | (1)     |
+---------------------------+-----------------------------------+---------+
| "\\\\"                      | Backslash ("\\")                   |         |
+---------------------------+-----------------------------------+---------+
| "\\'"                      | Single quote ("'")                |         |
+---------------------------+-----------------------------------+---------+
| "\\""                      | Double quote (""")                |         |
+---------------------------+-----------------------------------+---------+
| "\\a"                      | ASCII Bell (BEL)                  |         |
+---------------------------+-----------------------------------+---------+
| "\\b"                      | ASCII Backspace (BS)              |         |
+---------------------------+-----------------------------------+---------+
| "\\f"                      | ASCII Formfeed (FF)               |         |
+---------------------------+-----------------------------------+---------+
| "\\n"                      | ASCII Linefeed (LF)               |         |
+---------------------------+-----------------------------------+---------+
| "\\r"                      | ASCII Carriage Return (CR)        |         |
+---------------------------+-----------------------------------+---------+
| "\\t"                      | ASCII Horizontal Tab (TAB)        |         |
+---------------------------+-----------------------------------+---------+
| "\\v"                      | ASCII Vertical Tab (VT)           |         |
+---------------------------+-----------------------------------+---------+
| "\\*ooo*"                  | Character with octal value *ooo*  | (2,4)   |
+---------------------------+-----------------------------------+---------+
| "\\x*hh*"                  | Character with hex value *hh*     | (3,4)   |
+---------------------------+-----------------------------------+---------+

Escape sequences only recognized in string literals are:

+---------------------------+-----------------------------------+---------+
| Escape Sequence           | Meaning                           | Notes   |
|===========================|===================================|=========|
| "\\N{*name*}"              | Character named *name* in the     | (5)     |
|                           | Unicode database                  |         |
+---------------------------+-----------------------------------+---------+
| "\\u*xxxx*"                | Character with 16-bit hex value   | (6)     |
|                           | *xxxx*                            |         |
+---------------------------+-----------------------------------+---------+
| "\\U*xxxxxxxx*"            | Character with 32-bit hex value   | (7)     |
|                           | *xxxxxxxx*                        |         |
+---------------------------+-----------------------------------+---------+

Notes:

1. A backslash can be added at the end of a line to ignore the
   newline:

      >>> 'This string will not include \\
      ... backslashes or newline characters.'
      'This string will not include backslashes or newline characters.'

   The same result can be achieved using triple-quoted strings, or
   parentheses and string literal concatenation.

2. As in Standard C, up to three octal digits are accepted.

   Changed in version 3.11: Octal escapes with value larger than
   "0o377" produce a "DeprecationWarning".

   Changed in version 3.12: Octal escapes with value larger than
   "0o377" produce a "SyntaxWarning". In a future Python version they
   will be eventually a "SyntaxError".

3. Unlike in Standard C, exactly two hex digits are required.

4. In a bytes literal, hexadecimal and octal escapes denote the byte
   with the given value. In a string literal, these escapes denote a
   Unicode character with the given value.

5. Changed in version 3.3: Support for name aliases [1] has been
   added.

6. Exactly four hex digits are required.

7. Any Unicode character can be encoded this way.  Exactly eight hex
   digits are required.

Unlike Standard C, all unrecognized escape sequences are left in the
string unchanged, i.e., *the backslash is left in the result*.  (This
behavior is useful when debugging: if an escape sequence is mistyped,
the resulting output is more easily recognized as broken.)  It is also
important to note that the escape sequences only recognized in string
literals fall into the category of unrecognized escapes for bytes
literals.

Changed in version 3.6: Unrecognized escape sequences produce a
"DeprecationWarning".

Changed in version 3.12: Unrecognized escape sequences produce a
"SyntaxWarning". In a future Python version they will be eventually a
"SyntaxError".

Even in a raw literal, quotes can be escaped with a backslash, but the
backslash remains in the result; for example, "r"\\""" is a valid
string literal consisting of two characters: a backslash and a double
quote; "r"\\"" is not a valid string literal (even a raw string cannot
end in an odd number of backslashes).  Specifically, *a raw literal
cannot end in a single backslash* (since the backslash would escape
the following quote character).  Note also that a single backslash
followed by a newline is interpreted as those two characters as part
of the literal, *not* as a line continuation.
''',
    'subscriptions': r'''Subscriptions
*************

The subscription of an instance of a container class will generally
select an element from the container. The subscription of a *generic
class* will generally return a GenericAlias object.

   subscription ::= primary "[" flexible_expression_list "]"

When an object is subscripted, the interpreter will evaluate the
primary and the expression list.

The primary must evaluate to an object that supports subscription. An
object may support subscription through defining one or both of
"__getitem__()" and "__class_getitem__()". When the primary is
subscripted, the evaluated result of the expression list will be
passed to one of these methods. For more details on when
"__class_getitem__" is called instead of "__getitem__", see
__class_getitem__ versus __getitem__.

If the expression list contains at least one comma, or if any of the
expressions are starred, the expression list will evaluate to a
"tuple" containing the items of the expression list. Otherwise, the
expression list will evaluate to the value of the list’s sole member.

Changed in version 3.11: Expressions in an expression list may be
starred. See **PEP 646**.

For built-in objects, there are two types of objects that support
subscription via "__getitem__()":

1. Mappings. If the primary is a *mapping*, the expression list must
   evaluate to an object whose value is one of the keys of the
   mapping, and the subscription selects the value in the mapping that
   corresponds to that key. An example of a builtin mapping class is
   the "dict" class.

2. Sequences. If the primary is a *sequence*, the expression list must
   evaluate to an "int" or a "slice" (as discussed in the following
   section). Examples of builtin sequence classes include the "str",
   "list" and "tuple" classes.

The formal syntax makes no special provision for negative indices in
*sequences*. However, built-in sequences all provide a "__getitem__()"
method that interprets negative indices by adding the length of the
sequence to the index so that, for example, "x[-1]" selects the last
item of "x". The resulting value must be a nonnegative integer less
than the number of items in the sequence, and the subscription selects
the item whose index is that value (counting from zero). Since the
support for negative indices and slicing occurs in the object’s
"__getitem__()" method, subclasses overriding this method will need to
explicitly add that support.

A "string" is a special kind of sequence whose items are *characters*.
A character is not a separate data type but a string of exactly one
character.
''',
    'truth': r'''Truth Value Testing
*******************

Any object can be tested for truth value, for use in an "if" or
"while" condition or as operand of the Boolean operations below.

By default, an object is considered true unless its class defines
either a "__bool__()" method that returns "False" or a "__len__()"
method that returns zero, when called with the object. [1]  Here are
most of the built-in objects considered false:

* constants defined to be false: "None" and "False"

* zero of any numeric type: "0", "0.0", "0j", "Decimal(0)",
  "Fraction(0, 1)"

* empty sequences and collections: "''", "()", "[]", "{}", "set()",
  "range(0)"

Operations and built-in functions that have a Boolean result always
return "0" or "False" for false and "1" or "True" for true, unless
otherwise stated. (Important exception: the Boolean operations "or"
and "and" always return one of their operands.)
''',
    'try': r'''The "try" statement
*******************

The "try" statement specifies exception handlers and/or cleanup code
for a group of statements:

   try_stmt  ::= try1_stmt | try2_stmt | try3_stmt
   try1_stmt ::= "try" ":" suite
                 ("except" [expression ["as" identifier]] ":" suite)+
                 ["else" ":" suite]
                 ["finally" ":" suite]
   try2_stmt ::= "try" ":" suite
                 ("except" "*" expression ["as" identifier] ":" suite)+
                 ["else" ":" suite]
                 ["finally" ":" suite]
   try3_stmt ::= "try" ":" suite
                 "finally" ":" suite

Additional information on exceptions can be found in section
Exceptions, and information on using the "raise" statement to generate
exceptions may be found in section The raise statement.


"except" clause
===============

The "except" clause(s) specify one or more exception handlers. When no
exception occurs in the "try" clause, no exception handler is
executed. When an exception occurs in the "try" suite, a search for an
exception handler is started. This search inspects the "except"
clauses in turn until one is found that matches the exception. An
expression-less "except" clause, if present, must be last; it matches
any exception.

For an "except" clause with an expression, the expression must
evaluate to an exception type or a tuple of exception types. The
raised exception matches an "except" clause whose expression evaluates
to the class or a *non-virtual base class* of the exception object, or
to a tuple that contains such a class.

If no "except" clause matches the exception, the search for an
exception handler continues in the surrounding code and on the
invocation stack.  [1]

If the evaluation of an expression in the header of an "except" clause
raises an exception, the original search for a handler is canceled and
a search starts for the new exception in the surrounding code and on
the call stack (it is treated as if the entire "try" statement raised
the exception).

When a matching "except" clause is found, the exception is assigned to
the target specified after the "as" keyword in that "except" clause,
if present, and the "except" clause’s suite is executed. All "except"
clauses must have an executable block. When the end of this block is
reached, execution continues normally after the entire "try"
statement. (This means that if two nested handlers exist for the same
exception, and the exception occurs in the "try" clause of the inner
handler, the outer handler will not handle the exception.)

When an exception has been assigned using "as target", it is cleared
at the end of the "except" clause.  This is as if

   except E as N:
       foo

was translated to

   except E as N:
       try:
           foo
       finally:
           del N

This means the exception must be assigned to a different name to be
able to refer to it after the "except" clause. Exceptions are cleared
because with the traceback attached to them, they form a reference
cycle with the stack frame, keeping all locals in that frame alive
until the next garbage collection occurs.

Before an "except" clause’s suite is executed, the exception is stored
in the "sys" module, where it can be accessed from within the body of
the "except" clause by calling "sys.exception()". When leaving an
exception handler, the exception stored in the "sys" module is reset
to its previous value:

   >>> print(sys.exception())
   None
   >>> try:
   ...     raise TypeError
   ... except:
   ...     print(repr(sys.exception()))
   ...     try:
   ...          raise ValueError
   ...     except:
   ...         print(repr(sys.exception()))
   ...     print(repr(sys.exception()))
   ...
   TypeError()
   ValueError()
   TypeError()
   >>> print(sys.exception())
   None


"except*" clause
================

The "except*" clause(s) are used for handling "ExceptionGroup"s. The
exception type for matching is interpreted as in the case of "except",
but in the case of exception groups we can have partial matches when
the type matches some of the exceptions in the group. This means that
multiple "except*" clauses can execute, each handling part of the
exception group. Each clause executes at most once and handles an
exception group of all matching exceptions.  Each exception in the
group is handled by at most one "except*" clause, the first that
matches it.

   >>> try:
   ...     raise ExceptionGroup("eg",
   ...         [ValueError(1), TypeError(2), OSError(3), OSError(4)])
   ... except* TypeError as e:
   ...     print(f'caught {type(e)} with nested {e.exceptions}')
   ... except* OSError as e:
   ...     print(f'caught {type(e)} with nested {e.exceptions}')
   ...
   caught <class 'ExceptionGroup'> with nested (TypeError(2),)
   caught <class 'ExceptionGroup'> with nested (OSError(3), OSError(4))
     + Exception Group Traceback (most recent call last):
     |   File "<stdin>", line 2, in <module>
     | ExceptionGroup: eg
     +-+---------------- 1 ----------------
       | ValueError: 1
       +------------------------------------

Any remaining exceptions that were not handled by any "except*" clause
are re-raised at the end, along with all exceptions that were raised
from within the "except*" clauses. If this list contains more than one
exception to reraise, they are combined into an exception group.

If the raised exception is not an exception group and its type matches
one of the "except*" clauses, it is caught and wrapped by an exception
group with an empty message string.

   >>> try:
   ...     raise BlockingIOError
   ... except* BlockingIOError as e:
   ...     print(repr(e))
   ...
   ExceptionGroup('', (BlockingIOError()))

An "except*" clause must have a matching expression; it cannot be
"except*:". Furthermore, this expression cannot contain exception
group types, because that would have ambiguous semantics.

It is not possible to mix "except" and "except*" in the same "try".
"break", "continue" and "return" cannot appear in an "except*" clause.


"else" clause
=============

The optional "else" clause is executed if the control flow leaves the
"try" suite, no exception was raised, and no "return", "continue", or
"break" statement was executed.  Exceptions in the "else" clause are
not handled by the preceding "except" clauses.


"finally" clause
================

If "finally" is present, it specifies a ‘cleanup’ handler.  The "try"
clause is executed, including any "except" and "else" clauses.  If an
exception occurs in any of the clauses and is not handled, the
exception is temporarily saved. The "finally" clause is executed.  If
there is a saved exception it is re-raised at the end of the "finally"
clause.  If the "finally" clause raises another exception, the saved
exception is set as the context of the new exception. If the "finally"
clause executes a "return", "break" or "continue" statement, the saved
exception is discarded:

   >>> def f():
   ...     try:
   ...         1/0
   ...     finally:
   ...         return 42
   ...
   >>> f()
   42

The exception information is not available to the program during
execution of the "finally" clause.

When a "return", "break" or "continue" statement is executed in the
"try" suite of a "try"…"finally" statement, the "finally" clause is
also executed ‘on the way out.’

The return value of a function is determined by the last "return"
statement executed.  Since the "finally" clause always executes, a
"return" statement executed in the "finally" clause will always be the
last one executed:

   >>> def foo():
   ...     try:
   ...         return 'try'
   ...     finally:
   ...         return 'finally'
   ...
   >>> foo()
   'finally'

Changed in version 3.8: Prior to Python 3.8, a "continue" statement
was illegal in the "finally" clause due to a problem with the
implementation.
''',
    'types': r'''The standard type hierarchy
***************************

Below is a list of the types that are built into Python.  Extension
modules (written in C, Java, or other languages, depending on the
implementation) can define additional types.  Future versions of
Python may add types to the type hierarchy (e.g., rational numbers,
efficiently stored arrays of integers, etc.), although such additions
will often be provided via the standard library instead.

Some of the type descriptions below contain a paragraph listing
‘special attributes.’  These are attributes that provide access to the
implementation and are not intended for general use.  Their definition
may change in the future.


None
====

This type has a single value.  There is a single object with this
value. This object is accessed through the built-in name "None". It is
used to signify the absence of a value in many situations, e.g., it is
returned from functions that don’t explicitly return anything. Its
truth value is false.


NotImplemented
==============

This type has a single value.  There is a single object with this
value. This object is accessed through the built-in name
"NotImplemented". Numeric methods and rich comparison methods should
return this value if they do not implement the operation for the
operands provided.  (The interpreter will then try the reflected
operation, or some other fallback, depending on the operator.)  It
should not be evaluated in a boolean context.

See Implementing the arithmetic operations for more details.

Changed in version 3.9: Evaluating "NotImplemented" in a boolean
context is deprecated. While it currently evaluates as true, it will
emit a "DeprecationWarning". It will raise a "TypeError" in a future
version of Python.


Ellipsis
========

This type has a single value.  There is a single object with this
value. This object is accessed through the literal "..." or the built-
in name "Ellipsis".  Its truth value is true.


"numbers.Number"
================

These are created by numeric literals and returned as results by
arithmetic operators and arithmetic built-in functions.  Numeric
objects are immutable; once created their value never changes.  Python
numbers are of course strongly related to mathematical numbers, but
subject to the limitations of numerical representation in computers.

The string representations of the numeric classes, computed by
"__repr__()" and "__str__()", have the following properties:

* They are valid numeric literals which, when passed to their class
  constructor, produce an object having the value of the original
  numeric.

* The representation is in base 10, when possible.

* Leading zeros, possibly excepting a single zero before a decimal
  point, are not shown.

* Trailing zeros, possibly excepting a single zero after a decimal
  point, are not shown.

* A sign is shown only when the number is negative.

Python distinguishes between integers, floating-point numbers, and
complex numbers:


"numbers.Integral"
------------------

These represent elements from the mathematical set of integers
(positive and negative).

Note:

  The rules for integer representation are intended to give the most
  meaningful interpretation of shift and mask operations involving
  negative integers.

There are two types of integers:

Integers ("int")
   These represent numbers in an unlimited range, subject to available
   (virtual) memory only.  For the purpose of shift and mask
   operations, a binary representation is assumed, and negative
   numbers are represented in a variant of 2’s complement which gives
   the illusion of an infinite string of sign bits extending to the
   left.

Booleans ("bool")
   These represent the truth values False and True.  The two objects
   representing the values "False" and "True" are the only Boolean
   objects. The Boolean type is a subtype of the integer type, and
   Boolean values behave like the values 0 and 1, respectively, in
   almost all contexts, the exception being that when converted to a
   string, the strings ""False"" or ""True"" are returned,
   respectively.


"numbers.Real" ("float")
------------------------

These represent machine-level double precision floating-point numbers.
You are at the mercy of the underlying machine architecture (and C or
Java implementation) for the accepted range and handling of overflow.
Python does not support single-precision floating-point numbers; the
savings in processor and memory usage that are usually the reason for
using these are dwarfed by the overhead of using objects in Python, so
there is no reason to complicate the language with two kinds of
floating-point numbers.


"numbers.Complex" ("complex")
-----------------------------

These represent complex numbers as a pair of machine-level double
precision floating-point numbers.  The same caveats apply as for
floating-point numbers. The real and imaginary parts of a complex
number "z" can be retrieved through the read-only attributes "z.real"
and "z.imag".


Sequences
=========

These represent finite ordered sets indexed by non-negative numbers.
The built-in function "len()" returns the number of items of a
sequence. When the length of a sequence is *n*, the index set contains
the numbers 0, 1, …, *n*-1.  Item *i* of sequence *a* is selected by
"a[i]". Some sequences, including built-in sequences, interpret
negative subscripts by adding the sequence length. For example,
"a[-2]" equals "a[n-2]", the second to last item of sequence a with
length "n".

Sequences also support slicing: "a[i:j]" selects all items with index
*k* such that *i* "<=" *k* "<" *j*.  When used as an expression, a
slice is a sequence of the same type. The comment above about negative
indexes also applies to negative slice positions.

Some sequences also support “extended slicing” with a third “step”
parameter: "a[i:j:k]" selects all items of *a* with index *x* where "x
= i + n*k", *n* ">=" "0" and *i* "<=" *x* "<" *j*.

Sequences are distinguished according to their mutability:


Immutable sequences
-------------------

An object of an immutable sequence type cannot change once it is
created.  (If the object contains references to other objects, these
other objects may be mutable and may be changed; however, the
collection of objects directly referenced by an immutable object
cannot change.)

The following types are immutable sequences:

Strings
   A string is a sequence of values that represent Unicode code
   points. All the code points in the range "U+0000 - U+10FFFF" can be
   represented in a string.  Python doesn’t have a char type; instead,
   every code point in the string is represented as a string object
   with length "1".  The built-in function "ord()" converts a code
   point from its string form to an integer in the range "0 - 10FFFF";
   "chr()" converts an integer in the range "0 - 10FFFF" to the
   corresponding length "1" string object. "str.encode()" can be used
   to convert a "str" to "bytes" using the given text encoding, and
   "bytes.decode()" can be used to achieve the opposite.

Tuples
   The items of a tuple are arbitrary Python objects. Tuples of two or
   more items are formed by comma-separated lists of expressions.  A
   tuple of one item (a ‘singleton’) can be formed by affixing a comma
   to an expression (an expression by itself does not create a tuple,
   since parentheses must be usable for grouping of expressions).  An
   empty tuple can be formed by an empty pair of parentheses.

Bytes
   A bytes object is an immutable array.  The items are 8-bit bytes,
   represented by integers in the range 0 <= x < 256.  Bytes literals
   (like "b'abc'") and the built-in "bytes()" constructor can be used
   to create bytes objects.  Also, bytes objects can be decoded to
   strings via the "decode()" method.


Mutable sequences
-----------------

Mutable sequences can be changed after they are created.  The
subscription and slicing notations can be used as the target of
assignment and "del" (delete) statements.

Note:

  The "collections" and "array" module provide additional examples of
  mutable sequence types.

There are currently two intrinsic mutable sequence types:

Lists
   The items of a list are arbitrary Python objects.  Lists are formed
   by placing a comma-separated list of expressions in square
   brackets. (Note that there are no special cases needed to form
   lists of length 0 or 1.)

Byte Arrays
   A bytearray object is a mutable array. They are created by the
   built-in "bytearray()" constructor.  Aside from being mutable (and
   hence unhashable), byte arrays otherwise provide the same interface
   and functionality as immutable "bytes" objects.


Set types
=========

These represent unordered, finite sets of unique, immutable objects.
As such, they cannot be indexed by any subscript. However, they can be
iterated over, and the built-in function "len()" returns the number of
items in a set. Common uses for sets are fast membership testing,
removing duplicates from a sequence, and computing mathematical
operations such as intersection, union, difference, and symmetric
difference.

For set elements, the same immutability rules apply as for dictionary
keys. Note that numeric types obey the normal rules for numeric
comparison: if two numbers compare equal (e.g., "1" and "1.0"), only
one of them can be contained in a set.

There are currently two intrinsic set types:

Sets
   These represent a mutable set. They are created by the built-in
   "set()" constructor and can be modified afterwards by several
   methods, such as "add()".

Frozen sets
   These represent an immutable set.  They are created by the built-in
   "frozenset()" constructor.  As a frozenset is immutable and
   *hashable*, it can be used again as an element of another set, or
   as a dictionary key.


Mappings
========

These represent finite sets of objects indexed by arbitrary index
sets. The subscript notation "a[k]" selects the item indexed by "k"
from the mapping "a"; this can be used in expressions and as the
target of assignments or "del" statements. The built-in function
"len()" returns the number of items in a mapping.

There is currently a single intrinsic mapping type:


Dictionaries
------------

These represent finite sets of objects indexed by nearly arbitrary
values.  The only types of values not acceptable as keys are values
containing lists or dictionaries or other mutable types that are
compared by value rather than by object identity, the reason being
that the efficient implementation of dictionaries requires a key’s
hash value to remain constant. Numeric types used for keys obey the
normal rules for numeric comparison: if two numbers compare equal
(e.g., "1" and "1.0") then they can be used interchangeably to index
the same dictionary entry.

Dictionaries preserve insertion order, meaning that keys will be
produced in the same order they were added sequentially over the
dictionary. Replacing an existing key does not change the order,
however removing a key and re-inserting it will add it to the end
instead of keeping its old place.

Dictionaries are mutable; they can be created by the "{}" notation
(see section Dictionary displays).

The extension modules "dbm.ndbm" and "dbm.gnu" provide additional
examples of mapping types, as does the "collections" module.

Changed in version 3.7: Dictionaries did not preserve insertion order
in versions of Python before 3.6. In CPython 3.6, insertion order was
preserved, but it was considered an implementation detail at that time
rather than a language guarantee.


Callable types
==============

These are the types to which the function call operation (see section
Calls) can be applied:


User-defined functions
----------------------

A user-defined function object is created by a function definition
(see section Function definitions).  It should be called with an
argument list containing the same number of items as the function’s
formal parameter list.


Special read-only attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+----------------------------------------------------+----------------------------------------------------+
| Attribute                                          | Meaning                                            |
|====================================================|====================================================|
| function.__globals__                               | A reference to the "dictionary" that holds the     |
|                                                    | function’s global variables – the global namespace |
|                                                    | of the module in which the function was defined.   |
+----------------------------------------------------+----------------------------------------------------+
| function.__closure__                               | "None" or a "tuple" of cells that contain bindings |
|                                                    | for the function’s free variables.  A cell object  |
|                                                    | has the attribute "cell_contents". This can be     |
|                                                    | used to get the value of the cell, as well as set  |
|                                                    | the value.                                         |
+----------------------------------------------------+----------------------------------------------------+


Special writable attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Most of these attributes check the type of the assigned value:

+----------------------------------------------------+----------------------------------------------------+
| Attribute                                          | Meaning                                            |
|====================================================|====================================================|
| function.__doc__                                   | The function’s documentation string, or "None" if  |
|                                                    | unavailable.                                       |
+----------------------------------------------------+----------------------------------------------------+
| function.__name__                                  | The function’s name. See also: "__name__           |
|                                                    | attributes".                                       |
+----------------------------------------------------+----------------------------------------------------+
| function.__qualname__                              | The function’s *qualified name*. See also:         |
|                                                    | "__qualname__ attributes".  Added in version 3.3.  |
+----------------------------------------------------+----------------------------------------------------+
| function.__module__                                | The name of the module the function was defined    |
|                                                    | in, or "None" if unavailable.                      |
+----------------------------------------------------+----------------------------------------------------+
| function.__defaults__                              | A "tuple" containing default *parameter* values    |
|                                                    | for those parameters that have defaults, or "None" |
|                                                    | if no parameters have a default value.             |
+----------------------------------------------------+----------------------------------------------------+
| function.__code__                                  | The code object representing the compiled function |
|                                                    | body.                                              |
+----------------------------------------------------+----------------------------------------------------+
| function.__dict__                                  | The namespace supporting arbitrary function        |
|                                                    | attributes. See also: "__dict__ attributes".       |
+----------------------------------------------------+----------------------------------------------------+
| function.__annotations__                           | A "dictionary" containing annotations of           |
|                                                    | *parameters*. The keys of the dictionary are the   |
|                                                    | parameter names, and "'return'" for the return     |
|                                                    | annotation, if provided. See also: Annotations     |
|                                                    | Best Practices.                                    |
+----------------------------------------------------+----------------------------------------------------+
| function.__kwdefaults__                            | A "dictionary" containing defaults for keyword-    |
|                                                    | only *parameters*.                                 |
+----------------------------------------------------+----------------------------------------------------+
| function.__type_params__                           | A "tuple" containing the type parameters of a      |
|                                                    | generic function.  Added in version 3.12.          |
+----------------------------------------------------+----------------------------------------------------+

Function objects also support getting and setting arbitrary
attributes, which can be used, for example, to attach metadata to
functions.  Regular attribute dot-notation is used to get and set such
attributes.

**CPython implementation detail:** CPython’s current implementation
only supports function attributes on user-defined functions. Function
attributes on built-in functions may be supported in the future.

Additional information about a function’s definition can be retrieved
from its code object (accessible via the "__code__" attribute).


Instance methods
----------------

An instance method object combines a class, a class instance and any
callable object (normally a user-defined function).

Special read-only attributes:

+----------------------------------------------------+----------------------------------------------------+
| method.__self__                                    | Refers to the class instance object to which the   |
|                                                    | method is bound                                    |
+----------------------------------------------------+----------------------------------------------------+
| method.__func__                                    | Refers to the original function object             |
+----------------------------------------------------+----------------------------------------------------+
| method.__doc__                                     | The method’s documentation (same as                |
|                                                    | "method.__func__.__doc__"). A "string" if the      |
|                                                    | original function had a docstring, else "None".    |
+----------------------------------------------------+----------------------------------------------------+
| method.__name__                                    | The name of the method (same as                    |
|                                                    | "method.__func__.__name__")                        |
+----------------------------------------------------+----------------------------------------------------+
| method.__module__                                  | The name of the module the method was defined in,  |
|                                                    | or "None" if unavailable.                          |
+----------------------------------------------------+----------------------------------------------------+

Methods also support accessing (but not setting) the arbitrary
function attributes on the underlying function object.

User-defined method objects may be created when getting an attribute
of a class (perhaps via an instance of that class), if that attribute
is a user-defined function object or a "classmethod" object.

When an instance method object is created by retrieving a user-defined
function object from a class via one of its instances, its "__self__"
attribute is the instance, and the method object is said to be
*bound*.  The new method’s "__func__" attribute is the original
function object.

When an instance method object is created by retrieving a
"classmethod" object from a class or instance, its "__self__"
attribute is the class itself, and its "__func__" attribute is the
function object underlying the class method.

When an instance method object is called, the underlying function
("__func__") is called, inserting the class instance ("__self__") in
front of the argument list.  For instance, when "C" is a class which
contains a definition for a function "f()", and "x" is an instance of
"C", calling "x.f(1)" is equivalent to calling "C.f(x, 1)".

When an instance method object is derived from a "classmethod" object,
the “class instance” stored in "__self__" will actually be the class
itself, so that calling either "x.f(1)" or "C.f(1)" is equivalent to
calling "f(C,1)" where "f" is the underlying function.

It is important to note that user-defined functions which are
attributes of a class instance are not converted to bound methods;
this *only* happens when the function is an attribute of the class.


Generator functions
-------------------

A function or method which uses the "yield" statement (see section The
yield statement) is called a *generator function*.  Such a function,
when called, always returns an *iterator* object which can be used to
execute the body of the function:  calling the iterator’s
"iterator.__next__()" method will cause the function to execute until
it provides a value using the "yield" statement.  When the function
executes a "return" statement or falls off the end, a "StopIteration"
exception is raised and the iterator will have reached the end of the
set of values to be returned.


Coroutine functions
-------------------

A function or method which is defined using "async def" is called a
*coroutine function*.  Such a function, when called, returns a
*coroutine* object.  It may contain "await" expressions, as well as
"async with" and "async for" statements. See also the Coroutine
Objects section.


Asynchronous generator functions
--------------------------------

A function or method which is defined using "async def" and which uses
the "yield" statement is called a *asynchronous generator function*.
Such a function, when called, returns an *asynchronous iterator*
object which can be used in an "async for" statement to execute the
body of the function.

Calling the asynchronous iterator’s "aiterator.__anext__" method will
return an *awaitable* which when awaited will execute until it
provides a value using the "yield" expression.  When the function
executes an empty "return" statement or falls off the end, a
"StopAsyncIteration" exception is raised and the asynchronous iterator
will have reached the end of the set of values to be yielded.


Built-in functions
------------------

A built-in function object is a wrapper around a C function.  Examples
of built-in functions are "len()" and "math.sin()" ("math" is a
standard built-in module). The number and type of the arguments are
determined by the C function. Special read-only attributes:

* "__doc__" is the function’s documentation string, or "None" if
  unavailable. See "function.__doc__".

* "__name__" is the function’s name. See "function.__name__".

* "__self__" is set to "None" (but see the next item).

* "__module__" is the name of the module the function was defined in
  or "None" if unavailable. See "function.__module__".


Built-in methods
----------------

This is really a different disguise of a built-in function, this time
containing an object passed to the C function as an implicit extra
argument.  An example of a built-in method is "alist.append()",
assuming *alist* is a list object. In this case, the special read-only
attribute "__self__" is set to the object denoted by *alist*. (The
attribute has the same semantics as it does with "other instance
methods".)


Classes
-------

Classes are callable.  These objects normally act as factories for new
instances of themselves, but variations are possible for class types
that override "__new__()".  The arguments of the call are passed to
"__new__()" and, in the typical case, to "__init__()" to initialize
the new instance.


Class Instances
---------------

Instances of arbitrary classes can be made callable by defining a
"__call__()" method in their class.


Modules
=======

Modules are a basic organizational unit of Python code, and are
created by the import system as invoked either by the "import"
statement, or by calling functions such as "importlib.import_module()"
and built-in "__import__()".  A module object has a namespace
implemented by a "dictionary" object (this is the dictionary
referenced by the "__globals__" attribute of functions defined in the
module).  Attribute references are translated to lookups in this
dictionary, e.g., "m.x" is equivalent to "m.__dict__["x"]". A module
object does not contain the code object used to initialize the module
(since it isn’t needed once the initialization is done).

Attribute assignment updates the module’s namespace dictionary, e.g.,
"m.x = 1" is equivalent to "m.__dict__["x"] = 1".


Import-related attributes on module objects
-------------------------------------------

Module objects have the following attributes that relate to the import
system. When a module is created using the machinery associated with
the import system, these attributes are filled in based on the
module’s *spec*, before the *loader* executes and loads the module.

To create a module dynamically rather than using the import system,
it’s recommended to use "importlib.util.module_from_spec()", which
will set the various import-controlled attributes to appropriate
values. It’s also possible to use the "types.ModuleType" constructor
to create modules directly, but this technique is more error-prone, as
most attributes must be manually set on the module object after it has
been created when using this approach.

Caution:

  With the exception of "__name__", it is **strongly** recommended
  that you rely on "__spec__" and its attributes instead of any of the
  other individual attributes listed in this subsection. Note that
  updating an attribute on "__spec__" will not update the
  corresponding attribute on the module itself:

     >>> import typing
     >>> typing.__name__, typing.__spec__.name
     ('typing', 'typing')
     >>> typing.__spec__.name = 'spelling'
     >>> typing.__name__, typing.__spec__.name
     ('typing', 'spelling')
     >>> typing.__name__ = 'keyboard_smashing'
     >>> typing.__name__, typing.__spec__.name
     ('keyboard_smashing', 'spelling')

module.__name__

   The name used to uniquely identify the module in the import system.
   For a directly executed module, this will be set to ""__main__"".

   This attribute must be set to the fully qualified name of the
   module. It is expected to match the value of
   "module.__spec__.name".

module.__spec__

   A record of the module’s import-system-related state.

   Set to the "module spec" that was used when importing the module.
   See Module specs for more details.

   Added in version 3.4.

module.__package__

   The *package* a module belongs to.

   If the module is top-level (that is, not a part of any specific
   package) then the attribute should be set to "''" (the empty
   string). Otherwise, it should be set to the name of the module’s
   package (which can be equal to "module.__name__" if the module
   itself is a package). See **PEP 366** for further details.

   This attribute is used instead of "__name__" to calculate explicit
   relative imports for main modules. It defaults to "None" for
   modules created dynamically using the "types.ModuleType"
   constructor; use "importlib.util.module_from_spec()" instead to
   ensure the attribute is set to a "str".

   It is **strongly** recommended that you use
   "module.__spec__.parent" instead of "module.__package__".
   "__package__" is now only used as a fallback if "__spec__.parent"
   is not set, and this fallback path is deprecated.

   Changed in version 3.4: This attribute now defaults to "None" for
   modules created dynamically using the "types.ModuleType"
   constructor. Previously the attribute was optional.

   Changed in version 3.6: The value of "__package__" is expected to
   be the same as "__spec__.parent". "__package__" is now only used as
   a fallback during import resolution if "__spec__.parent" is not
   defined.

   Changed in version 3.10: "ImportWarning" is raised if an import
   resolution falls back to "__package__" instead of
   "__spec__.parent".

   Changed in version 3.12: Raise "DeprecationWarning" instead of
   "ImportWarning" when falling back to "__package__" during import
   resolution.

module.__loader__

   The *loader* object that the import machinery used to load the
   module.

   This attribute is mostly useful for introspection, but can be used
   for additional loader-specific functionality, for example getting
   data associated with a loader.

   "__loader__" defaults to "None" for modules created dynamically
   using the "types.ModuleType" constructor; use
   "importlib.util.module_from_spec()" instead to ensure the attribute
   is set to a *loader* object.

   It is **strongly** recommended that you use
   "module.__spec__.loader" instead of "module.__loader__".

   Changed in version 3.4: This attribute now defaults to "None" for
   modules created dynamically using the "types.ModuleType"
   constructor. Previously the attribute was optional.

   Deprecated since version 3.12, will be removed in version 3.16:
   Setting "__loader__" on a module while failing to set
   "__spec__.loader" is deprecated. In Python 3.16, "__loader__" will
   cease to be set or taken into consideration by the import system or
   the standard library.

module.__path__

   A (possibly empty) *sequence* of strings enumerating the locations
   where the package’s submodules will be found. Non-package modules
   should not have a "__path__" attribute. See __path__ attributes on
   modules for more details.

   It is **strongly** recommended that you use
   "module.__spec__.submodule_search_locations" instead of
   "module.__path__".

module.__file__

module.__cached__

   "__file__" and "__cached__" are both optional attributes that may
   or may not be set. Both attributes should be a "str" when they are
   available.

   "__file__" indicates the pathname of the file from which the module
   was loaded (if loaded from a file), or the pathname of the shared
   library file for extension modules loaded dynamically from a shared
   library. It might be missing for certain types of modules, such as
   C modules that are statically linked into the interpreter, and the
   import system may opt to leave it unset if it has no semantic
   meaning (for example, a module loaded from a database).

   If "__file__" is set then the "__cached__" attribute might also be
   set,  which is the path to any compiled version of the code (for
   example, a byte-compiled file). The file does not need to exist to
   set this attribute; the path can simply point to where the compiled
   file *would* exist (see **PEP 3147**).

   Note that "__cached__" may be set even if "__file__" is not set.
   However, that scenario is quite atypical.  Ultimately, the *loader*
   is what makes use of the module spec provided by the *finder* (from
   which "__file__" and "__cached__" are derived).  So if a loader can
   load from a cached module but otherwise does not load from a file,
   that atypical scenario may be appropriate.

   It is **strongly** recommended that you use
   "module.__spec__.cached" instead of "module.__cached__".


Other writable attributes on module objects
-------------------------------------------

As well as the import-related attributes listed above, module objects
also have the following writable attributes:

module.__doc__

   The module’s documentation string, or "None" if unavailable. See
   also: "__doc__ attributes".

module.__annotations__

   A dictionary containing *variable annotations* collected during
   module body execution.  For best practices on working with
   "__annotations__", please see Annotations Best Practices.


Module dictionaries
-------------------

Module objects also have the following special read-only attribute:

module.__dict__

   The module’s namespace as a dictionary object. Uniquely among the
   attributes listed here, "__dict__" cannot be accessed as a global
   variable from within a module; it can only be accessed as an
   attribute on module objects.

   **CPython implementation detail:** Because of the way CPython
   clears module dictionaries, the module dictionary will be cleared
   when the module falls out of scope even if the dictionary still has
   live references.  To avoid this, copy the dictionary or keep the
   module around while using its dictionary directly.


Custom classes
==============

Custom class types are typically created by class definitions (see
section Class definitions).  A class has a namespace implemented by a
dictionary object. Class attribute references are translated to
lookups in this dictionary, e.g., "C.x" is translated to
"C.__dict__["x"]" (although there are a number of hooks which allow
for other means of locating attributes). When the attribute name is
not found there, the attribute search continues in the base classes.
This search of the base classes uses the C3 method resolution order
which behaves correctly even in the presence of ‘diamond’ inheritance
structures where there are multiple inheritance paths leading back to
a common ancestor. Additional details on the C3 MRO used by Python can
be found at The Python 2.3 Method Resolution Order.

When a class attribute reference (for class "C", say) would yield a
class method object, it is transformed into an instance method object
whose "__self__" attribute is "C". When it would yield a
"staticmethod" object, it is transformed into the object wrapped by
the static method object. See section Implementing Descriptors for
another way in which attributes retrieved from a class may differ from
those actually contained in its "__dict__".

Class attribute assignments update the class’s dictionary, never the
dictionary of a base class.

A class object can be called (see above) to yield a class instance
(see below).


Special attributes
------------------

+----------------------------------------------------+----------------------------------------------------+
| Attribute                                          | Meaning                                            |
|====================================================|====================================================|
| type.__name__                                      | The class’s name. See also: "__name__ attributes". |
+----------------------------------------------------+----------------------------------------------------+
| type.__qualname__                                  | The class’s *qualified name*. See also:            |
|                                                    | "__qualname__ attributes".                         |
+----------------------------------------------------+----------------------------------------------------+
| type.__module__                                    | The name of the module in which the class was      |
|                                                    | defined.                                           |
+----------------------------------------------------+----------------------------------------------------+
| type.__dict__                                      | A "mapping proxy" providing a read-only view of    |
|                                                    | the class’s namespace. See also: "__dict__         |
|                                                    | attributes".                                       |
+----------------------------------------------------+----------------------------------------------------+
| type.__bases__                                     | A "tuple" containing the class’s bases. In most    |
|                                                    | cases, for a class defined as "class X(A, B, C)",  |
|                                                    | "X.__bases__" will be exactly equal to "(A, B,     |
|                                                    | C)".                                               |
+----------------------------------------------------+----------------------------------------------------+
| type.__doc__                                       | The class’s documentation string, or "None" if     |
|                                                    | undefined. Not inherited by subclasses.            |
+----------------------------------------------------+----------------------------------------------------+
| type.__annotations__                               | A dictionary containing *variable annotations*     |
|                                                    | collected during class body execution. For best    |
|                                                    | practices on working with "__annotations__",       |
|                                                    | please see Annotations Best Practices.  Caution:   |
|                                                    | Accessing the "__annotations__" attribute of a     |
|                                                    | class object directly may yield incorrect results  |
|                                                    | in the presence of metaclasses. In addition, the   |
|                                                    | attribute may not exist for some classes. Use      |
|                                                    | "inspect.get_annotations()" to retrieve class      |
|                                                    | annotations safely.                                |
+----------------------------------------------------+----------------------------------------------------+
| type.__type_params__                               | A "tuple" containing the type parameters of a      |
|                                                    | generic class.  Added in version 3.12.             |
+----------------------------------------------------+----------------------------------------------------+
| type.__mro__                                       | The "tuple" of classes that are considered when    |
|                                                    | looking for base classes during method resolution. |
+----------------------------------------------------+----------------------------------------------------+


Special methods
---------------

In addition to the special attributes described above, all Python
classes also have the following two methods available:

type.mro()

   This method can be overridden by a metaclass to customize the
   method resolution order for its instances.  It is called at class
   instantiation, and its result is stored in "__mro__".

type.__subclasses__()

   Each class keeps a list of weak references to its immediate
   subclasses. This method returns a list of all those references
   still alive. The list is in definition order. Example:

      >>> class A: pass
      >>> class B(A): pass
      >>> A.__subclasses__()
      [<class 'B'>]


Class instances
===============

A class instance is created by calling a class object (see above).  A
class instance has a namespace implemented as a dictionary which is
the first place in which attribute references are searched.  When an
attribute is not found there, and the instance’s class has an
attribute by that name, the search continues with the class
attributes.  If a class attribute is found that is a user-defined
function object, it is transformed into an instance method object
whose "__self__" attribute is the instance.  Static method and class
method objects are also transformed; see above under “Classes”.  See
section Implementing Descriptors for another way in which attributes
of a class retrieved via its instances may differ from the objects
actually stored in the class’s "__dict__".  If no class attribute is
found, and the object’s class has a "__getattr__()" method, that is
called to satisfy the lookup.

Attribute assignments and deletions update the instance’s dictionary,
never a class’s dictionary.  If the class has a "__setattr__()" or
"__delattr__()" method, this is called instead of updating the
instance dictionary directly.

Class instances can pretend to be numbers, sequences, or mappings if
they have methods with certain special names.  See section Special
method names.


Special attributes
------------------

object.__class__

   The class to which a class instance belongs.

object.__dict__

   A dictionary or other mapping object used to store an object’s
   (writable) attributes. Not all instances have a "__dict__"
   attribute; see the section on __slots__ for more details.


I/O objects (also known as file objects)
========================================

A *file object* represents an open file.  Various shortcuts are
available to create file objects: the "open()" built-in function, and
also "os.popen()", "os.fdopen()", and the "makefile()" method of
socket objects (and perhaps by other functions or methods provided by
extension modules).

The objects "sys.stdin", "sys.stdout" and "sys.stderr" are initialized
to file objects corresponding to the interpreter’s standard input,
output and error streams; they are all open in text mode and therefore
follow the interface defined by the "io.TextIOBase" abstract class.


Internal types
==============

A few types used internally by the interpreter are exposed to the
user. Their definitions may change with future versions of the
interpreter, but they are mentioned here for completeness.


Code objects
------------

Code objects represent *byte-compiled* executable Python code, or
*bytecode*. The difference between a code object and a function object
is that the function object contains an explicit reference to the
function’s globals (the module in which it was defined), while a code
object contains no context; also the default argument values are
stored in the function object, not in the code object (because they
represent values calculated at run-time).  Unlike function objects,
code objects are immutable and contain no references (directly or
indirectly) to mutable objects.


Special read-only attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_name                                 | The function name                                  |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_qualname                             | The fully qualified function name  Added in        |
|                                                    | version 3.11.                                      |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_argcount                             | The total number of positional *parameters*        |
|                                                    | (including positional-only parameters and          |
|                                                    | parameters with default values) that the function  |
|                                                    | has                                                |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_posonlyargcount                      | The number of positional-only *parameters*         |
|                                                    | (including arguments with default values) that the |
|                                                    | function has                                       |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_kwonlyargcount                       | The number of keyword-only *parameters* (including |
|                                                    | arguments with default values) that the function   |
|                                                    | has                                                |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_nlocals                              | The number of local variables used by the function |
|                                                    | (including parameters)                             |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_varnames                             | A "tuple" containing the names of the local        |
|                                                    | variables in the function (starting with the       |
|                                                    | parameter names)                                   |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_cellvars                             | A "tuple" containing the names of local variables  |
|                                                    | that are referenced by nested functions inside the |
|                                                    | function                                           |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_freevars                             | A "tuple" containing the names of free variables   |
|                                                    | in the function                                    |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_code                                 | A string representing the sequence of *bytecode*   |
|                                                    | instructions in the function                       |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_consts                               | A "tuple" containing the literals used by the      |
|                                                    | *bytecode* in the function                         |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_names                                | A "tuple" containing the names used by the         |
|                                                    | *bytecode* in the function                         |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_filename                             | The name of the file from which the code was       |
|                                                    | compiled                                           |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_firstlineno                          | The line number of the first line of the function  |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_lnotab                               | A string encoding the mapping from *bytecode*      |
|                                                    | offsets to line numbers. For details, see the      |
|                                                    | source code of the interpreter.  Deprecated since  |
|                                                    | version 3.12: This attribute of code objects is    |
|                                                    | deprecated, and may be removed in Python 3.15.     |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_stacksize                            | The required stack size of the code object         |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_flags                                | An "integer" encoding a number of flags for the    |
|                                                    | interpreter.                                       |
+----------------------------------------------------+----------------------------------------------------+

The following flag bits are defined for "co_flags": bit "0x04" is set
if the function uses the "*arguments" syntax to accept an arbitrary
number of positional arguments; bit "0x08" is set if the function uses
the "**keywords" syntax to accept arbitrary keyword arguments; bit
"0x20" is set if the function is a generator. See Code Objects Bit
Flags for details on the semantics of each flags that might be
present.

Future feature declarations ("from __future__ import division") also
use bits in "co_flags" to indicate whether a code object was compiled
with a particular feature enabled: bit "0x2000" is set if the function
was compiled with future division enabled; bits "0x10" and "0x1000"
were used in earlier versions of Python.

Other bits in "co_flags" are reserved for internal use.

If a code object represents a function, the first item in "co_consts"
is the documentation string of the function, or "None" if undefined.


Methods on code objects
~~~~~~~~~~~~~~~~~~~~~~~

codeobject.co_positions()

   Returns an iterable over the source code positions of each
   *bytecode* instruction in the code object.

   The iterator returns "tuple"s containing the "(start_line,
   end_line, start_column, end_column)". The *i-th* tuple corresponds
   to the position of the source code that compiled to the *i-th* code
   unit. Column information is 0-indexed utf-8 byte offsets on the
   given source line.

   This positional information can be missing. A non-exhaustive lists
   of cases where this may happen:

   * Running the interpreter with "-X" "no_debug_ranges".

   * Loading a pyc file compiled while using "-X" "no_debug_ranges".

   * Position tuples corresponding to artificial instructions.

   * Line and column numbers that can’t be represented due to
     implementation specific limitations.

   When this occurs, some or all of the tuple elements can be "None".

   Added in version 3.11.

   Note:

     This feature requires storing column positions in code objects
     which may result in a small increase of disk usage of compiled
     Python files or interpreter memory usage. To avoid storing the
     extra information and/or deactivate printing the extra traceback
     information, the "-X" "no_debug_ranges" command line flag or the
     "PYTHONNODEBUGRANGES" environment variable can be used.

codeobject.co_lines()

   Returns an iterator that yields information about successive ranges
   of *bytecode*s. Each item yielded is a "(start, end, lineno)"
   "tuple":

   * "start" (an "int") represents the offset (inclusive) of the start
     of the *bytecode* range

   * "end" (an "int") represents the offset (exclusive) of the end of
     the *bytecode* range

   * "lineno" is an "int" representing the line number of the
     *bytecode* range, or "None" if the bytecodes in the given range
     have no line number

   The items yielded will have the following properties:

   * The first range yielded will have a "start" of 0.

   * The "(start, end)" ranges will be non-decreasing and consecutive.
     That is, for any pair of "tuple"s, the "start" of the second will
     be equal to the "end" of the first.

   * No range will be backwards: "end >= start" for all triples.

   * The last "tuple" yielded will have "end" equal to the size of the
     *bytecode*.

   Zero-width ranges, where "start == end", are allowed. Zero-width
   ranges are used for lines that are present in the source code, but
   have been eliminated by the *bytecode* compiler.

   Added in version 3.10.

   See also:

     **PEP 626** - Precise line numbers for debugging and other tools.
        The PEP that introduced the "co_lines()" method.

codeobject.replace(**kwargs)

   Return a copy of the code object with new values for the specified
   fields.

   Added in version 3.8.


Frame objects
-------------

Frame objects represent execution frames.  They may occur in traceback
objects, and are also passed to registered trace functions.


Special read-only attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+----------------------------------------------------+----------------------------------------------------+
| frame.f_back                                       | Points to the previous stack frame (towards the    |
|                                                    | caller), or "None" if this is the bottom stack     |
|                                                    | frame                                              |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_code                                       | The code object being executed in this frame.      |
|                                                    | Accessing this attribute raises an auditing event  |
|                                                    | "object.__getattr__" with arguments "obj" and      |
|                                                    | ""f_code"".                                        |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_locals                                     | The dictionary used by the frame to look up local  |
|                                                    | variables                                          |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_globals                                    | The dictionary used by the frame to look up global |
|                                                    | variables                                          |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_builtins                                   | The dictionary used by the frame to look up built- |
|                                                    | in (intrinsic) names                               |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_lasti                                      | The “precise instruction” of the frame object      |
|                                                    | (this is an index into the *bytecode* string of    |
|                                                    | the code object)                                   |
+----------------------------------------------------+----------------------------------------------------+


Special writable attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~

+----------------------------------------------------+----------------------------------------------------+
| frame.f_trace                                      | If not "None", this is a function called for       |
|                                                    | various events during code execution (this is used |
|                                                    | by debuggers). Normally an event is triggered for  |
|                                                    | each new source line (see "f_trace_lines").        |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_trace_lines                                | Set this attribute to "False" to disable           |
|                                                    | triggering a tracing event for each source line.   |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_trace_opcodes                              | Set this attribute to "True" to allow per-opcode   |
|                                                    | events to be requested. Note that this may lead to |
|                                                    | undefined interpreter behaviour if exceptions      |
|                                                    | raised by the trace function escape to the         |
|                                                    | function being traced.                             |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_lineno                                     | The current line number of the frame – writing to  |
|                                                    | this from within a trace function jumps to the     |
|                                                    | given line (only for the bottom-most frame).  A    |
|                                                    | debugger can implement a Jump command (aka Set     |
|                                                    | Next Statement) by writing to this attribute.      |
+----------------------------------------------------+----------------------------------------------------+


Frame object methods
~~~~~~~~~~~~~~~~~~~~

Frame objects support one method:

frame.clear()

   This method clears all references to local variables held by the
   frame.  Also, if the frame belonged to a *generator*, the generator
   is finalized.  This helps break reference cycles involving frame
   objects (for example when catching an exception and storing its
   traceback for later use).

   "RuntimeError" is raised if the frame is currently executing.

   Added in version 3.4.


Traceback objects
-----------------

Traceback objects represent the stack trace of an exception. A
traceback object is implicitly created when an exception occurs, and
may also be explicitly created by calling "types.TracebackType".

Changed in version 3.7: Traceback objects can now be explicitly
instantiated from Python code.

For implicitly created tracebacks, when the search for an exception
handler unwinds the execution stack, at each unwound level a traceback
object is inserted in front of the current traceback.  When an
exception handler is entered, the stack trace is made available to the
program. (See section The try statement.) It is accessible as the
third item of the tuple returned by "sys.exc_info()", and as the
"__traceback__" attribute of the caught exception.

When the program contains no suitable handler, the stack trace is
written (nicely formatted) to the standard error stream; if the
interpreter is interactive, it is also made available to the user as
"sys.last_traceback".

For explicitly created tracebacks, it is up to the creator of the
traceback to determine how the "tb_next" attributes should be linked
to form a full stack trace.

Special read-only attributes:

+----------------------------------------------------+----------------------------------------------------+
| traceback.tb_frame                                 | Points to the execution frame of the current       |
|                                                    | level.  Accessing this attribute raises an         |
|                                                    | auditing event "object.__getattr__" with arguments |
|                                                    | "obj" and ""tb_frame"".                            |
+----------------------------------------------------+----------------------------------------------------+
| traceback.tb_lineno                                | Gives the line number where the exception occurred |
+----------------------------------------------------+----------------------------------------------------+
| traceback.tb_lasti                                 | Indicates the “precise instruction”.               |
+----------------------------------------------------+----------------------------------------------------+

The line number and last instruction in the traceback may differ from
the line number of its frame object if the exception occurred in a
"try" statement with no matching except clause or with a "finally"
clause.

traceback.tb_next

   The special writable attribute "tb_next" is the next level in the
   stack trace (towards the frame where the exception occurred), or
   "None" if there is no next level.

   Changed in version 3.7: This attribute is now writable


Slice objects
-------------

Slice objects are used to represent slices for "__getitem__()"
methods.  They are also created by the built-in "slice()" function.

Special read-only attributes: "start" is the lower bound; "stop" is
the upper bound; "step" is the step value; each is "None" if omitted.
These attributes can have any type.

Slice objects support one method:

slice.indices(self, length)

   This method takes a single integer argument *length* and computes
   information about the slice that the slice object would describe if
   applied to a sequence of *length* items.  It returns a tuple of
   three integers; respectively these are the *start* and *stop*
   indices and the *step* or stride length of the slice. Missing or
   out-of-bounds indices are handled in a manner consistent with
   regular slices.


Static method objects
---------------------

Static method objects provide a way of defeating the transformation of
function objects to method objects described above. A static method
object is a wrapper around any other object, usually a user-defined
method object. When a static method object is retrieved from a class
or a class instance, the object actually returned is the wrapped
object, which is not subject to any further transformation. Static
method objects are also callable. Static method objects are created by
the built-in "staticmethod()" constructor.


Class method objects
--------------------

A class method object, like a static method object, is a wrapper
around another object that alters the way in which that object is
retrieved from classes and class instances. The behaviour of class
method objects upon such retrieval is described above, under “instance
methods”. Class method objects are created by the built-in
"classmethod()" constructor.
''',
    'typesfunctions': r'''Functions
*********

Function objects are created by function definitions.  The only
operation on a function object is to call it: "func(argument-list)".

There are really two flavors of function objects: built-in functions
and user-defined functions.  Both support the same operation (to call
the function), but the implementation is different, hence the
different object types.

See Function definitions for more information.
''',
    'typesmapping': r'''Mapping Types — "dict"
**********************

A *mapping* object maps *hashable* values to arbitrary objects.
Mappings are mutable objects.  There is currently only one standard
mapping type, the *dictionary*.  (For other containers see the built-
in "list", "set", and "tuple" classes, and the "collections" module.)

A dictionary’s keys are *almost* arbitrary values.  Values that are
not *hashable*, that is, values containing lists, dictionaries or
other mutable types (that are compared by value rather than by object
identity) may not be used as keys. Values that compare equal (such as
"1", "1.0", and "True") can be used interchangeably to index the same
dictionary entry.

class dict(**kwargs)
class dict(mapping, **kwargs)
class dict(iterable, **kwargs)

   Return a new dictionary initialized from an optional positional
   argument and a possibly empty set of keyword arguments.

   Dictionaries can be created by several means:

   * Use a comma-separated list of "key: value" pairs within braces:
     "{'jack': 4098, 'sjoerd': 4127}" or "{4098: 'jack', 4127:
     'sjoerd'}"

   * Use a dict comprehension: "{}", "{x: x ** 2 for x in range(10)}"

   * Use the type constructor: "dict()", "dict([('foo', 100), ('bar',
     200)])", "dict(foo=100, bar=200)"

   If no positional argument is given, an empty dictionary is created.
   If a positional argument is given and it defines a "keys()" method,
   a dictionary is created by calling "__getitem__()" on the argument
   with each returned key from the method.  Otherwise, the positional
   argument must be an *iterable* object.  Each item in the iterable
   must itself be an iterable with exactly two elements.  The first
   element of each item becomes a key in the new dictionary, and the
   second element the corresponding value.  If a key occurs more than
   once, the last value for that key becomes the corresponding value
   in the new dictionary.

   If keyword arguments are given, the keyword arguments and their
   values are added to the dictionary created from the positional
   argument.  If a key being added is already present, the value from
   the keyword argument replaces the value from the positional
   argument.

   To illustrate, the following examples all return a dictionary equal
   to "{"one": 1, "two": 2, "three": 3}":

      >>> a = dict(one=1, two=2, three=3)
      >>> b = {'one': 1, 'two': 2, 'three': 3}
      >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
      >>> d = dict([('two', 2), ('one', 1), ('three', 3)])
      >>> e = dict({'three': 3, 'one': 1, 'two': 2})
      >>> f = dict({'one': 1, 'three': 3}, two=2)
      >>> a == b == c == d == e == f
      True

   Providing keyword arguments as in the first example only works for
   keys that are valid Python identifiers.  Otherwise, any valid keys
   can be used.

   These are the operations that dictionaries support (and therefore,
   custom mapping types should support too):

   list(d)

      Return a list of all the keys used in the dictionary *d*.

   len(d)

      Return the number of items in the dictionary *d*.

   d[key]

      Return the item of *d* with key *key*.  Raises a "KeyError" if
      *key* is not in the map.

      If a subclass of dict defines a method "__missing__()" and *key*
      is not present, the "d[key]" operation calls that method with
      the key *key* as argument.  The "d[key]" operation then returns
      or raises whatever is returned or raised by the
      "__missing__(key)" call. No other operations or methods invoke
      "__missing__()". If "__missing__()" is not defined, "KeyError"
      is raised. "__missing__()" must be a method; it cannot be an
      instance variable:

         >>> class Counter(dict):
         ...     def __missing__(self, key):
         ...         return 0
         ...
         >>> c = Counter()
         >>> c['red']
         0
         >>> c['red'] += 1
         >>> c['red']
         1

      The example above shows part of the implementation of
      "collections.Counter".  A different "__missing__" method is used
      by "collections.defaultdict".

   d[key] = value

      Set "d[key]" to *value*.

   del d[key]

      Remove "d[key]" from *d*.  Raises a "KeyError" if *key* is not
      in the map.

   key in d

      Return "True" if *d* has a key *key*, else "False".

   key not in d

      Equivalent to "not key in d".

   iter(d)

      Return an iterator over the keys of the dictionary.  This is a
      shortcut for "iter(d.keys())".

   clear()

      Remove all items from the dictionary.

   copy()

      Return a shallow copy of the dictionary.

   classmethod fromkeys(iterable, value=None, /)

      Create a new dictionary with keys from *iterable* and values set
      to *value*.

      "fromkeys()" is a class method that returns a new dictionary.
      *value* defaults to "None".  All of the values refer to just a
      single instance, so it generally doesn’t make sense for *value*
      to be a mutable object such as an empty list.  To get distinct
      values, use a dict comprehension instead.

   get(key, default=None, /)

      Return the value for *key* if *key* is in the dictionary, else
      *default*. If *default* is not given, it defaults to "None", so
      that this method never raises a "KeyError".

   items()

      Return a new view of the dictionary’s items ("(key, value)"
      pairs). See the documentation of view objects.

   keys()

      Return a new view of the dictionary’s keys.  See the
      documentation of view objects.

   pop(key[, default])

      If *key* is in the dictionary, remove it and return its value,
      else return *default*.  If *default* is not given and *key* is
      not in the dictionary, a "KeyError" is raised.

   popitem()

      Remove and return a "(key, value)" pair from the dictionary.
      Pairs are returned in LIFO (last-in, first-out) order.

      "popitem()" is useful to destructively iterate over a
      dictionary, as often used in set algorithms.  If the dictionary
      is empty, calling "popitem()" raises a "KeyError".

      Changed in version 3.7: LIFO order is now guaranteed. In prior
      versions, "popitem()" would return an arbitrary key/value pair.

   reversed(d)

      Return a reverse iterator over the keys of the dictionary. This
      is a shortcut for "reversed(d.keys())".

      Added in version 3.8.

   setdefault(key, default=None, /)

      If *key* is in the dictionary, return its value.  If not, insert
      *key* with a value of *default* and return *default*.  *default*
      defaults to "None".

   update([other])

      Update the dictionary with the key/value pairs from *other*,
      overwriting existing keys.  Return "None".

      "update()" accepts either another object with a "keys()" method
      (in which case "__getitem__()" is called with every key returned
      from the method) or an iterable of key/value pairs (as tuples or
      other iterables of length two). If keyword arguments are
      specified, the dictionary is then updated with those key/value
      pairs: "d.update(red=1, blue=2)".

   values()

      Return a new view of the dictionary’s values.  See the
      documentation of view objects.

      An equality comparison between one "dict.values()" view and
      another will always return "False". This also applies when
      comparing "dict.values()" to itself:

         >>> d = {'a': 1}
         >>> d.values() == d.values()
         False

   d | other

      Create a new dictionary with the merged keys and values of *d*
      and *other*, which must both be dictionaries. The values of
      *other* take priority when *d* and *other* share keys.

      Added in version 3.9.

   d |= other

      Update the dictionary *d* with keys and values from *other*,
      which may be either a *mapping* or an *iterable* of key/value
      pairs. The values of *other* take priority when *d* and *other*
      share keys.

      Added in version 3.9.

   Dictionaries compare equal if and only if they have the same "(key,
   value)" pairs (regardless of ordering). Order comparisons (‘<’,
   ‘<=’, ‘>=’, ‘>’) raise "TypeError".

   Dictionaries preserve insertion order.  Note that updating a key
   does not affect the order.  Keys added after deletion are inserted
   at the end.

      >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
      >>> d
      {'one': 1, 'two': 2, 'three': 3, 'four': 4}
      >>> list(d)
      ['one', 'two', 'three', 'four']
      >>> list(d.values())
      [1, 2, 3, 4]
      >>> d["one"] = 42
      >>> d
      {'one': 42, 'two': 2, 'three': 3, 'four': 4}
      >>> del d["two"]
      >>> d["two"] = None
      >>> d
      {'one': 42, 'three': 3, 'four': 4, 'two': None}

   Changed in version 3.7: Dictionary order is guaranteed to be
   insertion order.  This behavior was an implementation detail of
   CPython from 3.6.

   Dictionaries and dictionary views are reversible.

      >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
      >>> d
      {'one': 1, 'two': 2, 'three': 3, 'four': 4}
      >>> list(reversed(d))
      ['four', 'three', 'two', 'one']
      >>> list(reversed(d.values()))
      [4, 3, 2, 1]
      >>> list(reversed(d.items()))
      [('four', 4), ('three', 3), ('two', 2), ('one', 1)]

   Changed in version 3.8: Dictionaries are now reversible.

See also:

  "types.MappingProxyType" can be used to create a read-only view of a
  "dict".


Dictionary view objects
=======================

The objects returned by "dict.keys()", "dict.values()" and
"dict.items()" are *view objects*.  They provide a dynamic view on the
dictionary’s entries, which means that when the dictionary changes,
the view reflects these changes.

Dictionary views can be iterated over to yield their respective data,
and support membership tests:

len(dictview)

   Return the number of entries in the dictionary.

iter(dictview)

   Return an iterator over the keys, values or items (represented as
   tuples of "(key, value)") in the dictionary.

   Keys and values are iterated over in insertion order. This allows
   the creation of "(value, key)" pairs using "zip()": "pairs =
   zip(d.values(), d.keys())".  Another way to create the same list is
   "pairs = [(v, k) for (k, v) in d.items()]".

   Iterating views while adding or deleting entries in the dictionary
   may raise a "RuntimeError" or fail to iterate over all entries.

   Changed in version 3.7: Dictionary order is guaranteed to be
   insertion order.

x in dictview

   Return "True" if *x* is in the underlying dictionary’s keys, values
   or items (in the latter case, *x* should be a "(key, value)"
   tuple).

reversed(dictview)

   Return a reverse iterator over the keys, values or items of the
   dictionary. The view will be iterated in reverse order of the
   insertion.

   Changed in version 3.8: Dictionary views are now reversible.

dictview.mapping

   Return a "types.MappingProxyType" that wraps the original
   dictionary to which the view refers.

   Added in version 3.10.

Keys views are set-like since their entries are unique and *hashable*.
Items views also have set-like operations since the (key, value) pairs
are unique and the keys are hashable. If all values in an items view
are hashable as well, then the items view can interoperate with other
sets. (Values views are not treated as set-like since the entries are
generally not unique.)  For set-like views, all of the operations
defined for the abstract base class "collections.abc.Set" are
available (for example, "==", "<", or "^").  While using set
operators, set-like views accept any iterable as the other operand,
unlike sets which only accept sets as the input.

An example of dictionary view usage:

   >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
   >>> keys = dishes.keys()
   >>> values = dishes.values()

   >>> # iteration
   >>> n = 0
   >>> for val in values:
   ...     n += val
   ...
   >>> print(n)
   504

   >>> # keys and values are iterated over in the same order (insertion order)
   >>> list(keys)
   ['eggs', 'sausage', 'bacon', 'spam']
   >>> list(values)
   [2, 1, 1, 500]

   >>> # view objects are dynamic and reflect dict changes
   >>> del dishes['eggs']
   >>> del dishes['sausage']
   >>> list(keys)
   ['bacon', 'spam']

   >>> # set operations
   >>> keys & {'eggs', 'bacon', 'salad'}
   {'bacon'}
   >>> keys ^ {'sausage', 'juice'} == {'juice', 'sausage', 'bacon', 'spam'}
   True
   >>> keys | ['juice', 'juice', 'juice'] == {'bacon', 'spam', 'juice'}
   True

   >>> # get back a read-only proxy for the original dictionary
   >>> values.mapping
   mappingproxy({'bacon': 1, 'spam': 500})
   >>> values.mapping['spam']
   500
''',
    'typesmethods': r'''Methods
*******

Methods are functions that are called using the attribute notation.
There are two flavors: built-in methods (such as "append()" on lists)
and class instance method. Built-in methods are described with the
types that support them.

If you access a method (a function defined in a class namespace)
through an instance, you get a special object: a *bound method* (also
called instance method) object. When called, it will add the "self"
argument to the argument list.  Bound methods have two special read-
only attributes: "m.__self__" is the object on which the method
operates, and "m.__func__" is the function implementing the method.
Calling "m(arg-1, arg-2, ..., arg-n)" is completely equivalent to
calling "m.__func__(m.__self__, arg-1, arg-2, ..., arg-n)".

Like function objects, bound method objects support getting arbitrary
attributes.  However, since method attributes are actually stored on
the underlying function object ("method.__func__"), setting method
attributes on bound methods is disallowed.  Attempting to set an
attribute on a method results in an "AttributeError" being raised.  In
order to set a method attribute, you need to explicitly set it on the
underlying function object:

   >>> class C:
   ...     def method(self):
   ...         pass
   ...
   >>> c = C()
   >>> c.method.whoami = 'my name is method'  # can't set on the method
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   AttributeError: 'method' object has no attribute 'whoami'
   >>> c.method.__func__.whoami = 'my name is method'
   >>> c.method.whoami
   'my name is method'

See Instance methods for more information.
''',
    'typesmodules': r'''Modules
*******

The only special operation on a module is attribute access: "m.name",
where *m* is a module and *name* accesses a name defined in *m*’s
symbol table. Module attributes can be assigned to.  (Note that the
"import" statement is not, strictly speaking, an operation on a module
object; "import foo" does not require a module object named *foo* to
exist, rather it requires an (external) *definition* for a module
named *foo* somewhere.)

A special attribute of every module is "__dict__". This is the
dictionary containing the module’s symbol table. Modifying this
dictionary will actually change the module’s symbol table, but direct
assignment to the "__dict__" attribute is not possible (you can write
"m.__dict__['a'] = 1", which defines "m.a" to be "1", but you can’t
write "m.__dict__ = {}").  Modifying "__dict__" directly is not
recommended.

Modules built into the interpreter are written like this: "<module
'sys' (built-in)>".  If loaded from a file, they are written as
"<module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>".
''',
    'typesseq': r'''Sequence Types — "list", "tuple", "range"
*****************************************

There are three basic sequence types: lists, tuples, and range
objects. Additional sequence types tailored for processing of binary
data and text strings are described in dedicated sections.


Common Sequence Operations
==========================

The operations in the following table are supported by most sequence
types, both mutable and immutable. The "collections.abc.Sequence" ABC
is provided to make it easier to correctly implement these operations
on custom sequence types.

This table lists the sequence operations sorted in ascending priority.
In the table, *s* and *t* are sequences of the same type, *n*, *i*,
*j* and *k* are integers and *x* is an arbitrary object that meets any
type and value restrictions imposed by *s*.

The "in" and "not in" operations have the same priorities as the
comparison operations. The "+" (concatenation) and "*" (repetition)
operations have the same priority as the corresponding numeric
operations. [3]

+----------------------------+----------------------------------+------------+
| Operation                  | Result                           | Notes      |
|============================|==================================|============|
| "x in s"                   | "True" if an item of *s* is      | (1)        |
|                            | equal to *x*, else "False"       |            |
+----------------------------+----------------------------------+------------+
| "x not in s"               | "False" if an item of *s* is     | (1)        |
|                            | equal to *x*, else "True"        |            |
+----------------------------+----------------------------------+------------+
| "s + t"                    | the concatenation of *s* and *t* | (6)(7)     |
+----------------------------+----------------------------------+------------+
| "s * n" or "n * s"         | equivalent to adding *s* to      | (2)(7)     |
|                            | itself *n* times                 |            |
+----------------------------+----------------------------------+------------+
| "s[i]"                     | *i*th item of *s*, origin 0      | (3)        |
+----------------------------+----------------------------------+------------+
| "s[i:j]"                   | slice of *s* from *i* to *j*     | (3)(4)     |
+----------------------------+----------------------------------+------------+
| "s[i:j:k]"                 | slice of *s* from *i* to *j*     | (3)(5)     |
|                            | with step *k*                    |            |
+----------------------------+----------------------------------+------------+
| "len(s)"                   | length of *s*                    |            |
+----------------------------+----------------------------------+------------+
| "min(s)"                   | smallest item of *s*             |            |
+----------------------------+----------------------------------+------------+
| "max(s)"                   | largest item of *s*              |            |
+----------------------------+----------------------------------+------------+
| "s.index(x[, i[, j]])"     | index of the first occurrence of | (8)        |
|                            | *x* in *s* (at or after index    |            |
|                            | *i* and before index *j*)        |            |
+----------------------------+----------------------------------+------------+
| "s.count(x)"               | total number of occurrences of   |            |
|                            | *x* in *s*                       |            |
+----------------------------+----------------------------------+------------+

Sequences of the same type also support comparisons.  In particular,
tuples and lists are compared lexicographically by comparing
corresponding elements. This means that to compare equal, every
element must compare equal and the two sequences must be of the same
type and have the same length.  (For full details see Comparisons in
the language reference.)

Forward and reversed iterators over mutable sequences access values
using an index.  That index will continue to march forward (or
backward) even if the underlying sequence is mutated.  The iterator
terminates only when an "IndexError" or a "StopIteration" is
encountered (or when the index drops below zero).

Notes:

1. While the "in" and "not in" operations are used only for simple
   containment testing in the general case, some specialised sequences
   (such as "str", "bytes" and "bytearray") also use them for
   subsequence testing:

      >>> "gg" in "eggs"
      True

2. Values of *n* less than "0" are treated as "0" (which yields an
   empty sequence of the same type as *s*).  Note that items in the
   sequence *s* are not copied; they are referenced multiple times.
   This often haunts new Python programmers; consider:

      >>> lists = [[]] * 3
      >>> lists
      [[], [], []]
      >>> lists[0].append(3)
      >>> lists
      [[3], [3], [3]]

   What has happened is that "[[]]" is a one-element list containing
   an empty list, so all three elements of "[[]] * 3" are references
   to this single empty list.  Modifying any of the elements of
   "lists" modifies this single list. You can create a list of
   different lists this way:

      >>> lists = [[] for i in range(3)]
      >>> lists[0].append(3)
      >>> lists[1].append(5)
      >>> lists[2].append(7)
      >>> lists
      [[3], [5], [7]]

   Further explanation is available in the FAQ entry How do I create a
   multidimensional list?.

3. If *i* or *j* is negative, the index is relative to the end of
   sequence *s*: "len(s) + i" or "len(s) + j" is substituted.  But
   note that "-0" is still "0".

4. The slice of *s* from *i* to *j* is defined as the sequence of
   items with index *k* such that "i <= k < j".  If *i* or *j* is
   greater than "len(s)", use "len(s)".  If *i* is omitted or "None",
   use "0".  If *j* is omitted or "None", use "len(s)".  If *i* is
   greater than or equal to *j*, the slice is empty.

5. The slice of *s* from *i* to *j* with step *k* is defined as the
   sequence of items with index  "x = i + n*k" such that "0 <= n <
   (j-i)/k".  In other words, the indices are "i", "i+k", "i+2*k",
   "i+3*k" and so on, stopping when *j* is reached (but never
   including *j*).  When *k* is positive, *i* and *j* are reduced to
   "len(s)" if they are greater. When *k* is negative, *i* and *j* are
   reduced to "len(s) - 1" if they are greater.  If *i* or *j* are
   omitted or "None", they become “end” values (which end depends on
   the sign of *k*).  Note, *k* cannot be zero. If *k* is "None", it
   is treated like "1".

6. Concatenating immutable sequences always results in a new object.
   This means that building up a sequence by repeated concatenation
   will have a quadratic runtime cost in the total sequence length.
   To get a linear runtime cost, you must switch to one of the
   alternatives below:

   * if concatenating "str" objects, you can build a list and use
     "str.join()" at the end or else write to an "io.StringIO"
     instance and retrieve its value when complete

   * if concatenating "bytes" objects, you can similarly use
     "bytes.join()" or "io.BytesIO", or you can do in-place
     concatenation with a "bytearray" object.  "bytearray" objects are
     mutable and have an efficient overallocation mechanism

   * if concatenating "tuple" objects, extend a "list" instead

   * for other types, investigate the relevant class documentation

7. Some sequence types (such as "range") only support item sequences
   that follow specific patterns, and hence don’t support sequence
   concatenation or repetition.

8. "index" raises "ValueError" when *x* is not found in *s*. Not all
   implementations support passing the additional arguments *i* and
   *j*. These arguments allow efficient searching of subsections of
   the sequence. Passing the extra arguments is roughly equivalent to
   using "s[i:j].index(x)", only without copying any data and with the
   returned index being relative to the start of the sequence rather
   than the start of the slice.


Immutable Sequence Types
========================

The only operation that immutable sequence types generally implement
that is not also implemented by mutable sequence types is support for
the "hash()" built-in.

This support allows immutable sequences, such as "tuple" instances, to
be used as "dict" keys and stored in "set" and "frozenset" instances.

Attempting to hash an immutable sequence that contains unhashable
values will result in "TypeError".


Mutable Sequence Types
======================

The operations in the following table are defined on mutable sequence
types. The "collections.abc.MutableSequence" ABC is provided to make
it easier to correctly implement these operations on custom sequence
types.

In the table *s* is an instance of a mutable sequence type, *t* is any
iterable object and *x* is an arbitrary object that meets any type and
value restrictions imposed by *s* (for example, "bytearray" only
accepts integers that meet the value restriction "0 <= x <= 255").

+--------------------------------+----------------------------------+-----------------------+
| Operation                      | Result                           | Notes                 |
|================================|==================================|=======================|
| "s[i] = x"                     | item *i* of *s* is replaced by   |                       |
|                                | *x*                              |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s[i:j] = t"                   | slice of *s* from *i* to *j* is  |                       |
|                                | replaced by the contents of the  |                       |
|                                | iterable *t*                     |                       |
+--------------------------------+----------------------------------+-----------------------+
| "del s[i:j]"                   | same as "s[i:j] = []"            |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s[i:j:k] = t"                 | the elements of "s[i:j:k]" are   | (1)                   |
|                                | replaced by those of *t*         |                       |
+--------------------------------+----------------------------------+-----------------------+
| "del s[i:j:k]"                 | removes the elements of          |                       |
|                                | "s[i:j:k]" from the list         |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.append(x)"                  | appends *x* to the end of the    |                       |
|                                | sequence (same as                |                       |
|                                | "s[len(s):len(s)] = [x]")        |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.clear()"                    | removes all items from *s* (same | (5)                   |
|                                | as "del s[:]")                   |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.copy()"                     | creates a shallow copy of *s*    | (5)                   |
|                                | (same as "s[:]")                 |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.extend(t)" or "s += t"      | extends *s* with the contents of |                       |
|                                | *t* (for the most part the same  |                       |
|                                | as "s[len(s):len(s)] = t")       |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s *= n"                       | updates *s* with its contents    | (6)                   |
|                                | repeated *n* times               |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.insert(i, x)"               | inserts *x* into *s* at the      |                       |
|                                | index given by *i* (same as      |                       |
|                                | "s[i:i] = [x]")                  |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.pop()" or "s.pop(i)"        | retrieves the item at *i* and    | (2)                   |
|                                | also removes it from *s*         |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.remove(x)"                  | removes the first item from *s*  | (3)                   |
|                                | where "s[i]" is equal to *x*     |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.reverse()"                  | reverses the items of *s* in     | (4)                   |
|                                | place                            |                       |
+--------------------------------+----------------------------------+-----------------------+

Notes:

1. If *k* is not equal to "1", *t* must have the same length as the
   slice it is replacing.

2. The optional argument *i* defaults to "-1", so that by default the
   last item is removed and returned.

3. "remove()" raises "ValueError" when *x* is not found in *s*.

4. The "reverse()" method modifies the sequence in place for economy
   of space when reversing a large sequence.  To remind users that it
   operates by side effect, it does not return the reversed sequence.

5. "clear()" and "copy()" are included for consistency with the
   interfaces of mutable containers that don’t support slicing
   operations (such as "dict" and "set"). "copy()" is not part of the
   "collections.abc.MutableSequence" ABC, but most concrete mutable
   sequence classes provide it.

   Added in version 3.3: "clear()" and "copy()" methods.

6. The value *n* is an integer, or an object implementing
   "__index__()".  Zero and negative values of *n* clear the sequence.
   Items in the sequence are not copied; they are referenced multiple
   times, as explained for "s * n" under Common Sequence Operations.


Lists
=====

Lists are mutable sequences, typically used to store collections of
homogeneous items (where the precise degree of similarity will vary by
application).

class list([iterable])

   Lists may be constructed in several ways:

   * Using a pair of square brackets to denote the empty list: "[]"

   * Using square brackets, separating items with commas: "[a]", "[a,
     b, c]"

   * Using a list comprehension: "[x for x in iterable]"

   * Using the type constructor: "list()" or "list(iterable)"

   The constructor builds a list whose items are the same and in the
   same order as *iterable*’s items.  *iterable* may be either a
   sequence, a container that supports iteration, or an iterator
   object.  If *iterable* is already a list, a copy is made and
   returned, similar to "iterable[:]". For example, "list('abc')"
   returns "['a', 'b', 'c']" and "list( (1, 2, 3) )" returns "[1, 2,
   3]". If no argument is given, the constructor creates a new empty
   list, "[]".

   Many other operations also produce lists, including the "sorted()"
   built-in.

   Lists implement all of the common and mutable sequence operations.
   Lists also provide the following additional method:

   sort(*, key=None, reverse=False)

      This method sorts the list in place, using only "<" comparisons
      between items. Exceptions are not suppressed - if any comparison
      operations fail, the entire sort operation will fail (and the
      list will likely be left in a partially modified state).

      "sort()" accepts two arguments that can only be passed by
      keyword (keyword-only arguments):

      *key* specifies a function of one argument that is used to
      extract a comparison key from each list element (for example,
      "key=str.lower"). The key corresponding to each item in the list
      is calculated once and then used for the entire sorting process.
      The default value of "None" means that list items are sorted
      directly without calculating a separate key value.

      The "functools.cmp_to_key()" utility is available to convert a
      2.x style *cmp* function to a *key* function.

      *reverse* is a boolean value.  If set to "True", then the list
      elements are sorted as if each comparison were reversed.

      This method modifies the sequence in place for economy of space
      when sorting a large sequence.  To remind users that it operates
      by side effect, it does not return the sorted sequence (use
      "sorted()" to explicitly request a new sorted list instance).

      The "sort()" method is guaranteed to be stable.  A sort is
      stable if it guarantees not to change the relative order of
      elements that compare equal — this is helpful for sorting in
      multiple passes (for example, sort by department, then by salary
      grade).

      For sorting examples and a brief sorting tutorial, see Sorting
      Techniques.

      **CPython implementation detail:** While a list is being sorted,
      the effect of attempting to mutate, or even inspect, the list is
      undefined.  The C implementation of Python makes the list appear
      empty for the duration, and raises "ValueError" if it can detect
      that the list has been mutated during a sort.


Tuples
======

Tuples are immutable sequences, typically used to store collections of
heterogeneous data (such as the 2-tuples produced by the "enumerate()"
built-in). Tuples are also used for cases where an immutable sequence
of homogeneous data is needed (such as allowing storage in a "set" or
"dict" instance).

class tuple([iterable])

   Tuples may be constructed in a number of ways:

   * Using a pair of parentheses to denote the empty tuple: "()"

   * Using a trailing comma for a singleton tuple: "a," or "(a,)"

   * Separating items with commas: "a, b, c" or "(a, b, c)"

   * Using the "tuple()" built-in: "tuple()" or "tuple(iterable)"

   The constructor builds a tuple whose items are the same and in the
   same order as *iterable*’s items.  *iterable* may be either a
   sequence, a container that supports iteration, or an iterator
   object.  If *iterable* is already a tuple, it is returned
   unchanged. For example, "tuple('abc')" returns "('a', 'b', 'c')"
   and "tuple( [1, 2, 3] )" returns "(1, 2, 3)". If no argument is
   given, the constructor creates a new empty tuple, "()".

   Note that it is actually the comma which makes a tuple, not the
   parentheses. The parentheses are optional, except in the empty
   tuple case, or when they are needed to avoid syntactic ambiguity.
   For example, "f(a, b, c)" is a function call with three arguments,
   while "f((a, b, c))" is a function call with a 3-tuple as the sole
   argument.

   Tuples implement all of the common sequence operations.

For heterogeneous collections of data where access by name is clearer
than access by index, "collections.namedtuple()" may be a more
appropriate choice than a simple tuple object.


Ranges
======

The "range" type represents an immutable sequence of numbers and is
commonly used for looping a specific number of times in "for" loops.

class range(stop)
class range(start, stop[, step])

   The arguments to the range constructor must be integers (either
   built-in "int" or any object that implements the "__index__()"
   special method).  If the *step* argument is omitted, it defaults to
   "1". If the *start* argument is omitted, it defaults to "0". If
   *step* is zero, "ValueError" is raised.

   For a positive *step*, the contents of a range "r" are determined
   by the formula "r[i] = start + step*i" where "i >= 0" and "r[i] <
   stop".

   For a negative *step*, the contents of the range are still
   determined by the formula "r[i] = start + step*i", but the
   constraints are "i >= 0" and "r[i] > stop".

   A range object will be empty if "r[0]" does not meet the value
   constraint. Ranges do support negative indices, but these are
   interpreted as indexing from the end of the sequence determined by
   the positive indices.

   Ranges containing absolute values larger than "sys.maxsize" are
   permitted but some features (such as "len()") may raise
   "OverflowError".

   Range examples:

      >>> list(range(10))
      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
      >>> list(range(1, 11))
      [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
      >>> list(range(0, 30, 5))
      [0, 5, 10, 15, 20, 25]
      >>> list(range(0, 10, 3))
      [0, 3, 6, 9]
      >>> list(range(0, -10, -1))
      [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
      >>> list(range(0))
      []
      >>> list(range(1, 0))
      []

   Ranges implement all of the common sequence operations except
   concatenation and repetition (due to the fact that range objects
   can only represent sequences that follow a strict pattern and
   repetition and concatenation will usually violate that pattern).

   start

      The value of the *start* parameter (or "0" if the parameter was
      not supplied)

   stop

      The value of the *stop* parameter

   step

      The value of the *step* parameter (or "1" if the parameter was
      not supplied)

The advantage of the "range" type over a regular "list" or "tuple" is
that a "range" object will always take the same (small) amount of
memory, no matter the size of the range it represents (as it only
stores the "start", "stop" and "step" values, calculating individual
items and subranges as needed).

Range objects implement the "collections.abc.Sequence" ABC, and
provide features such as containment tests, element index lookup,
slicing and support for negative indices (see Sequence Types — list,
tuple, range):

>>> r = range(0, 20, 2)
>>> r
range(0, 20, 2)
>>> 11 in r
False
>>> 10 in r
True
>>> r.index(10)
5
>>> r[5]
10
>>> r[:5]
range(0, 10, 2)
>>> r[-1]
18

Testing range objects for equality with "==" and "!=" compares them as
sequences.  That is, two range objects are considered equal if they
represent the same sequence of values.  (Note that two range objects
that compare equal might have different "start", "stop" and "step"
attributes, for example "range(0) == range(2, 1, 3)" or "range(0, 3,
2) == range(0, 4, 2)".)

Changed in version 3.2: Implement the Sequence ABC. Support slicing
and negative indices. Test "int" objects for membership in constant
time instead of iterating through all items.

Changed in version 3.3: Define ‘==’ and ‘!=’ to compare range objects
based on the sequence of values they define (instead of comparing
based on object identity).Added the "start", "stop" and "step"
attributes.

See also:

  * The linspace recipe shows how to implement a lazy version of range
    suitable for floating-point applications.
''',
    'typesseq-mutable': r'''Mutable Sequence Types
**********************

The operations in the following table are defined on mutable sequence
types. The "collections.abc.MutableSequence" ABC is provided to make
it easier to correctly implement these operations on custom sequence
types.

In the table *s* is an instance of a mutable sequence type, *t* is any
iterable object and *x* is an arbitrary object that meets any type and
value restrictions imposed by *s* (for example, "bytearray" only
accepts integers that meet the value restriction "0 <= x <= 255").

+--------------------------------+----------------------------------+-----------------------+
| Operation                      | Result                           | Notes                 |
|================================|==================================|=======================|
| "s[i] = x"                     | item *i* of *s* is replaced by   |                       |
|                                | *x*                              |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s[i:j] = t"                   | slice of *s* from *i* to *j* is  |                       |
|                                | replaced by the contents of the  |                       |
|                                | iterable *t*                     |                       |
+--------------------------------+----------------------------------+-----------------------+
| "del s[i:j]"                   | same as "s[i:j] = []"            |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s[i:j:k] = t"                 | the elements of "s[i:j:k]" are   | (1)                   |
|                                | replaced by those of *t*         |                       |
+--------------------------------+----------------------------------+-----------------------+
| "del s[i:j:k]"                 | removes the elements of          |                       |
|                                | "s[i:j:k]" from the list         |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.append(x)"                  | appends *x* to the end of the    |                       |
|                                | sequence (same as                |                       |
|                                | "s[len(s):len(s)] = [x]")        |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.clear()"                    | removes all items from *s* (same | (5)                   |
|                                | as "del s[:]")                   |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.copy()"                     | creates a shallow copy of *s*    | (5)                   |
|                                | (same as "s[:]")                 |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.extend(t)" or "s += t"      | extends *s* with the contents of |                       |
|                                | *t* (for the most part the same  |                       |
|                                | as "s[len(s):len(s)] = t")       |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s *= n"                       | updates *s* with its contents    | (6)                   |
|                                | repeated *n* times               |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.insert(i, x)"               | inserts *x* into *s* at the      |                       |
|                                | index given by *i* (same as      |                       |
|                                | "s[i:i] = [x]")                  |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.pop()" or "s.pop(i)"        | retrieves the item at *i* and    | (2)                   |
|                                | also removes it from *s*         |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.remove(x)"                  | removes the first item from *s*  | (3)                   |
|                                | where "s[i]" is equal to *x*     |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.reverse()"                  | reverses the items of *s* in     | (4)                   |
|                                | place                            |                       |
+--------------------------------+----------------------------------+-----------------------+

Notes:

1. If *k* is not equal to "1", *t* must have the same length as the
   slice it is replacing.

2. The optional argument *i* defaults to "-1", so that by default the
   last item is removed and returned.

3. "remove()" raises "ValueError" when *x* is not found in *s*.

4. The "reverse()" method modifies the sequence in place for economy
   of space when reversing a large sequence.  To remind users that it
   operates by side effect, it does not return the reversed sequence.

5. "clear()" and "copy()" are included for consistency with the
   interfaces of mutable containers that don’t support slicing
   operations (such as "dict" and "set"). "copy()" is not part of the
   "collections.abc.MutableSequence" ABC, but most concrete mutable
   sequence classes provide it.

   Added in version 3.3: "clear()" and "copy()" methods.

6. The value *n* is an integer, or an object implementing
   "__index__()".  Zero and negative values of *n* clear the sequence.
   Items in the sequence are not copied; they are referenced multiple
   times, as explained for "s * n" under Common Sequence Operations.
''',
    'unary': r'''Unary arithmetic and bitwise operations
***************************************

All unary arithmetic and bitwise operations have the same priority:

   u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr

The unary "-" (minus) operator yields the negation of its numeric
argument; the operation can be overridden with the "__neg__()" special
method.

The unary "+" (plus) operator yields its numeric argument unchanged;
the operation can be overridden with the "__pos__()" special method.

The unary "~" (invert) operator yields the bitwise inversion of its
integer argument.  The bitwise inversion of "x" is defined as
"-(x+1)".  It only applies to integral numbers or to custom objects
that override the "__invert__()" special method.

In all three cases, if the argument does not have the proper type, a
"TypeError" exception is raised.
''',
    'while': r'''The "while" statement
*********************

The "while" statement is used for repeated execution as long as an
expression is true:

   while_stmt ::= "while" assignment_expression ":" suite
                  ["else" ":" suite]

This repeatedly tests the expression and, if it is true, executes the
first suite; if the expression is false (which may be the first time
it is tested) the suite of the "else" clause, if present, is executed
and the loop terminates.

A "break" statement executed in the first suite terminates the loop
without executing the "else" clause’s suite.  A "continue" statement
executed in the first suite skips the rest of the suite and goes back
to testing the expression.
''',
    'with': r'''The "with" statement
********************

The "with" statement is used to wrap the execution of a block with
methods defined by a context manager (see section With Statement
Context Managers). This allows common "try"…"except"…"finally" usage
patterns to be encapsulated for convenient reuse.

   with_stmt          ::= "with" ( "(" with_stmt_contents ","? ")" | with_stmt_contents ) ":" suite
   with_stmt_contents ::= with_item ("," with_item)*
   with_item          ::= expression ["as" target]

The execution of the "with" statement with one “item” proceeds as
follows:

1. The context expression (the expression given in the "with_item") is
   evaluated to obtain a context manager.

2. The context manager’s "__enter__()" is loaded for later use.

3. The context manager’s "__exit__()" is loaded for later use.

4. The context manager’s "__enter__()" method is invoked.

5. If a target was included in the "with" statement, the return value
   from "__enter__()" is assigned to it.

   Note:

     The "with" statement guarantees that if the "__enter__()" method
     returns without an error, then "__exit__()" will always be
     called. Thus, if an error occurs during the assignment to the
     target list, it will be treated the same as an error occurring
     within the suite would be. See step 7 below.

6. The suite is executed.

7. The context manager’s "__exit__()" method is invoked.  If an
   exception caused the suite to be exited, its type, value, and
   traceback are passed as arguments to "__exit__()". Otherwise, three
   "None" arguments are supplied.

   If the suite was exited due to an exception, and the return value
   from the "__exit__()" method was false, the exception is reraised.
   If the return value was true, the exception is suppressed, and
   execution continues with the statement following the "with"
   statement.

   If the suite was exited for any reason other than an exception, the
   return value from "__exit__()" is ignored, and execution proceeds
   at the normal location for the kind of exit that was taken.

The following code:

   with EXPRESSION as TARGET:
       SUITE

is semantically equivalent to:

   manager = (EXPRESSION)
   enter = type(manager).__enter__
   exit = type(manager).__exit__
   value = enter(manager)
   hit_except = False

   try:
       TARGET = value
       SUITE
   except:
       hit_except = True
       if not exit(manager, *sys.exc_info()):
           raise
   finally:
       if not hit_except:
           exit(manager, None, None, None)

With more than one item, the context managers are processed as if
multiple "with" statements were nested:

   with A() as a, B() as b:
       SUITE

is semantically equivalent to:

   with A() as a:
       with B() as b:
           SUITE

You can also write multi-item context managers in multiple lines if
the items are surrounded by parentheses. For example:

   with (
       A() as a,
       B() as b,
   ):
       SUITE

Changed in version 3.1: Support for multiple context expressions.

Changed in version 3.10: Support for using grouping parentheses to
break the statement in multiple lines.

See also:

  **PEP 343** - The “with” statement
     The specification, background, and examples for the Python "with"
     statement.
''',
    'yield': r'''The "yield" statement
*********************

   yield_stmt ::= yield_expression

A "yield" statement is semantically equivalent to a yield expression.
The "yield" statement can be used to omit the parentheses that would
otherwise be required in the equivalent yield expression statement.
For example, the yield statements

   yield <expr>
   yield from <expr>

are equivalent to the yield expression statements

   (yield <expr>)
   (yield from <expr>)

Yield expressions and statements are only used when defining a
*generator* function, and are only used in the body of the generator
function.  Using "yield" in a function definition is sufficient to
cause that definition to create a generator function instead of a
normal function.

For full details of "yield" semantics, refer to the Yield expressions
section.
''',
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          '''A multi-producer, multi-consumer queue.'''

import threading
import types
from collections import deque
from heapq import heappush, heappop
from time import monotonic as time
try:
    from _queue import SimpleQueue
except ImportError:
    SimpleQueue = None

__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue', 'SimpleQueue']


try:
    from _queue import Empty
except ImportError:
    class Empty(Exception):
        'Exception raised by Queue.get(block=0)/get_nowait().'
        pass

class Full(Exception):
    'Exception raised by Queue.put(block=0)/put_nowait().'
    pass


class Queue:
    '''Create a queue object with a given maximum size.

    If maxsize is <= 0, the queue size is infinite.
    '''

    def __init__(self, maxsize=0):
        self.maxsize = maxsize
        self._init(maxsize)

        # mutex must be held whenever the queue is mutating.  All methods
        # that acquire mutex must release it before returning.  mutex
        # is shared between the three conditions, so acquiring and
        # releasing the conditions also acquires and releases mutex.
        self.mutex = threading.Lock()

        # Notify not_empty whenever an item is added to the queue; a
        # thread waiting to get is notified then.
        self.not_empty = threading.Condition(self.mutex)

        # Notify not_full whenever an item is removed from the queue;
        # a thread waiting to put is notified then.
        self.not_full = threading.Condition(self.mutex)

        # Notify all_tasks_done whenever the number of unfinished tasks
        # drops to zero; thread waiting to join() is notified to resume
        self.all_tasks_done = threading.Condition(self.mutex)
        self.unfinished_tasks = 0

    def task_done(self):
        '''Indicate that a formerly enqueued task is complete.

        Used by Queue consumer threads.  For each get() used to fetch a task,
        a subsequent call to task_done() tells the queue that the processing
        on the task is complete.

        If a join() is currently blocking, it will resume when all items
        have been processed (meaning that a task_done() call was received
        for every item that had been put() into the queue).

        Raises a ValueError if called more times than there were items
        placed in the queue.
        '''
        with self.all_tasks_done:
            unfinished = self.unfinished_tasks - 1
            if unfinished <= 0:
                if unfinished < 0:
                    raise ValueError('task_done() called too many times')
                self.all_tasks_done.notify_all()
            self.unfinished_tasks = unfinished

    def join(self):
        '''Blocks until all items in the Queue have been gotten and processed.

        The count of unfinished tasks goes up whenever an item is added to the
        queue. The count goes down whenever a consumer thread calls task_done()
        to indicate the item was retrieved and all work on it is complete.

        When the count of unfinished tasks drops to zero, join() unblocks.
        '''
        with self.all_tasks_done:
            while self.unfinished_tasks:
                self.all_tasks_done.wait()

    def qsize(self):
        '''Return the approximate size of the queue (not reliable!).'''
        with self.mutex:
            return self._qsize()

    def empty(self):
        '''Return True if the queue is empty, False otherwise (not reliable!).

        This method is likely to be removed at some point.  Use qsize() == 0
        as a direct substitute, but be aware that either approach risks a race
        condition where a queue can grow before the result of empty() or
        qsize() can be used.

        To create code that needs to wait for all queued tasks to be
        completed, the preferred technique is to use the join() method.
        '''
        with self.mutex:
            return not self._qsize()

    def full(self):
        '''Return True if the queue is full, False otherwise (not reliable!).

        This method is likely to be removed at some point.  Use qsize() >= n
        as a direct substitute, but be aware that either approach risks a race
        condition where a queue can shrink before the result of full() or
        qsize() can be used.
        '''
        with self.mutex:
            return 0 < self.maxsize <= self._qsize()

    def put(self, item, block=True, timeout=None):
        '''Put an item into the queue.

        If optional args 'block' is true and 'timeout' is None (the default),
        block if necessary until a free slot is available. If 'timeout' is
        a non-negative number, it blocks at most 'timeout' seconds and raises
        the Full exception if no free slot was available within that time.
        Otherwise ('block' is false), put an item on the queue if a free slot
        is immediately available, else raise the Full exception ('timeout'
        is ignored in that case).
        '''
        with self.not_full:
            if self.maxsize > 0:
                if not block:
                    if self._qsize() >= self.maxsize:
                        raise Full
                elif timeout is None:
                    while self._qsize() >= self.maxsize:
                        self.not_full.wait()
                elif timeout < 0:
                    raise ValueError("'timeout' must be a non-negative number")
                else:
                    endtime = time() + timeout
                    while self._qsize() >= self.maxsize:
                        remaining = endtime - time()
                        if remaining <= 0.0:
                            raise Full
                        self.not_full.wait(remaining)
            self._put(item)
            self.unfinished_tasks += 1
            self.not_empty.notify()

    def get(self, block=True, timeout=None):
        '''Remove and return an item from the queue.

        If optional args 'block' is true and 'timeout' is None (the default),
        block if necessary until an item is available. If 'timeout' is
        a non-negative number, it blocks at most 'timeout' seconds and raises
        the Empty exception if no item was available within that time.
        Otherwise ('block' is false), return an item if one is immediately
        available, else raise the Empty exception ('timeout' is ignored
        in that case).
        '''
        with self.not_empty:
            if not block:
                if not self._qsize():
                    raise Empty
            elif timeout is None:
                while not self._qsize():
                    self.not_empty.wait()
            elif timeout < 0:
                raise ValueError("'timeout' must be a non-negative number")
            else:
                endtime = time() + timeout
                while not self._qsize():
                    remaining = endtime - time()
                    if remaining <= 0.0:
                        raise Empty
                    self.not_empty.wait(remaining)
            item = self._get()
            self.not_full.notify()
            return item

    def put_nowait(self, item):
        '''Put an item into the queue without blocking.

        Only enqueue the item if a free slot is immediately available.
        Otherwise raise the Full exception.
        '''
        return self.put(item, block=False)

    def get_nowait(self):
        '''Remove and return an item from the queue without blocking.

        Only get an item if one is immediately available. Otherwise
        raise the Empty exception.
        '''
        return self.get(block=False)

    # Override these methods to implement other queue organizations
    # (e.g. stack or priority queue).
    # These will only be called with appropriate locks held

    # Initialize the queue representation
    def _init(self, maxsize):
        self.queue = deque()

    def _qsize(self):
        return len(self.queue)

    # Put a new item in the queue
    def _put(self, item):
        self.queue.append(item)

    # Get an item from the queue
    def _get(self):
        return self.queue.popleft()

    __class_getitem__ = classmethod(types.GenericAlias)


class PriorityQueue(Queue):
    '''Variant of Queue that retrieves open entries in priority order (lowest first).

    Entries are typically tuples of the form:  (priority number, data).
    '''

    def _init(self, maxsize):
        self.queue = []

    def _qsize(self):
        return len(self.queue)

    def _put(self, item):
        heappush(self.queue, item)

    def _get(self):
        return heappop(self.queue)


class LifoQueue(Queue):
    '''Variant of Queue that retrieves most recently added entries first.'''

    def _init(self, maxsize):
        self.queue = []

    def _qsize(self):
        return len(self.queue)

    def _put(self, item):
        self.queue.append(item)

    def _get(self):
        return self.queue.pop()


class _PySimpleQueue:
    '''Simple, unbounded FIFO queue.

    This pure Python implementation is not reentrant.
    '''
    # Note: while this pure Python version provides fairness
    # (by using a threading.Semaphore which is itself fair, being based
    #  on threading.Condition), fairness is not part of the API contract.
    # This allows the C version to use a different implementation.

    def __init__(self):
        self._queue = deque()
        self._count = threading.Semaphore(0)

    def put(self, item, block=True, timeout=None):
        '''Put the item on the queue.

        The optional 'block' and 'timeout' arguments are ignored, as this method
        never blocks.  They are provided for compatibility with the Queue class.
        '''
        self._queue.append(item)
        self._count.release()

    def get(self, block=True, timeout=None):
        '''Remove and return an item from the queue.

        If optional args 'block' is true and 'timeout' is None (the default),
        block if necessary until an item is available. If 'timeout' is
        a non-negative number, it blocks at most 'timeout' seconds and raises
        the Empty exception if no item was available within that time.
        Otherwise ('block' is false), return an item if one is immediately
        available, else raise the Empty exception ('timeout' is ignored
        in that case).
        '''
        if timeout is not None and timeout < 0:
            raise ValueError("'timeout' must be a non-negative number")
        if not self._count.acquire(block, timeout):
            raise Empty
        return self._queue.popleft()

    def put_nowait(self, item):
        '''Put an item into the queue without blocking.

        This is exactly equivalent to `put(item, block=False)` and is only provided
        for compatibility with the Queue class.
        '''
        return self.put(item, block=False)

    def get_nowait(self):
        '''Remove and return an item from the queue without blocking.

        Only get an item if one is immediately available. Otherwise
        raise the Empty exception.
        '''
        return self.get(block=False)

    def empty(self):
        '''Return True if the queue is empty, False otherwise (not reliable!).'''
        return len(self._queue) == 0

    def qsize(self):
        '''Return the approximate size of the queue (not reliable!).'''
        return len(self._queue)

    __class_getitem__ = classmethod(types.GenericAlias)


if SimpleQueue is None:
    SimpleQueue = _PySimpleQueue
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        #! /usr/bin/env python3

"""Conversions to/from quoted-printable transport encoding as per RFC 1521."""

# (Dec 1991 version).

__all__ = ["encode", "decode", "encodestring", "decodestring"]

ESCAPE = b'='
MAXLINESIZE = 76
HEX = b'0123456789ABCDEF'
EMPTYSTRING = b''

try:
    from binascii import a2b_qp, b2a_qp
except ImportError:
    a2b_qp = None
    b2a_qp = None


def needsquoting(c, quotetabs, header):
    """Decide whether a particular byte ordinal needs to be quoted.

    The 'quotetabs' flag indicates whether embedded tabs and spaces should be
    quoted.  Note that line-ending tabs and spaces are always encoded, as per
    RFC 1521.
    """
    assert isinstance(c, bytes)
    if c in b' \t':
        return quotetabs
    # if header, we have to escape _ because _ is used to escape space
    if c == b'_':
        return header
    return c == ESCAPE or not (b' ' <= c <= b'~')

def quote(c):
    """Quote a single character."""
    assert isinstance(c, bytes) and len(c)==1
    c = ord(c)
    return ESCAPE + bytes((HEX[c//16], HEX[c%16]))



def encode(input, output, quotetabs, header=False):
    """Read 'input', apply quoted-printable encoding, and write to 'output'.

    'input' and 'output' are binary file objects. The 'quotetabs' flag
    indicates whether embedded tabs and spaces should be quoted. Note that
    line-ending tabs and spaces are always encoded, as per RFC 1521.
    The 'header' flag indicates whether we are encoding spaces as _ as per RFC
    1522."""

    if b2a_qp is not None:
        data = input.read()
        odata = b2a_qp(data, quotetabs=quotetabs, header=header)
        output.write(odata)
        return

    def write(s, output=output, lineEnd=b'\n'):
        # RFC 1521 requires that the line ending in a space or tab must have
        # that trailing character encoded.
        if s and s[-1:] in b' \t':
            output.write(s[:-1] + quote(s[-1:]) + lineEnd)
        elif s == b'.':
            output.write(quote(s) + lineEnd)
        else:
            output.write(s + lineEnd)

    prevline = None
    while line := input.readline():
        outline = []
        # Strip off any readline induced trailing newline
        stripped = b''
        if line[-1:] == b'\n':
            line = line[:-1]
            stripped = b'\n'
        # Calculate the un-length-limited encoded line
        for c in line:
            c = bytes((c,))
            if needsquoting(c, quotetabs, header):
                c = quote(c)
            if header and c == b' ':
                outline.append(b'_')
            else:
                outline.append(c)
        # First, write out the previous line
        if prevline is not None:
            write(prevline)
        # Now see if we need any soft line breaks because of RFC-imposed
        # length limitations.  Then do the thisline->prevline dance.
        thisline = EMPTYSTRING.join(outline)
        while len(thisline) > MAXLINESIZE:
            # Don't forget to include the soft line break `=' sign in the
            # length calculation!
            write(thisline[:MAXLINESIZE-1], lineEnd=b'=\n')
            thisline = thisline[MAXLINESIZE-1:]
        # Write out the current line
        prevline = thisline
    # Write out the last line, without a trailing newline
    if prevline is not None:
        write(prevline, lineEnd=stripped)

def encodestring(s, quotetabs=False, header=False):
    if b2a_qp is not None:
        return b2a_qp(s, quotetabs=quotetabs, header=header)
    from io import BytesIO
    infp = BytesIO(s)
    outfp = BytesIO()
    encode(infp, outfp, quotetabs, header)
    return outfp.getvalue()



def decode(input, output, header=False):
    """Read 'input', apply quoted-printable decoding, and write to 'output'.
    'input' and 'output' are binary file objects.
    If 'header' is true, decode underscore as space (per RFC 1522)."""

    if a2b_qp is not None:
        data = input.read()
        odata = a2b_qp(data, header=header)
        output.write(odata)
        return

    new = b''
    while line := input.readline():
        i, n = 0, len(line)
        if n > 0 and line[n-1:n] == b'\n':
            partial = 0; n = n-1
            # Strip trailing whitespace
            while n > 0 and line[n-1:n] in b" \t\r":
                n = n-1
        else:
            partial = 1
        while i < n:
            c = line[i:i+1]
            if c == b'_' and header:
                new = new + b' '; i = i+1
            elif c != ESCAPE:
                new = new + c; i = i+1
            elif i+1 == n and not partial:
                partial = 1; break
            elif i+1 < n and line[i+1:i+2] == ESCAPE:
                new = new + ESCAPE; i = i+2
            elif i+2 < n and ishex(line[i+1:i+2]) and ishex(line[i+2:i+3]):
                new = new + bytes((unhex(line[i+1:i+3]),)); i = i+3
            else: # Bad escape sequence -- leave it in
                new = new + c; i = i+1
        if not partial:
            output.write(new + b'\n')
            new = b''
    if new:
        output.write(new)

def decodestring(s, header=False):
    if a2b_qp is not None:
        return a2b_qp(s, header=header)
    from io import BytesIO
    infp = BytesIO(s)
    outfp = BytesIO()
    decode(infp, outfp, header=header)
    return outfp.getvalue()



# Other helper functions
def ishex(c):
    """Return true if the byte ordinal 'c' is a hexadecimal digit in ASCII."""
    assert isinstance(c, bytes)
    return b'0' <= c <= b'9' or b'a' <= c <= b'f' or b'A' <= c <= b'F'

def unhex(s):
    """Get the integer value of a hexadecimal number."""
    bits = 0
    for c in s:
        c = bytes((c,))
        if b'0' <= c <= b'9':
            i = ord('0')
        elif b'a' <= c <= b'f':
            i = ord('a')-10
        elif b'A' <= c <= b'F':
            i = ord(b'A')-10
        else:
            assert False, "non-hex digit "+repr(c)
        bits = bits*16 + (ord(c) - i)
    return bits



def main():
    import sys
    import getopt
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'td')
    except getopt.error as msg:
        sys.stdout = sys.stderr
        print(msg)
        print("usage: quopri [-t | -d] [file] ...")
        print("-t: quote tabs")
        print("-d: decode; default encode")
        sys.exit(2)
    deco = False
    tabs = False
    for o, a in opts:
        if o == '-t': tabs = True
        if o == '-d': deco = True
    if tabs and deco:
        sys.stdout = sys.stderr
        print("-t and -d are mutually exclusive")
        sys.exit(2)
    if not args: args = ['-']
    sts = 0
    for file in args:
        if file == '-':
            fp = sys.stdin.buffer
        else:
            try:
                fp = open(file, "rb")
            except OSError as msg:
                sys.stderr.write("%s: can't open (%s)\n" % (file, msg))
                sts = 1
                continue
        try:
            if deco:
                decode(fp, sys.stdout.buffer)
            else:
                encode(fp, sys.stdout.buffer, tabs)
        finally:
            if file != '-':
                fp.close()
    if sts:
        sys.exit(sts)



if __name__ == '__main__':
    main()
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                