Spade
Mini Shell
| Directory:~$ /proc/self/root/lib64/python2.7/pydoc_data/ |
| [Home] [System Details] [Kill Me] |
# Autogenerated by Sphinx on Sat May 11 22:31:13 2013
topics = {'assert': '\nThe ``assert``
statement\n************************\n\nAssert statements are a convenient
way to insert debugging assertions\ninto a program:\n\n assert_stmt ::=
"assert" expression ["," expression]\n\nThe simple
form, ``assert expression``, is equivalent to\n\n if __debug__:\n if
not expression: raise AssertionError\n\nThe extended form, ``assert
expression1, expression2``, is equivalent\nto\n\n if __debug__:\n if
not expression1: raise AssertionError(expression2)\n\nThese equivalences
assume that ``__debug__`` and ``AssertionError``\nrefer to the built-in
variables with those names. In the current\nimplementation, the built-in
variable ``__debug__`` is ``True`` under\nnormal circumstances, ``False``
when optimization is requested\n(command line option -O). The current code
generator emits no code\nfor an assert statement when optimization is
requested at compile\ntime. Note that it is unnecessary to include the
source code for the\nexpression that failed in the error message; it will
be displayed as\npart of the stack trace.\n\nAssignments to ``__debug__``
are illegal. The value for the built-in\nvariable is determined when the
interpreter starts.\n',
'assignment': '\nAssignment
statements\n*********************\n\nAssignment statements are used to
(re)bind names to values and to\nmodify attributes or items of mutable
objects:\n\n assignment_stmt ::= (target_list "=")+
(expression_list | yield_expression)\n target_list ::= target
("," target)* [","]\n target ::=
identifier\n | "(" target_list ")"\n
| "[" target_list "]"\n |
attributeref\n | subscription\n | slicing\n\n(See
section *Primaries* for the syntax definitions for the last
three\nsymbols.)\n\nAn assignment statement evaluates the expression list
(remember that\nthis can be a single expression or a comma-separated list,
the latter\nyielding a tuple) and assigns the single resulting object to
each of\nthe target lists, from left to right.\n\nAssignment is defined
recursively depending on the form of the target\n(list). When a target is
part of a mutable object (an attribute\nreference, subscription or
slicing), the mutable object must\nultimately perform the assignment and
decide about its validity, and\nmay raise an exception if the assignment is
unacceptable. The rules\nobserved by various types and the exceptions
raised are given with the\ndefinition of the object types (see section *The
standard type\nhierarchy*).\n\nAssignment of an object to a target list is
recursively defined as\nfollows.\n\n* If the target list is a single
target: The object is assigned to\n that target.\n\n* If the target list
is a comma-separated list of targets: The object\n must be an iterable
with the same number of items as there are\n targets in the target list,
and the items are assigned, from left to\n right, to the corresponding
targets.\n\nAssignment of an object to a single target is recursively
defined as\nfollows.\n\n* If the target is an identifier (name):\n\n * If
the name does not occur in a ``global`` statement in the\n current code
block: the name is bound to the object in the current\n local
namespace.\n\n * Otherwise: the name is bound to the object in the current
global\n namespace.\n\n The name is rebound if it was already bound.
This may cause the\n reference count for the object previously bound to
the name to reach\n zero, causing the object to be deallocated and its
destructor (if it\n has one) to be called.\n\n* If the target is a target
list enclosed in parentheses or in square\n brackets: The object must be
an iterable with the same number of\n items as there are targets in the
target list, and its items are\n assigned, from left to right, to the
corresponding targets.\n\n* If the target is an attribute reference: The
primary expression in\n the reference is evaluated. It should yield an
object with\n assignable attributes; if this is not the case,
``TypeError`` is\n raised. That object is then asked to assign the
assigned object to\n the given attribute; if it cannot perform the
assignment, it raises\n an exception (usually but not necessarily
``AttributeError``).\n\n Note: If the object is a class instance and the
attribute reference\n occurs on both sides of the assignment operator, the
RHS expression,\n ``a.x`` can access either an instance attribute or (if
no instance\n attribute exists) a class attribute. The LHS target ``a.x``
is\n always set as an instance attribute, creating it if necessary.\n
Thus, the two occurrences of ``a.x`` do not necessarily refer to the\n
same attribute: if the RHS expression refers to a class attribute,\n the
LHS creates a new instance attribute as the target of the\n
assignment:\n\n class Cls:\n x = 3 # class
variable\n inst = Cls()\n inst.x = inst.x + 1 # writes inst.x as
4 leaving Cls.x as 3\n\n This description does not necessarily apply to
descriptor\n attributes, such as properties created with
``property()``.\n\n* If the target is a subscription: The primary
expression in the\n reference is evaluated. It should yield either a
mutable sequence\n object (such as a list) or a mapping object (such as a
dictionary).\n Next, the subscript expression is evaluated.\n\n If the
primary is a mutable sequence object (such as a list), the\n subscript
must yield a plain integer. If it is negative, the\n sequence\'s
length is added to it. The resulting value must be a\n nonnegative integer
less than the sequence\'s length, and the\n sequence is asked to
assign the assigned object to its item with\n that index. If the index is
out of range, ``IndexError`` is raised\n (assignment to a subscripted
sequence cannot add new items to a\n list).\n\n If the primary is a
mapping object (such as a dictionary), the\n subscript must have a type
compatible with the mapping\'s key type,\n and the mapping is then
asked to create a key/datum pair which maps\n the subscript to the
assigned object. This can either replace an\n existing key/value pair
with the same key value, or insert a new\n key/value pair (if no key with
the same value existed).\n\n* If the target is a slicing: The primary
expression in the reference\n is evaluated. It should yield a mutable
sequence object (such as a\n list). The assigned object should be a
sequence object of the same\n type. Next, the lower and upper bound
expressions are evaluated,\n insofar they are present; defaults are zero
and the sequence\'s\n length. The bounds should evaluate to (small)
integers. If either\n bound is negative, the sequence\'s length is
added to it. The\n resulting bounds are clipped to lie between zero and
the sequence\'s\n length, inclusive. Finally, the sequence object is
asked to replace\n the slice with the items of the assigned sequence. The
length of\n the slice may be different from the length of the assigned
sequence,\n thus changing the length of the target sequence, if the
object\n allows it.\n\n**CPython implementation detail:** In the current
implementation, the\nsyntax for targets is taken to be the same as for
expressions, and\ninvalid syntax is rejected during the code generation
phase, causing\nless detailed error messages.\n\nWARNING: Although the
definition of assignment implies that overlaps\nbetween the left-hand side
and the right-hand side are \'safe\' (for\nexample ``a, b = b,
a`` swaps two variables), overlaps *within* the\ncollection of assigned-to
variables are not safe! For instance, the\nfollowing program prints ``[0,
2]``:\n\n x = [0, 1]\n i = 0\n i, x[i] = 1, 2\n print
x\n\n\nAugmented assignment
statements\n===============================\n\nAugmented assignment is the
combination, in a single statement, of a\nbinary operation and an
assignment statement:\n\n augmented_assignment_stmt ::= augtarget augop
(expression_list | yield_expression)\n augtarget ::=
identifier | attributeref | subscription | slicing\n augop
::= "+=" | "-=" | "*=" | "/="
| "//=" | "%=" | "**="\n |
">>=" | "<<=" | "&=" |
"^=" | "|="\n\n(See section *Primaries* for the syntax
definitions for the last three\nsymbols.)\n\nAn augmented assignment
evaluates the target (which, unlike normal\nassignment statements, cannot
be an unpacking) and the expression\nlist, performs the binary operation
specific to the type of assignment\non the two operands, and assigns the
result to the original target.\nThe target is only evaluated once.\n\nAn
augmented assignment expression like ``x += 1`` can be rewritten as\n``x =
x + 1`` to achieve a similar, but not exactly equal effect. In\nthe
augmented version, ``x`` is only evaluated once. Also, when\npossible, the
actual operation is performed *in-place*, meaning that\nrather than
creating a new object and assigning that to the target,\nthe old object is
modified instead.\n\nWith the exception of assigning to tuples and multiple
targets in a\nsingle statement, the assignment done by augmented
assignment\nstatements is handled the same way as normal assignments.
Similarly,\nwith the exception of the possible *in-place* behavior, the
binary\noperation performed by augmented assignment is the same as the
normal\nbinary operations.\n\nFor targets which are attribute references,
the same *caveat about\nclass and instance attributes* applies as for
regular assignments.\n',
'atom-identifiers': '\nIdentifiers
(Names)\n*******************\n\nAn identifier occurring as an atom is a
name. See section\n*Identifiers and keywords* for lexical definition and
section *Naming\nand binding* for documentation of naming and
binding.\n\nWhen the name is bound to an object, evaluation of the atom
yields\nthat object. When a name is not bound, an attempt to evaluate
it\nraises a ``NameError`` exception.\n\n**Private name mangling:** When an
identifier that textually occurs in\na class definition begins with two or
more underscore characters and\ndoes not end in two or more underscores, it
is considered a *private\nname* of that class. Private names are
transformed to a longer form\nbefore code is generated for them. The
transformation inserts the\nclass name, with leading underscores removed
and a single underscore\ninserted, in front of the name. For example, the
identifier\n``__spam`` occurring in a class named ``Ham`` will be
transformed to\n``_Ham__spam``. This transformation is independent of the
syntactical\ncontext in which the identifier is used. If the transformed
name is\nextremely long (longer than 255 characters), implementation
defined\ntruncation may happen. If the class name consists only of
underscores,\nno transformation is done.\n',
'atom-literals': "\nLiterals\n********\n\nPython supports
string literals and various numeric literals:\n\n literal ::=
stringliteral | integer | longinteger\n | floatnumber |
imagnumber\n\nEvaluation of a literal yields an object of the given type
(string,\ninteger, long integer, floating point number, complex number)
with the\ngiven value. The value may be approximated in the case of
floating\npoint and imaginary (complex) literals. See section *Literals*
for\ndetails.\n\nAll literals correspond to immutable data types, and hence
the\nobject's identity is less important than its value.
Multiple\nevaluations of literals with the same value (either the
same\noccurrence in the program text or a different occurrence) may
obtain\nthe same object or a different object with the same value.\n",
'attribute-access': '\nCustomizing attribute
access\n****************************\n\nThe following methods can be
defined to customize the meaning of\nattribute access (use of, assignment
to, or deletion of ``x.name``)\nfor class
instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute
lookup has not found the attribute in the\n usual places (i.e. it is not
an instance attribute nor is it found\n in the class tree for ``self``).
``name`` is the attribute name.\n This method should return the
(computed) attribute value or raise\n an ``AttributeError``
exception.\n\n Note that if the attribute is found through the normal
mechanism,\n ``__getattr__()`` is not called. (This is an intentional
asymmetry\n between ``__getattr__()`` and ``__setattr__()``.) This is
done both\n for efficiency reasons and because otherwise
``__getattr__()``\n would have no way to access other attributes of the
instance. Note\n that at least for instance variables, you can fake
total control by\n not inserting any values in the instance attribute
dictionary (but\n instead inserting them in another object). See the\n
``__getattribute__()`` method below for a way to actually get total\n
control in new-style classes.\n\nobject.__setattr__(self, name, value)\n\n
Called when an attribute assignment is attempted. This is called\n
instead of the normal mechanism (i.e. store the value in the\n instance
dictionary). *name* is the attribute name, *value* is the\n value to be
assigned to it.\n\n If ``__setattr__()`` wants to assign to an instance
attribute, it\n should not simply execute ``self.name = value`` --- this
would\n cause a recursive call to itself. Instead, it should insert
the\n value in the dictionary of instance attributes, e.g.,\n
``self.__dict__[name] = value``. For new-style classes, rather\n than
accessing the instance dictionary, it should call the base\n class method
with the same name, for example,\n ``object.__setattr__(self, name,
value)``.\n\nobject.__delattr__(self, name)\n\n Like ``__setattr__()``
but for attribute deletion instead of\n assignment. This should only be
implemented if ``del obj.name`` is\n meaningful for the object.\n\n\nMore
attribute access for new-style
classes\n===========================================\n\nThe following
methods only apply to new-style classes.\n\nobject.__getattribute__(self,
name)\n\n Called unconditionally to implement attribute accesses for\n
instances of the class. If the class also defines\n ``__getattr__()``,
the latter will not be called unless\n ``__getattribute__()`` either
calls it explicitly or raises an\n ``AttributeError``. This method should
return the (computed)\n attribute value or raise an ``AttributeError``
exception. In order\n to avoid infinite recursion in this method, its
implementation\n should always call the base class method with the same
name to\n access any attributes it needs, for example,\n
``object.__getattribute__(self, name)``.\n\n Note: This method may still
be bypassed when looking up special methods\n as the result of implicit
invocation via language syntax or\n built-in functions. See *Special
method lookup for new-style\n classes*.\n\n\nImplementing
Descriptors\n========================\n\nThe following methods only apply
when an instance of the class\ncontaining the method (a so-called
*descriptor* class) appears in an\n*owner* class (the descriptor must be in
either the owner\'s class\ndictionary or in the class dictionary for
one of its parents). In the\nexamples below, "the attribute"
refers to the attribute whose name is\nthe key of the property in the owner
class\' ``__dict__``.\n\nobject.__get__(self, instance, owner)\n\n
Called to get the attribute of the owner class (class attribute\n access)
or of an instance of that class (instance attribute\n access). *owner* is
always the owner class, while *instance* is the\n instance that the
attribute was accessed through, or ``None`` when\n the attribute is
accessed through the *owner*. This method should\n return the (computed)
attribute value or raise an\n ``AttributeError``
exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the
attribute on an instance *instance* of the owner\n class to a new value,
*value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the
attribute on an instance *instance* of the\n owner class.\n\n\nInvoking
Descriptors\n====================\n\nIn general, a descriptor is an object
attribute with "binding\nbehavior", one whose attribute access
has been overridden by methods\nin the descriptor protocol: ``__get__()``,
``__set__()``, and\n``__delete__()``. If any of those methods are defined
for an object,\nit is said to be a descriptor.\n\nThe default behavior for
attribute access is to get, set, or delete\nthe attribute from an
object\'s dictionary. For instance, ``a.x`` has a\nlookup chain
starting with ``a.__dict__[\'x\']``,
then\n``type(a).__dict__[\'x\']``, and continuing through the
base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the
looked-up value is an object defining one of the\ndescriptor methods, then
Python may override the default behavior and\ninvoke the descriptor method
instead. Where this occurs in the\nprecedence chain depends on which
descriptor methods were defined and\nhow they were called. Note that
descriptors are only invoked for new\nstyle objects or classes (ones that
subclass ``object()`` or\n``type()``).\n\nThe starting point for descriptor
invocation is a binding, ``a.x``.\nHow the arguments are assembled depends
on ``a``:\n\nDirect Call\n The simplest and least common call is when
user code directly\n invokes a descriptor method:
``x.__get__(a)``.\n\nInstance Binding\n If binding to a new-style object
instance, ``a.x`` is transformed\n into the call:
``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass
Binding\n If binding to a new-style class, ``A.x`` is transformed into
the\n call: ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper
Binding\n If ``a`` is an instance of ``super``, then the binding
``super(B,\n obj).m()`` searches ``obj.__class__.__mro__`` for the base
class\n ``A`` immediately preceding ``B`` and then invokes the
descriptor\n with the call: ``A.__dict__[\'m\'].__get__(obj,
obj.__class__)``.\n\nFor instance bindings, the precedence of descriptor
invocation depends\non the which descriptor methods are defined. A
descriptor can define\nany combination of ``__get__()``, ``__set__()`` and
``__delete__()``.\nIf it does not define ``__get__()``, then accessing the
attribute will\nreturn the descriptor object itself unless there is a value
in the\nobject\'s instance dictionary. If the descriptor defines
``__set__()``\nand/or ``__delete__()``, it is a data descriptor; if it
defines\nneither, it is a non-data descriptor. Normally, data
descriptors\ndefine both ``__get__()`` and ``__set__()``, while
non-data\ndescriptors have just the ``__get__()`` method. Data descriptors
with\n``__set__()`` and ``__get__()`` defined always override a
redefinition\nin an instance dictionary. In contrast, non-data descriptors
can be\noverridden by instances.\n\nPython methods (including
``staticmethod()`` and ``classmethod()``)\nare implemented as non-data
descriptors. Accordingly, instances can\nredefine and override methods.
This allows individual instances to\nacquire behaviors that differ from
other instances of the same class.\n\nThe ``property()`` function is
implemented as a data descriptor.\nAccordingly, instances cannot override
the behavior of a property.\n\n\n__slots__\n=========\n\nBy default,
instances of both old and new-style classes have a\ndictionary for
attribute storage. This wastes space for objects\nhaving very few instance
variables. The space consumption can become\nacute when creating large
numbers of instances.\n\nThe default can be overridden by defining
*__slots__* in a new-style\nclass definition. The *__slots__* declaration
takes a sequence of\ninstance variables and reserves just enough space in
each instance to\nhold a value for each variable. Space is saved because
*__dict__* is\nnot created for each instance.\n\n__slots__\n\n This class
variable can be assigned a string, iterable, or sequence\n of strings
with variable names used by instances. If defined in a\n new-style
class, *__slots__* reserves space for the declared\n variables and
prevents the automatic creation of *__dict__* and\n *__weakref__* for
each instance.\n\n New in version 2.2.\n\nNotes on using *__slots__*\n\n*
When inheriting from a class without *__slots__*, the *__dict__*\n
attribute of that class will always be accessible, so a *__slots__*\n
definition in the subclass is meaningless.\n\n* Without a *__dict__*
variable, instances cannot be assigned new\n variables not listed in the
*__slots__* definition. Attempts to\n assign to an unlisted variable name
raises ``AttributeError``. If\n dynamic assignment of new variables is
desired, then add\n ``\'__dict__\'`` to the sequence of strings
in the *__slots__*\n declaration.\n\n Changed in version 2.3: Previously,
adding ``\'__dict__\'`` to the\n *__slots__* declaration would
not enable the assignment of new\n attributes not specifically listed in
the sequence of instance\n variable names.\n\n* Without a *__weakref__*
variable for each instance, classes defining\n *__slots__* do not support
weak references to its instances. If weak\n reference support is needed,
then add ``\'__weakref__\'`` to the\n sequence of strings in the
*__slots__* declaration.\n\n Changed in version 2.3: Previously, adding
``\'__weakref__\'`` to the\n *__slots__* declaration would not
enable support for weak\n references.\n\n* *__slots__* are implemented at
the class level by creating\n descriptors (*Implementing Descriptors*) for
each variable name. As\n a result, class attributes cannot be used to set
default values for\n instance variables defined by *__slots__*; otherwise,
the class\n attribute would overwrite the descriptor assignment.\n\n* The
action of a *__slots__* declaration is limited to the class\n where it is
defined. As a result, subclasses will have a *__dict__*\n unless they
also define *__slots__* (which must only contain names\n of any
*additional* slots).\n\n* If a class defines a slot also defined in a base
class, the instance\n variable defined by the base class slot is
inaccessible (except by\n retrieving its descriptor directly from the base
class). This\n renders the meaning of the program undefined. In the
future, a\n check may be added to prevent this.\n\n* Nonempty *__slots__*
does not work for classes derived from\n "variable-length"
built-in types such as ``long``, ``str`` and\n ``tuple``.\n\n* Any
non-string iterable may be assigned to *__slots__*. Mappings may\n also be
used; however, in the future, special meaning may be\n assigned to the
values corresponding to each key.\n\n* *__class__* assignment works only if
both classes have the same\n *__slots__*.\n\n Changed in version 2.6:
Previously, *__class__* assignment raised an\n error if either new or old
class had *__slots__*.\n',
'attribute-references': '\nAttribute
references\n********************\n\nAn attribute reference is a primary
followed by a period and a name:\n\n attributeref ::= primary
"." identifier\n\nThe primary must evaluate to an object of a
type that supports\nattribute references, e.g., a module, list, or an
instance. This\nobject is then asked to produce the attribute whose name
is the\nidentifier. If this attribute is not available, the
exception\n``AttributeError`` is raised. Otherwise, the type and value of
the\nobject produced is determined by the object. Multiple evaluations
of\nthe same attribute reference may yield different objects.\n',
'augassign': '\nAugmented assignment
statements\n*******************************\n\nAugmented assignment is the
combination, in a single statement, of a\nbinary operation and an
assignment statement:\n\n augmented_assignment_stmt ::= augtarget augop
(expression_list | yield_expression)\n augtarget ::=
identifier | attributeref | subscription | slicing\n augop
::= "+=" | "-=" | "*=" | "/="
| "//=" | "%=" | "**="\n |
">>=" | "<<=" | "&=" |
"^=" | "|="\n\n(See section *Primaries* for the syntax
definitions for the last three\nsymbols.)\n\nAn augmented assignment
evaluates the target (which, unlike normal\nassignment statements, cannot
be an unpacking) and the expression\nlist, performs the binary operation
specific to the type of assignment\non the two operands, and assigns the
result to the original target.\nThe target is only evaluated once.\n\nAn
augmented assignment expression like ``x += 1`` can be rewritten as\n``x =
x + 1`` to achieve a similar, but not exactly equal effect. In\nthe
augmented version, ``x`` is only evaluated once. Also, when\npossible, the
actual operation is performed *in-place*, meaning that\nrather than
creating a new object and assigning that to the target,\nthe old object is
modified instead.\n\nWith the exception of assigning to tuples and multiple
targets in a\nsingle statement, the assignment done by augmented
assignment\nstatements is handled the same way as normal assignments.
Similarly,\nwith the exception of the possible *in-place* behavior, the
binary\noperation performed by augmented assignment is the same as the
normal\nbinary operations.\n\nFor targets which are attribute references,
the same *caveat about\nclass and instance attributes* applies as for
regular assignments.\n',
'binary': '\nBinary arithmetic
operations\n****************************\n\nThe binary arithmetic
operations have the conventional priority\nlevels. Note that some of these
operations also apply to certain non-\nnumeric types. Apart from the power
operator, there are only two\nlevels, one for multiplicative operators and
one for additive\noperators:\n\n m_expr ::= u_expr | m_expr "*"
u_expr | m_expr "//" u_expr | m_expr "/" u_expr\n
| m_expr "%" u_expr\n a_expr ::= m_expr | a_expr
"+" m_expr | a_expr "-" m_expr\n\nThe ``*``
(multiplication) operator yields the product of its\narguments. The
arguments must either both be numbers, or one argument\nmust be an integer
(plain or long) and the other must be a sequence.\nIn the former case, the
numbers are converted to a common type and\nthen multiplied together. In
the latter case, sequence repetition is\nperformed; a negative repetition
factor yields an empty sequence.\n\nThe ``/`` (division) and ``//`` (floor
division) operators yield the\nquotient of their arguments. The numeric
arguments are first\nconverted to a common type. Plain or long integer
division yields an\ninteger of the same type; the result is that of
mathematical division\nwith the \'floor\' function applied to the
result. Division by zero\nraises the ``ZeroDivisionError``
exception.\n\nThe ``%`` (modulo) operator yields the remainder from the
division of\nthe first argument by the second. The numeric arguments are
first\nconverted to a common type. A zero right argument raises
the\n``ZeroDivisionError`` exception. The arguments may be floating
point\nnumbers, e.g., ``3.14%0.7`` equals ``0.34`` (since ``3.14``
equals\n``4*0.7 + 0.34``.) The modulo operator always yields a result
with\nthe same sign as its second operand (or zero); the absolute value
of\nthe result is strictly smaller than the absolute value of the
second\noperand [2].\n\nThe integer division and modulo operators are
connected by the\nfollowing identity: ``x == (x/y)*y + (x%y)``. Integer
division and\nmodulo are also connected with the built-in function
``divmod()``:\n``divmod(x, y) == (x/y, x%y)``. These identities
don\'t hold for\nfloating point numbers; there similar identities hold
approximately\nwhere ``x/y`` is replaced by ``floor(x/y)`` or ``floor(x/y)
- 1`` [3].\n\nIn addition to performing the modulo operation on numbers,
the ``%``\noperator is also overloaded by string and unicode objects to
perform\nstring formatting (also known as interpolation). The syntax for
string\nformatting is described in the Python Library Reference,
section\n*String Formatting Operations*.\n\nDeprecated since version 2.3:
The floor division operator, the modulo\noperator, and the ``divmod()``
function are no longer defined for\ncomplex numbers. Instead, convert to a
floating point number using\nthe ``abs()`` function if appropriate.\n\nThe
``+`` (addition) operator yields the sum of its arguments. The\narguments
must either both be numbers or both sequences of the same\ntype. In the
former case, the numbers are converted to a common type\nand then added
together. In the latter case, the sequences are\nconcatenated.\n\nThe
``-`` (subtraction) operator yields the difference of its\narguments. The
numeric arguments are first converted to a common\ntype.\n',
'bitwise': '\nBinary bitwise
operations\n*************************\n\nEach of the three bitwise
operations has a different priority level:\n\n and_expr ::= shift_expr |
and_expr "&" shift_expr\n xor_expr ::= and_expr | xor_expr
"^" and_expr\n or_expr ::= xor_expr | or_expr "|"
xor_expr\n\nThe ``&`` operator yields the bitwise AND of its arguments,
which must\nbe plain or long integers. The arguments are converted to a
common\ntype.\n\nThe ``^`` operator yields the bitwise XOR (exclusive OR)
of its\narguments, which must be plain or long integers. The arguments
are\nconverted to a common type.\n\nThe ``|`` operator yields the bitwise
(inclusive) OR of its arguments,\nwhich must be plain or long integers.
The arguments are converted to\na common type.\n',
'bltin-code-objects': '\nCode Objects\n************\n\nCode
objects are used by the implementation to represent
"pseudo-\ncompiled" executable Python code such as a function
body. They differ\nfrom function objects because they don\'t contain a
reference to their\nglobal execution environment. Code objects are
returned by the built-\nin ``compile()`` function and can be extracted from
function objects\nthrough their ``func_code`` attribute. See also the
``code`` module.\n\nA code object can be executed or evaluated by passing
it (instead of a\nsource string) to the ``exec`` statement or the built-in
``eval()``\nfunction.\n\nSee *The standard type hierarchy* for more
information.\n',
'bltin-ellipsis-object': '\nThe Ellipsis
Object\n*******************\n\nThis object is used by extended slice
notation (see *Slicings*). It\nsupports no special operations. There is
exactly one ellipsis object,\nnamed ``Ellipsis`` (a built-in name).\n\nIt
is written as ``Ellipsis``. When in a subscript, it can also be\nwritten
as ``...``, for example ``seq[...]``.\n',
'bltin-null-object': "\nThe Null
Object\n***************\n\nThis object is returned by functions that
don't explicitly return a\nvalue. It supports no special operations.
There is exactly one null\nobject, named ``None`` (a built-in name).\n\nIt
is written as ``None``.\n",
'bltin-type-objects': "\nType Objects\n************\n\nType
objects represent the various object types. An object's type
is\naccessed by the built-in function ``type()``. There are no
special\noperations on types. The standard module ``types`` defines names
for\nall standard built-in types.\n\nTypes are written like this:
``<type 'int'>``.\n",
'booleans': '\nBoolean operations\n******************\n\n
or_test ::= and_test | or_test "or" and_test\n and_test ::=
not_test | and_test "and" not_test\n not_test ::= comparison |
"not" not_test\n\nIn the context of Boolean operations, and also
when expressions are\nused by control flow statements, the following values
are interpreted\nas false: ``False``, ``None``, numeric zero of all types,
and empty\nstrings and containers (including strings, tuples,
lists,\ndictionaries, sets and frozensets). All other values are
interpreted\nas true. (See the ``__nonzero__()`` special method for a way
to\nchange this.)\n\nThe operator ``not`` yields ``True`` if its argument
is false,\n``False`` otherwise.\n\nThe expression ``x and y`` first
evaluates *x*; if *x* is false, its\nvalue is returned; otherwise, *y* is
evaluated and the resulting value\nis returned.\n\nThe expression ``x or
y`` first evaluates *x*; if *x* is true, its\nvalue is returned; otherwise,
*y* is evaluated and the resulting value\nis returned.\n\n(Note that
neither ``and`` nor ``or`` restrict the value and type they\nreturn to
``False`` and ``True``, but rather return the last evaluated\nargument.
This is sometimes useful, e.g., if ``s`` is a string that\nshould be
replaced by a default value if it is empty, the expression\n``s or
\'foo\'`` yields the desired value. Because ``not`` has
to\ninvent a value anyway, it does not bother to return a value of
the\nsame type as its argument, so e.g., ``not \'foo\'`` yields
``False``,\nnot ``\'\'``.)\n',
'break': '\nThe ``break``
statement\n***********************\n\n break_stmt ::=
"break"\n\n``break`` may only occur syntactically nested in a
``for`` or\n``while`` loop, but not nested in a function or class
definition\nwithin that loop.\n\nIt terminates the nearest enclosing loop,
skipping the optional\n``else`` clause if the loop has one.\n\nIf a ``for``
loop is terminated by ``break``, the loop control target\nkeeps its current
value.\n\nWhen ``break`` passes control out of a ``try`` statement with
a\n``finally`` clause, that ``finally`` clause is executed before
really\nleaving the loop.\n',
'callable-types': '\nEmulating callable
objects\n**************************\n\nobject.__call__(self[, args...])\n\n
Called when the instance is "called" as a function; if this
method\n is defined, ``x(arg1, arg2, ...)`` is a shorthand for\n
``x.__call__(arg1, arg2, ...)``.\n',
'calls': '\nCalls\n*****\n\nA call calls a callable object
(e.g., a *function*) with a possibly\nempty series of *arguments*:\n\n
call ::= primary "(" [argument_list
[","]\n | expression genexpr_for] ")"\n
argument_list ::= positional_arguments [","
keyword_arguments]\n ["," "*"
expression] ["," keyword_arguments]\n
["," "**" expression]\n |
keyword_arguments ["," "*" expression]\n
["," "**" expression]\n |
"*" expression ["," "*" expression]
["," "**" expression]\n |
"**" expression\n positional_arguments ::= expression
("," expression)*\n keyword_arguments ::= keyword_item
("," keyword_item)*\n keyword_item ::= identifier
"=" expression\n\nA trailing comma may be present after the
positional and keyword\narguments but does not affect the semantics.\n\nThe
primary must evaluate to a callable object (user-defined\nfunctions,
built-in functions, methods of built-in objects, class\nobjects, methods of
class instances, and certain class instances\nthemselves are callable;
extensions may define additional callable\nobject types). All argument
expressions are evaluated before the call\nis attempted. Please refer to
section *Function definitions* for the\nsyntax of formal *parameter*
lists.\n\nIf keyword arguments are present, they are first converted
to\npositional arguments, as follows. First, a list of unfilled slots
is\ncreated for the formal parameters. If there are N
positional\narguments, they are placed in the first N slots. Next, for
each\nkeyword argument, the identifier is used to determine
the\ncorresponding slot (if the identifier is the same as the first
formal\nparameter name, the first slot is used, and so on). If the slot
is\nalready filled, a ``TypeError`` exception is raised. Otherwise,
the\nvalue of the argument is placed in the slot, filling it (even if
the\nexpression is ``None``, it fills the slot). When all arguments
have\nbeen processed, the slots that are still unfilled are filled with
the\ncorresponding default value from the function definition.
(Default\nvalues are calculated, once, when the function is defined; thus,
a\nmutable object such as a list or dictionary used as default value
will\nbe shared by all calls that don\'t specify an argument value for
the\ncorresponding slot; this should usually be avoided.) If there are
any\nunfilled slots for which no default value is specified,
a\n``TypeError`` exception is raised. Otherwise, the list of filled\nslots
is used as the argument list for the call.\n\n**CPython implementation
detail:** An implementation may provide\nbuilt-in functions whose
positional parameters do not have names, even\nif they are
\'named\' for the purpose of documentation, and which\ntherefore
cannot be supplied by keyword. In CPython, this is the case\nfor functions
implemented in C that use ``PyArg_ParseTuple()`` to\nparse their
arguments.\n\nIf there are more positional arguments than there are formal
parameter\nslots, a ``TypeError`` exception is raised, unless a formal
parameter\nusing the syntax ``*identifier`` is present; in this case, that
formal\nparameter receives a tuple containing the excess positional
arguments\n(or an empty tuple if there were no excess positional
arguments).\n\nIf any keyword argument does not correspond to a formal
parameter\nname, a ``TypeError`` exception is raised, unless a formal
parameter\nusing the syntax ``**identifier`` is present; in this case,
that\nformal parameter receives a dictionary containing the excess
keyword\narguments (using the keywords as keys and the argument values
as\ncorresponding values), or a (new) empty dictionary if there were
no\nexcess keyword arguments.\n\nIf the syntax ``*expression`` appears in
the function call,\n``expression`` must evaluate to an iterable. Elements
from this\niterable are treated as if they were additional positional
arguments;\nif there are positional arguments *x1*, ..., *xN*, and
``expression``\nevaluates to a sequence *y1*, ..., *yM*, this is equivalent
to a call\nwith M+N positional arguments *x1*, ..., *xN*, *y1*, ...,
*yM*.\n\nA consequence of this is that although the ``*expression`` syntax
may\nappear *after* some keyword arguments, it is processed *before*
the\nkeyword arguments (and the ``**expression`` argument, if any --
see\nbelow). So:\n\n >>> def f(a, b):\n ... print a, b\n
...\n >>> f(b=1, *(2,))\n 2 1\n >>> f(a=1, *(2,))\n
Traceback (most recent call last):\n File "<stdin>",
line 1, in ?\n TypeError: f() got multiple values for keyword argument
\'a\'\n >>> f(1, *(2,))\n 1 2\n\nIt is unusual for
both keyword arguments and the ``*expression``\nsyntax to be used in the
same call, so in practice this confusion does\nnot arise.\n\nIf the syntax
``**expression`` appears in the function call,\n``expression`` must
evaluate to a mapping, the contents of which are\ntreated as additional
keyword arguments. In the case of a keyword\nappearing in both
``expression`` and as an explicit keyword argument,\na ``TypeError``
exception is raised.\n\nFormal parameters using the syntax ``*identifier``
or ``**identifier``\ncannot be used as positional argument slots or as
keyword argument\nnames. Formal parameters using the syntax ``(sublist)``
cannot be\nused as keyword argument names; the outermost sublist
corresponds to a\nsingle unnamed argument slot, and the argument value is
assigned to\nthe sublist using the usual tuple assignment rules after all
other\nparameter processing is done.\n\nA call always returns some value,
possibly ``None``, unless it raises\nan exception. How this value is
computed depends on the type of the\ncallable object.\n\nIf it is---\n\na
user-defined function:\n The code block for the function is executed,
passing it the\n argument list. The first thing the code block will do
is bind the\n formal parameters to the arguments; this is described in
section\n *Function definitions*. When the code block executes a
``return``\n statement, this specifies the return value of the function
call.\n\na built-in function or method:\n The result is up to the
interpreter; see *Built-in Functions* for\n the descriptions of built-in
functions and methods.\n\na class object:\n A new instance of that class
is returned.\n\na class instance method:\n The corresponding user-defined
function is called, with an argument\n list that is one longer than the
argument list of the call: the\n instance becomes the first
argument.\n\na class instance:\n The class must define a ``__call__()``
method; the effect is then\n the same as if that method was
called.\n',
'class': '\nClass definitions\n*****************\n\nA class
definition defines a class object (see section *The standard\ntype
hierarchy*):\n\n classdef ::= "class" classname
[inheritance] ":" suite\n inheritance ::= "("
[expression_list] ")"\n classname ::= identifier\n\nA class
definition is an executable statement. It first evaluates the\ninheritance
list, if present. Each item in the inheritance list\nshould evaluate to a
class object or class type which allows\nsubclassing. The class\'s
suite is then executed in a new execution\nframe (see section *Naming and
binding*), using a newly created local\nnamespace and the original global
namespace. (Usually, the suite\ncontains only function definitions.) When
the class\'s suite finishes\nexecution, its execution frame is
discarded but its local namespace is\nsaved. [4] A class object is then
created using the inheritance list\nfor the base classes and the saved
local namespace for the attribute\ndictionary. The class name is bound to
this class object in the\noriginal local namespace.\n\n**Programmer\'s
note:** Variables defined in the class definition are\nclass variables;
they are shared by all instances. To create instance\nvariables, they can
be set in a method with ``self.name = value``.\nBoth class and instance
variables are accessible through the notation\n"``self.name``",
and an instance variable hides a class variable with\nthe same name when
accessed in this way. Class variables can be used\nas defaults for instance
variables, but using mutable values there can\nlead to unexpected results.
For *new-style class*es, descriptors can\nbe used to create instance
variables with different implementation\ndetails.\n\nClass definitions,
like function definitions, may be wrapped by one or\nmore *decorator*
expressions. The evaluation rules for the decorator\nexpressions are the
same as for functions. The result must be a class\nobject, which is then
bound to the class name.\n\n-[ Footnotes ]-\n\n[1] The exception is
propagated to the invocation stack unless there\n is a ``finally``
clause which happens to raise another exception.\n That new exception
causes the old one to be lost.\n\n[2] Currently, control "flows off
the end" except in the case of an\n exception or the execution of a
``return``, ``continue``, or\n ``break`` statement.\n\n[3] A string
literal appearing as the first statement in the function\n body is
transformed into the function\'s ``__doc__`` attribute and\n
therefore the function\'s *docstring*.\n\n[4] A string literal
appearing as the first statement in the class\n body is transformed into
the namespace\'s ``__doc__`` item and\n therefore the class\'s
*docstring*.\n',
'comparisons': '\nComparisons\n***********\n\nUnlike C, all
comparison operations in Python have the same priority,\nwhich is lower
than that of any arithmetic, shifting or bitwise\noperation. Also unlike
C, expressions like ``a < b < c`` have the\ninterpretation that is
conventional in mathematics:\n\n comparison ::= or_expr (
comp_operator or_expr )*\n comp_operator ::= "<" |
">" | "==" | ">=" | "<=" |
"<>" | "!="\n |
"is" ["not"] | ["not"]
"in"\n\nComparisons yield boolean values: ``True`` or
``False``.\n\nComparisons can be chained arbitrarily, e.g., ``x < y
<= z`` is\nequivalent to ``x < y and y <= z``, except that ``y``
is evaluated\nonly once (but in both cases ``z`` is not evaluated at all
when ``x <\ny`` is found to be false).\n\nFormally, if *a*, *b*, *c*,
..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison
operators, then ``a op1 b op2 c ... y\nopN z`` is equivalent to ``a op1 b
and b op2 c and ... y opN z``,\nexcept that each expression is evaluated at
most once.\n\nNote that ``a op1 b op2 c`` doesn\'t imply any kind of
comparison\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is
perfectly legal\n(though perhaps not pretty).\n\nThe forms ``<>`` and
``!=`` are equivalent; for consistency with C,\n``!=`` is preferred; where
``!=`` is mentioned below ``<>`` is also\naccepted. The ``<>``
spelling is considered obsolescent.\n\nThe operators ``<``, ``>``,
``==``, ``>=``, ``<=``, and ``!=`` compare\nthe values of two
objects. The objects need not have the same type.\nIf both are numbers,
they are converted to a common type. Otherwise,\nobjects of different
types *always* compare unequal, and are ordered\nconsistently but
arbitrarily. You can control comparison behavior of\nobjects of
non-built-in types by defining a ``__cmp__`` method or rich\ncomparison
methods like ``__gt__``, described in section *Special\nmethod
names*.\n\n(This unusual definition of comparison was used to simplify
the\ndefinition of operations like sorting and the ``in`` and ``not
in``\noperators. In the future, the comparison rules for objects
of\ndifferent types are likely to change.)\n\nComparison of objects of the
same type depends on the type:\n\n* Numbers are compared
arithmetically.\n\n* Strings are compared lexicographically using the
numeric equivalents\n (the result of the built-in function ``ord()``) of
their characters.\n Unicode and 8-bit strings are fully interoperable in
this behavior.\n [4]\n\n* Tuples and lists are compared lexicographically
using comparison of\n corresponding elements. This means that to compare
equal, each\n element must compare equal and the two sequences must be of
the same\n type and have the same length.\n\n If not equal, the sequences
are ordered the same as their first\n differing elements. For example,
``cmp([1,2,x], [1,2,y])`` returns\n the same as ``cmp(x,y)``. If the
corresponding element does not\n exist, the shorter sequence is ordered
first (for example, ``[1,2] <\n [1,2,3]``).\n\n* Mappings
(dictionaries) compare equal if and only if their sorted\n (key, value)
lists compare equal. [5] Outcomes other than equality\n are resolved
consistently, but are not otherwise defined. [6]\n\n* Most other objects of
built-in types compare unequal unless they are\n the same object; the
choice whether one object is considered smaller\n or larger than another
one is made arbitrarily but consistently\n within one execution of a
program.\n\nThe operators ``in`` and ``not in`` test for collection
membership.\n``x in s`` evaluates to true if *x* is a member of the
collection *s*,\nand false otherwise. ``x not in s`` returns the negation
of ``x in\ns``. The collection membership test has traditionally been bound
to\nsequences; an object is a member of a collection if the collection
is\na sequence and contains an element equal to that object. However,
it\nmake sense for many other object types to support membership
tests\nwithout being a sequence. In particular, dictionaries (for keys)
and\nsets support membership testing.\n\nFor the list and tuple types, ``x
in y`` is true if and only if there\nexists an index *i* such that ``x ==
y[i]`` is true.\n\nFor the Unicode and string types, ``x in y`` is true if
and only if\n*x* is a substring of *y*. An equivalent test is ``y.find(x)
!= -1``.\nNote, *x* and *y* need not be the same type; consequently,
``u\'ab\' in\n\'abc\'`` will return ``True``. Empty
strings are always considered to\nbe a substring of any other string, so
``"" in "abc"`` will return\n``True``.\n\nChanged in
version 2.3: Previously, *x* was required to be a string of\nlength
``1``.\n\nFor user-defined classes which define the ``__contains__()``
method,\n``x in y`` is true if and only if ``y.__contains__(x)`` is
true.\n\nFor user-defined classes which do not define ``__contains__()``
but do\ndefine ``__iter__()``, ``x in y`` is true if some value ``z`` with
``x\n== z`` is produced while iterating over ``y``. If an exception
is\nraised during the iteration, it is as if ``in`` raised that
exception.\n\nLastly, the old-style iteration protocol is tried: if a class
defines\n``__getitem__()``, ``x in y`` is true if and only if there is a
non-\nnegative integer index *i* such that ``x == y[i]``, and all
lower\ninteger indices do not raise ``IndexError`` exception. (If any
other\nexception is raised, it is as if ``in`` raised that
exception).\n\nThe operator ``not in`` is defined to have the inverse true
value of\n``in``.\n\nThe operators ``is`` and ``is not`` test for object
identity: ``x is\ny`` is true if and only if *x* and *y* are the same
object. ``x is\nnot y`` yields the inverse truth value. [7]\n',
'compound': '\nCompound
statements\n*******************\n\nCompound statements contain (groups of)
other statements; they affect\nor control the execution of those other
statements in some way. In\ngeneral, compound statements span multiple
lines, although in simple\nincarnations a whole compound statement may be
contained in one line.\n\nThe ``if``, ``while`` and ``for`` statements
implement traditional\ncontrol flow constructs. ``try`` specifies
exception handlers and/or\ncleanup code for a group of statements.
Function and class\ndefinitions are also syntactically compound
statements.\n\nCompound statements consist of one or more
\'clauses.\' A clause\nconsists of a header and a
\'suite.\' The clause headers of a\nparticular compound
statement are all at the same indentation level.\nEach clause header begins
with a uniquely identifying keyword and ends\nwith a colon. A suite is a
group of statements controlled by a\nclause. A suite can be one or more
semicolon-separated simple\nstatements on the same line as the header,
following the header\'s\ncolon, or it can be one or more indented
statements on subsequent\nlines. Only the latter form of suite can contain
nested compound\nstatements; the following is illegal, mostly because it
wouldn\'t be\nclear to which ``if`` clause a following ``else`` clause
would belong:\n\n if test1: if test2: print x\n\nAlso note that the
semicolon binds tighter than the colon in this\ncontext, so that in the
following example, either all or none of the\n``print`` statements are
executed:\n\n if x < y < z: print x; print y; print
z\n\nSummarizing:\n\n compound_stmt ::= if_stmt\n |
while_stmt\n | for_stmt\n |
try_stmt\n | with_stmt\n |
funcdef\n | classdef\n |
decorated\n suite ::= stmt_list NEWLINE | NEWLINE INDENT
statement+ DEDENT\n statement ::= stmt_list NEWLINE | compound_stmt\n
stmt_list ::= simple_stmt (";" simple_stmt)*
[";"]\n\nNote that statements always end in a ``NEWLINE``
possibly followed by\na ``DEDENT``. Also note that optional continuation
clauses always\nbegin with a keyword that cannot start a statement, thus
there are no\nambiguities (the \'dangling ``else``\' problem is
solved in Python by\nrequiring nested ``if`` statements to be
indented).\n\nThe formatting of the grammar rules in the following sections
places\neach clause on a separate line for clarity.\n\n\nThe ``if``
statement\n====================\n\nThe ``if`` statement is used for
conditional execution:\n\n if_stmt ::= "if" expression
":" suite\n ( "elif" expression
":" suite )*\n ["else" ":"
suite]\n\nIt selects exactly one of the suites by evaluating the
expressions one\nby one until one is found to be true (see section *Boolean
operations*\nfor the definition of true and false); then that suite is
executed\n(and no other part of the ``if`` statement is executed or
evaluated).\nIf all expressions are false, the suite of the ``else``
clause, if\npresent, is executed.\n\n\nThe ``while``
statement\n=======================\n\nThe ``while`` statement is used for
repeated execution as long as an\nexpression is true:\n\n while_stmt ::=
"while" expression ":" suite\n
["else" ":" suite]\n\nThis repeatedly tests the
expression and, if it is true, executes the\nfirst suite; if the expression
is false (which may be the first time\nit is tested) the suite of the
``else`` clause, if present, is\nexecuted and the loop terminates.\n\nA
``break`` statement executed in the first suite terminates the
loop\nwithout executing the ``else`` clause\'s suite. A
``continue``\nstatement executed in the first suite skips the rest of the
suite and\ngoes back to testing the expression.\n\n\nThe ``for``
statement\n=====================\n\nThe ``for`` statement is used to
iterate over the elements of a\nsequence (such as a string, tuple or list)
or other iterable object:\n\n for_stmt ::= "for" target_list
"in" expression_list ":" suite\n
["else" ":" suite]\n\nThe expression list is evaluated
once; it should yield an iterable\nobject. An iterator is created for the
result of the\n``expression_list``. The suite is then executed once for
each item\nprovided by the iterator, in the order of ascending indices.
Each\nitem in turn is assigned to the target list using the standard
rules\nfor assignments, and then the suite is executed. When the items
are\nexhausted (which is immediately when the sequence is empty), the
suite\nin the ``else`` clause, if present, is executed, and the
loop\nterminates.\n\nA ``break`` statement executed in the first suite
terminates the loop\nwithout executing the ``else`` clause\'s suite.
A ``continue``\nstatement executed in the first suite skips the rest of the
suite and\ncontinues with the next item, or with the ``else`` clause if
there was\nno next item.\n\nThe suite may assign to the variable(s) in the
target list; this does\nnot affect the next item assigned to it.\n\nThe
target list is not deleted when the loop is finished, but if the\nsequence
is empty, it will not have been assigned to at all by the\nloop. Hint: the
built-in function ``range()`` returns a sequence of\nintegers suitable to
emulate the effect of Pascal\'s ``for i := a to b\ndo``; e.g.,
``range(3)`` returns the list ``[0, 1, 2]``.\n\nNote: There is a subtlety
when the sequence is being modified by the loop\n (this can only occur for
mutable sequences, i.e. lists). An internal\n counter is used to keep
track of which item is used next, and this\n is incremented on each
iteration. When this counter has reached the\n length of the sequence the
loop terminates. This means that if the\n suite deletes the current (or a
previous) item from the sequence,\n the next item will be skipped (since
it gets the index of the\n current item which has already been treated).
Likewise, if the\n suite inserts an item in the sequence before the
current item, the\n current item will be treated again the next time
through the loop.\n This can lead to nasty bugs that can be avoided by
making a\n temporary copy using a slice of the whole sequence, e.g.,\n\n
for x in a[:]:\n if x < 0: a.remove(x)\n\n\nThe ``try``
statement\n=====================\n\nThe ``try`` statement specifies
exception handlers and/or cleanup code\nfor a group of statements:\n\n
try_stmt ::= try1_stmt | try2_stmt\n try1_stmt ::= "try"
":" suite\n ("except" [expression
[("as" | ",") target]] ":" suite)+\n
["else" ":" suite]\n
["finally" ":" suite]\n try2_stmt ::= "try"
":" suite\n "finally" ":"
suite\n\nChanged in version 2.5: In previous versions of
Python,\n``try``...``except``...``finally`` did not work.
``try``...``except``\nhad to be nested in ``try``...``finally``.\n\nThe
``except`` clause(s) specify one or more exception handlers. When\nno
exception occurs in the ``try`` clause, no exception handler is\nexecuted.
When an exception occurs in the ``try`` suite, a search for\nan exception
handler is started. This search inspects the except\nclauses in turn until
one is found that matches the exception. An\nexpression-less except
clause, if present, must be last; it matches\nany exception. For an except
clause with an expression, that\nexpression is evaluated, and the clause
matches the exception if the\nresulting object is "compatible"
with the exception. An object is\ncompatible with an exception if it is
the class or a base class of the\nexception object, or a tuple containing
an item compatible with the\nexception.\n\nIf no except clause matches the
exception, the search for an exception\nhandler continues in the
surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of
an expression in the header of an except clause\nraises an exception, the
original search for a handler is canceled and\na search starts for the new
exception in the surrounding code and on\nthe call stack (it is treated as
if the entire ``try`` statement\nraised the exception).\n\nWhen a matching
except clause is found, the exception is assigned to\nthe target specified
in that except clause, if present, and the except\nclause\'s suite is
executed. All except clauses must have an\nexecutable block. When the end
of this block is reached, execution\ncontinues normally after the entire
try statement. (This means that\nif two nested handlers exist for the same
exception, and the exception\noccurs in the try clause of the inner
handler, the outer handler will\nnot handle the exception.)\n\nBefore an
except clause\'s suite is executed, details about the\nexception are
assigned to three variables in the ``sys`` module:\n``sys.exc_type``
receives the object identifying the exception;\n``sys.exc_value`` receives
the exception\'s parameter;\n``sys.exc_traceback`` receives a
traceback object (see section *The\nstandard type hierarchy*) identifying
the point in the program where\nthe exception occurred. These details are
also available through the\n``sys.exc_info()`` function, which returns a
tuple ``(exc_type,\nexc_value, exc_traceback)``. Use of the corresponding
variables is\ndeprecated in favor of this function, since their use is
unsafe in a\nthreaded program. As of Python 1.5, the variables are
restored to\ntheir previous values (before the call) when returning from a
function\nthat handled an exception.\n\nThe optional ``else`` clause is
executed if and when control flows off\nthe end of the ``try`` clause. [2]
Exceptions in the ``else`` clause\nare not handled by the preceding
``except`` clauses.\n\nIf ``finally`` is present, it specifies a
\'cleanup\' handler. The\n``try`` clause is executed, including
any ``except`` and ``else``\nclauses. If an exception occurs in any of the
clauses and is not\nhandled, the exception is temporarily saved. The
``finally`` clause is\nexecuted. If there is a saved exception, it is
re-raised at the end\nof the ``finally`` clause. If the ``finally`` clause
raises another\nexception or executes a ``return`` or ``break`` statement,
the saved\nexception is discarded:\n\n def f():\n try:\n
1/0\n finally:\n return 42\n\n >>> f()\n
42\n\nThe exception information is not available to the program
during\nexecution of the ``finally`` clause.\n\nWhen a ``return``,
``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a
``try``...``finally`` statement, the\n``finally`` clause is also executed
\'on the way out.\' A ``continue``\nstatement is illegal in the
``finally`` clause. (The reason is a\nproblem with the current
implementation --- this restriction may be\nlifted in the
future).\n\nAdditional information on exceptions can be found in
section\n*Exceptions*, and information on using the ``raise`` statement
to\ngenerate exceptions may be found in section *The raise
statement*.\n\n\nThe ``with`` statement\n======================\n\nNew in
version 2.5.\n\nThe ``with`` statement is used to wrap the execution of a
block with\nmethods defined by a context manager (see section *With
Statement\nContext Managers*). This allows
common\n``try``...``except``...``finally`` usage patterns to be
encapsulated\nfor convenient reuse.\n\n with_stmt ::= "with"
with_item ("," with_item)* ":" suite\n with_item ::=
expression ["as" target]\n\nThe execution of the ``with``
statement with one "item" proceeds as\nfollows:\n\n1. The context
expression (the expression given in the ``with_item``)\n is evaluated to
obtain a context manager.\n\n2. The context manager\'s ``__exit__()``
is loaded for later use.\n\n3. The context manager\'s ``__enter__()``
method is invoked.\n\n4. If a target was included in the ``with``
statement, the return\n value from ``__enter__()`` is assigned to it.\n\n
Note: The ``with`` statement guarantees that if the ``__enter__()``\n
method returns without an error, then ``__exit__()`` will always\n be
called. Thus, if an error occurs during the assignment to the\n target
list, it will be treated the same as an error occurring\n within the
suite would be. See step 6 below.\n\n5. The suite is executed.\n\n6. The
context manager\'s ``__exit__()`` method is invoked. If an\n
exception caused the suite to be exited, its type, value, and\n traceback
are passed as arguments to ``__exit__()``. Otherwise,\n three ``None``
arguments are supplied.\n\n If the suite was exited due to an exception,
and the return value\n from the ``__exit__()`` method was false, the
exception is\n reraised. If the return value was true, the exception is\n
suppressed, and execution continues with the statement following\n the
``with`` statement.\n\n If the suite was exited for any reason other than
an exception, the\n return value from ``__exit__()`` is ignored, and
execution proceeds\n at the normal location for the kind of exit that was
taken.\n\nWith more than one item, the context managers are processed as
if\nmultiple ``with`` statements were nested:\n\n with A() as a, B() as
b:\n suite\n\nis equivalent to\n\n with A() as a:\n with B()
as b:\n suite\n\nNote: In Python 2.5, the ``with`` statement is
only allowed when the\n ``with_statement`` feature has been enabled. It
is always enabled\n in Python 2.6.\n\nChanged in version 2.7: Support for
multiple context expressions.\n\nSee also:\n\n **PEP 0343** - The
"with" statement\n The specification, background, and
examples for the Python\n ``with`` statement.\n\n\nFunction
definitions\n====================\n\nA function definition defines a
user-defined function object (see\nsection *The standard type
hierarchy*):\n\n decorated ::= decorators (classdef | funcdef)\n
decorators ::= decorator+\n decorator ::= "@"
dotted_name ["(" [argument_list [","]] ")"]
NEWLINE\n funcdef ::= "def" funcname "("
[parameter_list] ")" ":" suite\n dotted_name ::=
identifier ("." identifier)*\n parameter_list ::= (defparameter
",")*\n ( "*" identifier
["," "**" identifier]\n |
"**" identifier\n | defparameter
[","] )\n defparameter ::= parameter ["="
expression]\n sublist ::= parameter ("," parameter)*
[","]\n parameter ::= identifier | "(" sublist
")"\n funcname ::= identifier\n\nA function definition is
an executable statement. Its execution binds\nthe function name in the
current local namespace to a function object\n(a wrapper around the
executable code for the function). This\nfunction object contains a
reference to the current global namespace\nas the global namespace to be
used when the function is called.\n\nThe function definition does not
execute the function body; this gets\nexecuted only when the function is
called. [3]\n\nA function definition may be wrapped by one or more
*decorator*\nexpressions. Decorator expressions are evaluated when the
function is\ndefined, in the scope that contains the function definition.
The\nresult must be a callable, which is invoked with the function
object\nas the only argument. The returned value is bound to the function
name\ninstead of the function object. Multiple decorators are applied
in\nnested fashion. For example, the following code:\n\n @f1(arg)\n
@f2\n def func(): pass\n\nis equivalent to:\n\n def func(): pass\n
func = f1(arg)(f2(func))\n\nWhen one or more top-level *parameters* have
the form *parameter*\n``=`` *expression*, the function is said to have
"default parameter\nvalues." For a parameter with a default
value, the corresponding\n*argument* may be omitted from a call, in which
case the parameter\'s\ndefault value is substituted. If a parameter
has a default value, all\nfollowing parameters must also have a default
value --- this is a\nsyntactic restriction that is not expressed by the
grammar.\n\n**Default parameter values are evaluated when the function
definition\nis executed.** This means that the expression is evaluated
once, when\nthe function is defined, and that the same
"pre-computed" value is\nused for each call. This is especially
important to understand when a\ndefault parameter is a mutable object, such
as a list or a dictionary:\nif the function modifies the object (e.g. by
appending an item to a\nlist), the default value is in effect modified.
This is generally not\nwhat was intended. A way around this is to use
``None`` as the\ndefault, and explicitly test for it in the body of the
function, e.g.:\n\n def whats_on_the_telly(penguin=None):\n if
penguin is None:\n penguin = []\n
penguin.append("property of the zoo")\n return
penguin\n\nFunction call semantics are described in more detail in
section\n*Calls*. A function call always assigns values to all
parameters\nmentioned in the parameter list, either from position
arguments, from\nkeyword arguments, or from default values. If the
form\n"``*identifier``" is present, it is initialized to a tuple
receiving\nany excess positional parameters, defaulting to the empty tuple.
If\nthe form "``**identifier``" is present, it is initialized to
a new\ndictionary receiving any excess keyword arguments, defaulting to a
new\nempty dictionary.\n\nIt is also possible to create anonymous functions
(functions not bound\nto a name), for immediate use in expressions. This
uses lambda forms,\ndescribed in section *Lambdas*. Note that the lambda
form is merely a\nshorthand for a simplified function definition; a
function defined in\na "``def``" statement can be passed around
or assigned to another name\njust like a function defined by a lambda form.
The "``def``" form is\nactually more powerful since it allows
the execution of multiple\nstatements.\n\n**Programmer\'s note:**
Functions are first-class objects. A "``def``"\nform executed
inside a function definition defines a local function\nthat can be returned
or passed around. Free variables used in the\nnested function can access
the local variables of the function\ncontaining the def. See section
*Naming and binding* for details.\n\n\nClass
definitions\n=================\n\nA class definition defines a class object
(see section *The standard\ntype hierarchy*):\n\n classdef ::=
"class" classname [inheritance] ":" suite\n
inheritance ::= "(" [expression_list] ")"\n classname
::= identifier\n\nA class definition is an executable statement. It
first evaluates the\ninheritance list, if present. Each item in the
inheritance list\nshould evaluate to a class object or class type which
allows\nsubclassing. The class\'s suite is then executed in a new
execution\nframe (see section *Naming and binding*), using a newly created
local\nnamespace and the original global namespace. (Usually, the
suite\ncontains only function definitions.) When the class\'s suite
finishes\nexecution, its execution frame is discarded but its local
namespace is\nsaved. [4] A class object is then created using the
inheritance list\nfor the base classes and the saved local namespace for
the attribute\ndictionary. The class name is bound to this class object in
the\noriginal local namespace.\n\n**Programmer\'s note:** Variables
defined in the class definition are\nclass variables; they are shared by
all instances. To create instance\nvariables, they can be set in a method
with ``self.name = value``.\nBoth class and instance variables are
accessible through the notation\n"``self.name``", and an instance
variable hides a class variable with\nthe same name when accessed in this
way. Class variables can be used\nas defaults for instance variables, but
using mutable values there can\nlead to unexpected results. For *new-style
class*es, descriptors can\nbe used to create instance variables with
different implementation\ndetails.\n\nClass definitions, like function
definitions, may be wrapped by one or\nmore *decorator* expressions. The
evaluation rules for the decorator\nexpressions are the same as for
functions. The result must be a class\nobject, which is then bound to the
class name.\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the
invocation stack unless there\n is a ``finally`` clause which happens to
raise another exception.\n That new exception causes the old one to be
lost.\n\n[2] Currently, control "flows off the end" except in the
case of an\n exception or the execution of a ``return``, ``continue``,
or\n ``break`` statement.\n\n[3] A string literal appearing as the first
statement in the function\n body is transformed into the
function\'s ``__doc__`` attribute and\n therefore the
function\'s *docstring*.\n\n[4] A string literal appearing as the
first statement in the class\n body is transformed into the
namespace\'s ``__doc__`` item and\n therefore the class\'s
*docstring*.\n',
'context-managers': '\nWith Statement Context
Managers\n*******************************\n\nNew in version 2.5.\n\nA
*context manager* is an object that defines the runtime context to\nbe
established when executing a ``with`` statement. The context\nmanager
handles the entry into, and the exit from, the desired runtime\ncontext for
the execution of the block of code. Context managers are\nnormally invoked
using the ``with`` statement (described in section\n*The with statement*),
but can also be used by directly invoking their\nmethods.\n\nTypical uses
of context managers include saving and restoring various\nkinds of global
state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor
more information on context managers, see *Context Manager
Types*.\n\nobject.__enter__(self)\n\n Enter the runtime context related
to this object. The ``with``\n statement will bind this method\'s
return value to the target(s)\n specified in the ``as`` clause of the
statement, if any.\n\nobject.__exit__(self, exc_type, exc_value,
traceback)\n\n Exit the runtime context related to this object. The
parameters\n describe the exception that caused the context to be exited.
If the\n context was exited without an exception, all three arguments
will\n be ``None``.\n\n If an exception is supplied, and the method
wishes to suppress the\n exception (i.e., prevent it from being
propagated), it should\n return a true value. Otherwise, the exception
will be processed\n normally upon exit from this method.\n\n Note that
``__exit__()`` methods should not reraise the passed-in\n exception; this
is the caller\'s responsibility.\n\nSee also:\n\n **PEP 0343** - The
"with" statement\n The specification, background, and
examples for the Python\n ``with`` statement.\n',
'continue': '\nThe ``continue``
statement\n**************************\n\n continue_stmt ::=
"continue"\n\n``continue`` may only occur syntactically nested in
a ``for`` or\n``while`` loop, but not nested in a function or class
definition or\n``finally`` clause within that loop. It continues with the
next cycle\nof the nearest enclosing loop.\n\nWhen ``continue`` passes
control out of a ``try`` statement with a\n``finally`` clause, that
``finally`` clause is executed before really\nstarting the next loop
cycle.\n',
'conversions': '\nArithmetic
conversions\n**********************\n\nWhen a description of an arithmetic
operator below uses the phrase\n"the numeric arguments are converted
to a common type," the arguments\nare coerced using the coercion rules
listed at *Coercion rules*. If\nboth arguments are standard numeric
types, the following coercions are\napplied:\n\n* If either argument is a
complex number, the other is converted to\n complex;\n\n* otherwise, if
either argument is a floating point number, the other\n is converted to
floating point;\n\n* otherwise, if either argument is a long integer, the
other is\n converted to long integer;\n\n* otherwise, both must be plain
integers and no conversion is\n necessary.\n\nSome additional rules apply
for certain operators (e.g., a string left\nargument to the \'%\'
operator). Extensions can define their own\ncoercions.\n',
'customization': '\nBasic
customization\n*******************\n\nobject.__new__(cls[, ...])\n\n
Called to create a new instance of class *cls*. ``__new__()`` is a\n
static method (special-cased so you need not declare it as such)\n that
takes the class of which an instance was requested as its\n first
argument. The remaining arguments are those passed to the\n object
constructor expression (the call to the class). The return\n value of
``__new__()`` should be the new object instance (usually\n an instance of
*cls*).\n\n Typical implementations create a new instance of the class
by\n invoking the superclass\'s ``__new__()`` method using\n
``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n
arguments and then modifying the newly-created instance as\n necessary
before returning it.\n\n If ``__new__()`` returns an instance of *cls*,
then the new\n instance\'s ``__init__()`` method will be invoked
like\n ``__init__(self[, ...])``, where *self* is the new instance and
the\n remaining arguments are the same as were passed to
``__new__()``.\n\n If ``__new__()`` does not return an instance of *cls*,
then the new\n instance\'s ``__init__()`` method will not be
invoked.\n\n ``__new__()`` is intended mainly to allow subclasses of
immutable\n types (like int, str, or tuple) to customize instance
creation. It\n is also commonly overridden in custom metaclasses in
order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n
Called when the instance is created. The arguments are those\n passed
to the class constructor expression. If a base class has an\n
``__init__()`` method, the derived class\'s ``__init__()`` method,\n
if any, must explicitly call it to ensure proper initialization of\n the
base class part of the instance; for example:\n
``BaseClass.__init__(self, [args...])``. As a special constraint\n on
constructors, no value may be returned; doing so will cause a\n
``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n Called
when the instance is about to be destroyed. This is also\n called a
destructor. If a base class has a ``__del__()`` method,\n the derived
class\'s ``__del__()`` method, if any, must explicitly\n call it to
ensure proper deletion of the base class part of the\n instance. Note
that it is possible (though not recommended!) for\n the ``__del__()``
method to postpone destruction of the instance by\n creating a new
reference to it. It may then be called at a later\n time when this new
reference is deleted. It is not guaranteed that\n ``__del__()`` methods
are called for objects that still exist when\n the interpreter exits.\n\n
Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the
former\n decrements the reference count for ``x`` by one, and the
latter\n is only called when ``x``\'s reference count reaches
zero. Some\n common situations that may prevent the reference count of
an\n object from going to zero include: circular references between\n
objects (e.g., a doubly-linked list or a tree data structure with\n
parent and child pointers); a reference to the object on the\n stack
frame of a function that caught an exception (the traceback\n stored in
``sys.exc_traceback`` keeps the stack frame alive); or\n a reference to
the object on the stack frame that raised an\n unhandled exception in
interactive mode (the traceback stored in\n ``sys.last_traceback``
keeps the stack frame alive). The first\n situation can only be
remedied by explicitly breaking the cycles;\n the latter two situations
can be resolved by storing ``None`` in\n ``sys.exc_traceback`` or
``sys.last_traceback``. Circular\n references which are garbage are
detected when the option cycle\n detector is enabled (it\'s on by
default), but can only be cleaned\n up if there are no Python-level
``__del__()`` methods involved.\n Refer to the documentation for the
``gc`` module for more\n information about how ``__del__()`` methods
are handled by the\n cycle detector, particularly the description of
the ``garbage``\n value.\n\n Warning: Due to the precarious
circumstances under which ``__del__()``\n methods are invoked,
exceptions that occur during their execution\n are ignored, and a
warning is printed to ``sys.stderr`` instead.\n Also, when
``__del__()`` is invoked in response to a module being\n deleted (e.g.,
when execution of the program is done), other\n globals referenced by
the ``__del__()`` method may already have\n been deleted or in the
process of being torn down (e.g. the\n import machinery shutting down).
For this reason, ``__del__()``\n methods should do the absolute
minimum needed to maintain\n external invariants. Starting with
version 1.5, Python\n guarantees that globals whose name begins with a
single\n underscore are deleted from their module before other globals
are\n deleted; if no other references to such globals exist, this may\n
help in assuring that imported modules are still available at the\n
time when the ``__del__()`` method is called.\n\n See also the *-R*
command-line option.\n\nobject.__repr__(self)\n\n Called by the
``repr()`` built-in function and by string\n conversions (reverse quotes)
to compute the "official" string\n representation of an object.
If at all possible, this should look\n like a valid Python expression
that could be used to recreate an\n object with the same value (given an
appropriate environment). If\n this is not possible, a string of the
form ``<...some useful\n description...>`` should be returned. The
return value must be a\n string object. If a class defines ``__repr__()``
but not\n ``__str__()``, then ``__repr__()`` is also used when an
"informal"\n string representation of instances of that class
is required.\n\n This is typically used for debugging, so it is important
that the\n representation is information-rich and
unambiguous.\n\nobject.__str__(self)\n\n Called by the ``str()`` built-in
function and by the ``print``\n statement to compute the
"informal" string representation of an\n object. This differs
from ``__repr__()`` in that it does not have\n to be a valid Python
expression: a more convenient or concise\n representation may be used
instead. The return value must be a\n string
object.\n\nobject.__lt__(self, other)\nobject.__le__(self,
other)\nobject.__eq__(self, other)\nobject.__ne__(self,
other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n New in
version 2.1.\n\n These are the so-called "rich comparison"
methods, and are called\n for comparison operators in preference to
``__cmp__()`` below. The\n correspondence between operator symbols and
method names is as\n follows: ``x<y`` calls ``x.__lt__(y)``,
``x<=y`` calls\n ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``,
``x!=y`` and\n ``x<>y`` call ``x.__ne__(y)``, ``x>y`` calls
``x.__gt__(y)``, and\n ``x>=y`` calls ``x.__ge__(y)``.\n\n A rich
comparison method may return the singleton\n ``NotImplemented`` if it
does not implement the operation for a\n given pair of arguments. By
convention, ``False`` and ``True`` are\n returned for a successful
comparison. However, these methods can\n return any value, so if the
comparison operator is used in a\n Boolean context (e.g., in the
condition of an ``if`` statement),\n Python will call ``bool()`` on the
value to determine if the result\n is true or false.\n\n There are no
implied relationships among the comparison operators.\n The truth of
``x==y`` does not imply that ``x!=y`` is false.\n Accordingly, when
defining ``__eq__()``, one should also define\n ``__ne__()`` so that the
operators will behave as expected. See\n the paragraph on ``__hash__()``
for some important notes on\n creating *hashable* objects which support
custom comparison\n operations and are usable as dictionary keys.\n\n
There are no swapped-argument versions of these methods (to be used\n
when the left argument does not support the operation but the right\n
argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n
other\'s reflection, ``__le__()`` and ``__ge__()`` are each
other\'s\n reflection, and ``__eq__()`` and ``__ne__()`` are their
own\n reflection.\n\n Arguments to rich comparison methods are never
coerced.\n\n To automatically generate ordering operations from a single
root\n operation, see
``functools.total_ordering()``.\n\nobject.__cmp__(self, other)\n\n Called
by comparison operations if rich comparison (see above) is\n not defined.
Should return a negative integer if ``self < other``,\n zero if
``self == other``, a positive integer if ``self > other``.\n If no
``__cmp__()``, ``__eq__()`` or ``__ne__()`` operation is\n defined, class
instances are compared by object identity\n ("address"). See
also the description of ``__hash__()`` for some\n important notes on
creating *hashable* objects which support custom\n comparison operations
and are usable as dictionary keys. (Note: the\n restriction that
exceptions are not propagated by ``__cmp__()`` has\n been removed since
Python 1.5.)\n\nobject.__rcmp__(self, other)\n\n Changed in version 2.1:
No longer supported.\n\nobject.__hash__(self)\n\n Called by built-in
function ``hash()`` and for operations on\n members of hashed collections
including ``set``, ``frozenset``, and\n ``dict``. ``__hash__()`` should
return an integer. The only\n required property is that objects which
compare equal have the same\n hash value; it is advised to somehow mix
together (e.g. using\n exclusive or) the hash values for the components
of the object that\n also play a part in comparison of objects.\n\n If
a class does not define a ``__cmp__()`` or ``__eq__()`` method\n it
should not define a ``__hash__()`` operation either; if it\n defines
``__cmp__()`` or ``__eq__()`` but not ``__hash__()``, its\n instances
will not be usable in hashed collections. If a class\n defines mutable
objects and implements a ``__cmp__()`` or\n ``__eq__()`` method, it
should not implement ``__hash__()``, since\n hashable collection
implementations require that a object\'s hash\n value is immutable
(if the object\'s hash value changes, it will be\n in the wrong hash
bucket).\n\n User-defined classes have ``__cmp__()`` and ``__hash__()``
methods\n by default; with them, all objects compare unequal (except
with\n themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n Classes
which inherit a ``__hash__()`` method from a parent class\n but change
the meaning of ``__cmp__()`` or ``__eq__()`` such that\n the hash value
returned is no longer appropriate (e.g. by switching\n to a value-based
concept of equality instead of the default\n identity based equality) can
explicitly flag themselves as being\n unhashable by setting ``__hash__ =
None`` in the class definition.\n Doing so means that not only will
instances of the class raise an\n appropriate ``TypeError`` when a
program attempts to retrieve their\n hash value, but they will also be
correctly identified as\n unhashable when checking ``isinstance(obj,
collections.Hashable)``\n (unlike classes which define their own
``__hash__()`` to explicitly\n raise ``TypeError``).\n\n Changed in
version 2.5: ``__hash__()`` may now also return a long\n integer object;
the 32-bit integer is then derived from the hash of\n that object.\n\n
Changed in version 2.6: ``__hash__`` may now be set to ``None`` to\n
explicitly flag instances of a class as
unhashable.\n\nobject.__nonzero__(self)\n\n Called to implement truth
value testing and the built-in operation\n ``bool()``; should return
``False`` or ``True``, or their integer\n equivalents ``0`` or ``1``.
When this method is not defined,\n ``__len__()`` is called, if it is
defined, and the object is\n considered true if its result is nonzero. If
a class defines\n neither ``__len__()`` nor ``__nonzero__()``, all its
instances are\n considered true.\n\nobject.__unicode__(self)\n\n Called
to implement ``unicode()`` built-in; should return a Unicode\n object.
When this method is not defined, string conversion is\n attempted, and
the result of string conversion is converted to\n Unicode using the
system default encoding.\n',
'debugger': '\n``pdb`` --- The Python
Debugger\n*******************************\n\nThe module ``pdb`` defines an
interactive source code debugger for\nPython programs. It supports setting
(conditional) breakpoints and\nsingle stepping at the source line level,
inspection of stack frames,\nsource code listing, and evaluation of
arbitrary Python code in the\ncontext of any stack frame. It also supports
post-mortem debugging\nand can be called under program control.\n\nThe
debugger is extensible --- it is actually defined as the class\n``Pdb``.
This is currently undocumented but easily understood by\nreading the
source. The extension interface uses the modules ``bdb``\nand
``cmd``.\n\nThe debugger\'s prompt is ``(Pdb)``. Typical usage to run
a program\nunder control of the debugger is:\n\n >>> import
pdb\n >>> import mymodule\n >>>
pdb.run(\'mymodule.test()\')\n > <string>(0)?()\n
(Pdb) continue\n > <string>(1)?()\n (Pdb) continue\n
NameError: \'spam\'\n > <string>(1)?()\n
(Pdb)\n\n``pdb.py`` can also be invoked as a script to debug other
scripts.\nFor example:\n\n python -m pdb myscript.py\n\nWhen invoked as a
script, pdb will automatically enter post-mortem\ndebugging if the program
being debugged exits abnormally. After post-\nmortem debugging (or after
normal exit of the program), pdb will\nrestart the program. Automatic
restarting preserves pdb\'s state (such\nas breakpoints) and in most
cases is more useful than quitting the\ndebugger upon program\'s
exit.\n\nNew in version 2.4: Restarting post-mortem behavior added.\n\nThe
typical usage to break into the debugger from a running program is\nto
insert\n\n import pdb; pdb.set_trace()\n\nat the location you want to
break into the debugger. You can then\nstep through the code following
this statement, and continue running\nwithout the debugger using the ``c``
command.\n\nThe typical usage to inspect a crashed program is:\n\n
>>> import pdb\n >>> import mymodule\n >>>
mymodule.test()\n Traceback (most recent call last):\n File
"<stdin>", line 1, in ?\n File
"./mymodule.py", line 4, in test\n test2()\n File
"./mymodule.py", line 3, in test2\n print spam\n
NameError: spam\n >>> pdb.pm()\n >
./mymodule.py(3)test2()\n -> print spam\n (Pdb)\n\nThe module
defines the following functions; each enters the debugger\nin a slightly
different way:\n\npdb.run(statement[, globals[, locals]])\n\n Execute the
*statement* (given as a string) under debugger control.\n The debugger
prompt appears before any code is executed; you can\n set breakpoints and
type ``continue``, or you can step through the\n statement using ``step``
or ``next`` (all these commands are\n explained below). The optional
*globals* and *locals* arguments\n specify the environment in which the
code is executed; by default\n the dictionary of the module ``__main__``
is used. (See the\n explanation of the ``exec`` statement or the
``eval()`` built-in\n function.)\n\npdb.runeval(expression[, globals[,
locals]])\n\n Evaluate the *expression* (given as a string) under
debugger\n control. When ``runeval()`` returns, it returns the value of
the\n expression. Otherwise this function is similar to
``run()``.\n\npdb.runcall(function[, argument, ...])\n\n Call the
*function* (a function or method object, not a string)\n with the given
arguments. When ``runcall()`` returns, it returns\n whatever the
function call returned. The debugger prompt appears\n as soon as the
function is entered.\n\npdb.set_trace()\n\n Enter the debugger at the
calling stack frame. This is useful to\n hard-code a breakpoint at a
given point in a program, even if the\n code is not otherwise being
debugged (e.g. when an assertion\n
fails).\n\npdb.post_mortem([traceback])\n\n Enter post-mortem debugging
of the given *traceback* object. If no\n *traceback* is given, it uses
the one of the exception that is\n currently being handled (an exception
must be being handled if the\n default is to be used).\n\npdb.pm()\n\n
Enter post-mortem debugging of the traceback found in\n
``sys.last_traceback``.\n\nThe ``run*`` functions and ``set_trace()`` are
aliases for\ninstantiating the ``Pdb`` class and calling the method of the
same\nname. If you want to access further features, you have to do
this\nyourself:\n\nclass class pdb.Pdb(completekey=\'tab\',
stdin=None, stdout=None, skip=None)\n\n ``Pdb`` is the debugger
class.\n\n The *completekey*, *stdin* and *stdout* arguments are passed
to the\n underlying ``cmd.Cmd`` class; see the description there.\n\n
The *skip* argument, if given, must be an iterable of glob-style\n module
name patterns. The debugger will not step into frames that\n originate
in a module that matches one of these patterns. [1]\n\n Example call to
enable tracing with *skip*:\n\n import pdb;
pdb.Pdb(skip=[\'django.*\']).set_trace()\n\n New in version
2.7: The *skip* argument.\n\n run(statement[, globals[, locals]])\n
runeval(expression[, globals[, locals]])\n runcall(function[, argument,
...])\n set_trace()\n\n See the documentation for the functions
explained above.\n',
'del': '\nThe ``del`` statement\n*********************\n\n
del_stmt ::= "del" target_list\n\nDeletion is recursively
defined very similar to the way assignment is\ndefined. Rather than
spelling it out in full details, here are some\nhints.\n\nDeletion of a
target list recursively deletes each target, from left\nto
right.\n\nDeletion of a name removes the binding of that name from the
local or\nglobal namespace, depending on whether the name occurs in a
``global``\nstatement in the same code block. If the name is unbound,
a\n``NameError`` exception will be raised.\n\nIt is illegal to delete a
name from the local namespace if it occurs\nas a free variable in a nested
block.\n\nDeletion of attribute references, subscriptions and slicings is
passed\nto the primary object involved; deletion of a slicing is in
general\nequivalent to assignment of an empty slice of the right type (but
even\nthis is determined by the sliced object).\n',
'dict': '\nDictionary displays\n*******************\n\nA
dictionary display is a possibly empty series of key/datum pairs\nenclosed
in curly braces:\n\n dict_display ::= "{" [key_datum_list
| dict_comprehension] "}"\n key_datum_list ::= key_datum
("," key_datum)* [","]\n key_datum ::=
expression ":" expression\n dict_comprehension ::= expression
":" expression comp_for\n\nA dictionary display yields a new
dictionary object.\n\nIf a comma-separated sequence of key/datum pairs is
given, they are\nevaluated from left to right to define the entries of the
dictionary:\neach key object is used as a key into the dictionary to store
the\ncorresponding datum. This means that you can specify the same
key\nmultiple times in the key/datum list, and the final dictionary\'s
value\nfor that key will be the last one given.\n\nA dict comprehension, in
contrast to list and set comprehensions,\nneeds two expressions separated
with a colon followed by the usual\n"for" and "if"
clauses. When the comprehension is run, the resulting\nkey and value
elements are inserted in the new dictionary in the order\nthey are
produced.\n\nRestrictions on the types of the key values are listed earlier
in\nsection *The standard type hierarchy*. (To summarize, the key
type\nshould be *hashable*, which excludes all mutable objects.)
Clashes\nbetween duplicate keys are not detected; the last datum
(textually\nrightmost in the display) stored for a given key value
prevails.\n',
'dynamic-features': '\nInteraction with dynamic
features\n*********************************\n\nThere are several cases
where Python statements are illegal when used\nin conjunction with nested
scopes that contain free variables.\n\nIf a variable is referenced in an
enclosing scope, it is illegal to\ndelete the name. An error will be
reported at compile time.\n\nIf the wild card form of import --- ``import
*`` --- is used in a\nfunction and the function contains or is a nested
block with free\nvariables, the compiler will raise a
``SyntaxError``.\n\nIf ``exec`` is used in a function and the function
contains or is a\nnested block with free variables, the compiler will raise
a\n``SyntaxError`` unless the exec explicitly specifies the
local\nnamespace for the ``exec``. (In other words, ``exec obj`` would
be\nillegal, but ``exec obj in ns`` would be legal.)\n\nThe ``eval()``,
``execfile()``, and ``input()`` functions and the\n``exec`` statement do
not have access to the full environment for\nresolving names. Names may be
resolved in the local and global\nnamespaces of the caller. Free variables
are not resolved in the\nnearest enclosing namespace, but in the global
namespace. [1] The\n``exec`` statement and the ``eval()`` and
``execfile()`` functions\nhave optional arguments to override the global
and local namespace.\nIf only one namespace is specified, it is used for
both.\n',
'else': '\nThe ``if``
statement\n********************\n\nThe ``if`` statement is used for
conditional execution:\n\n if_stmt ::= "if" expression
":" suite\n ( "elif" expression
":" suite )*\n ["else" ":"
suite]\n\nIt selects exactly one of the suites by evaluating the
expressions one\nby one until one is found to be true (see section *Boolean
operations*\nfor the definition of true and false); then that suite is
executed\n(and no other part of the ``if`` statement is executed or
evaluated).\nIf all expressions are false, the suite of the ``else``
clause, if\npresent, is executed.\n',
'exceptions': '\nExceptions\n**********\n\nExceptions are a
means of breaking out of the normal flow of control\nof a code block in
order to handle errors or other exceptional\nconditions. An exception is
*raised* at the point where the error is\ndetected; it may be *handled* by
the surrounding code block or by any\ncode block that directly or
indirectly invoked the code block where\nthe error occurred.\n\nThe Python
interpreter raises an exception when it detects a run-time\nerror (such as
division by zero). A Python program can also\nexplicitly raise an
exception with the ``raise`` statement. Exception\nhandlers are specified
with the ``try`` ... ``except`` statement. The\n``finally`` clause of such
a statement can be used to specify cleanup\ncode which does not handle the
exception, but is executed whether an\nexception occurred or not in the
preceding code.\n\nPython uses the "termination" model of error
handling: an exception\nhandler can find out what happened and continue
execution at an outer\nlevel, but it cannot repair the cause of the error
and retry the\nfailing operation (except by re-entering the offending piece
of code\nfrom the top).\n\nWhen an exception is not handled at all, the
interpreter terminates\nexecution of the program, or returns to its
interactive main loop. In\neither case, it prints a stack backtrace,
except when the exception is\n``SystemExit``.\n\nExceptions are identified
by class instances. The ``except`` clause\nis selected depending on the
class of the instance: it must reference\nthe class of the instance or a
base class thereof. The instance can\nbe received by the handler and can
carry additional information about\nthe exceptional
condition.\n\nExceptions can also be identified by strings, in which case
the\n``except`` clause is selected by object identity. An arbitrary
value\ncan be raised along with the identifying string which can be passed
to\nthe handler.\n\nNote: Messages to exceptions are not part of the Python
API. Their\n contents may change from one version of Python to the next
without\n warning and should not be relied on by code which will run
under\n multiple versions of the interpreter.\n\nSee also the description
of the ``try`` statement in section *The try\nstatement* and ``raise``
statement in section *The raise statement*.\n\n-[ Footnotes ]-\n\n[1] This
limitation occurs because the code that is executed by these\n
operations is not available at the time the module is compiled.\n',
'exec': '\nThe ``exec``
statement\n**********************\n\n exec_stmt ::= "exec"
or_expr ["in" expression ["," expression]]\n\nThis
statement supports dynamic execution of Python code. The first\nexpression
should evaluate to either a Unicode string, a *Latin-1*\nencoded string, an
open file object, a code object, or a tuple. If it\nis a string, the
string is parsed as a suite of Python statements\nwhich is then executed
(unless a syntax error occurs). [1] If it is an\nopen file, the file is
parsed until EOF and executed. If it is a code\nobject, it is simply
executed. For the interpretation of a tuple, see\nbelow. In all cases,
the code that\'s executed is expected to be valid\nas file input (see
section *File input*). Be aware that the\n``return`` and ``yield``
statements may not be used outside of\nfunction definitions even within the
context of code passed to the\n``exec`` statement.\n\nIn all cases, if the
optional parts are omitted, the code is executed\nin the current scope. If
only the first expression after ``in`` is\nspecified, it should be a
dictionary, which will be used for both the\nglobal and the local
variables. If two expressions are given, they\nare used for the global and
local variables, respectively. If\nprovided, *locals* can be any mapping
object. Remember that at module\nlevel, globals and locals are the same
dictionary. If two separate\nobjects are given as *globals* and *locals*,
the code will be executed\nas if it were embedded in a class
definition.\n\nThe first expression may also be a tuple of length 2 or 3.
In this\ncase, the optional parts must be omitted. The form
``exec(expr,\nglobals)`` is equivalent to ``exec expr in globals``, while
the form\n``exec(expr, globals, locals)`` is equivalent to ``exec expr
in\nglobals, locals``. The tuple form of ``exec`` provides
compatibility\nwith Python 3, where ``exec`` is a function rather than a
statement.\n\nChanged in version 2.4: Formerly, *locals* was required to be
a\ndictionary.\n\nAs a side effect, an implementation may insert additional
keys into\nthe dictionaries given besides those corresponding to variable
names\nset by the executed code. For example, the current implementation
may\nadd a reference to the dictionary of the built-in
module\n``__builtin__`` under the key ``__builtins__``
(!).\n\n**Programmer\'s hints:** dynamic evaluation of expressions is
supported\nby the built-in function ``eval()``. The built-in
functions\n``globals()`` and ``locals()`` return the current global and
local\ndictionary, respectively, which may be useful to pass around for
use\nby ``exec``.\n\n-[ Footnotes ]-\n\n[1] Note that the parser only
accepts the Unix-style end of line\n convention. If you are reading the
code from a file, make sure to\n use *universal newlines* mode to
convert Windows or Mac-style\n newlines.\n',
'execmodel': '\nExecution
model\n***************\n\n\nNaming and
binding\n==================\n\n*Names* refer to objects. Names are
introduced by name binding\noperations. Each occurrence of a name in the
program text refers to\nthe *binding* of that name established in the
innermost function block\ncontaining the use.\n\nA *block* is a piece of
Python program text that is executed as a\nunit. The following are blocks:
a module, a function body, and a class\ndefinition. Each command typed
interactively is a block. A script\nfile (a file given as standard input
to the interpreter or specified\non the interpreter command line the first
argument) is a code block.\nA script command (a command specified on the
interpreter command line\nwith the \'**-c**\' option) is a code
block. The file read by the\nbuilt-in function ``execfile()`` is a code
block. The string argument\npassed to the built-in function ``eval()`` and
to the ``exec``\nstatement is a code block. The expression read and
evaluated by the\nbuilt-in function ``input()`` is a code block.\n\nA code
block is executed in an *execution frame*. A frame contains\nsome
administrative information (used for debugging) and determines\nwhere and
how execution continues after the code block\'s execution
has\ncompleted.\n\nA *scope* defines the visibility of a name within a
block. If a local\nvariable is defined in a block, its scope includes that
block. If the\ndefinition occurs in a function block, the scope extends to
any blocks\ncontained within the defining one, unless a contained block
introduces\na different binding for the name. The scope of names defined
in a\nclass block is limited to the class block; it does not extend to
the\ncode blocks of methods -- this includes generator expressions
since\nthey are implemented using a function scope. This means that
the\nfollowing will fail:\n\n class A:\n a = 42\n b = list(a
+ i for i in range(10))\n\nWhen a name is used in a code block, it is
resolved using the nearest\nenclosing scope. The set of all such scopes
visible to a code block\nis called the block\'s *environment*.\n\nIf a
name is bound in a block, it is a local variable of that block.\nIf a name
is bound at the module level, it is a global variable. (The\nvariables of
the module code block are local and global.) If a\nvariable is used in a
code block but not defined there, it is a *free\nvariable*.\n\nWhen a name
is not found at all, a ``NameError`` exception is raised.\nIf the name
refers to a local variable that has not been bound,
a\n``UnboundLocalError`` exception is raised. ``UnboundLocalError`` is
a\nsubclass of ``NameError``.\n\nThe following constructs bind names:
formal parameters to functions,\n``import`` statements, class and function
definitions (these bind the\nclass or function name in the defining block),
and targets that are\nidentifiers if occurring in an assignment, ``for``
loop header, in the\nsecond position of an ``except`` clause header or
after ``as`` in a\n``with`` statement. The ``import`` statement of the
form ``from ...\nimport *`` binds all names defined in the imported module,
except\nthose beginning with an underscore. This form may only be used at
the\nmodule level.\n\nA target occurring in a ``del`` statement is also
considered bound for\nthis purpose (though the actual semantics are to
unbind the name). It\nis illegal to unbind a name that is referenced by an
enclosing scope;\nthe compiler will report a ``SyntaxError``.\n\nEach
assignment or import statement occurs within a block defined by a\nclass or
function definition or at the module level (the top-level\ncode
block).\n\nIf a name binding operation occurs anywhere within a code block,
all\nuses of the name within the block are treated as references to
the\ncurrent block. This can lead to errors when a name is used within
a\nblock before it is bound. This rule is subtle. Python
lacks\ndeclarations and allows name binding operations to occur
anywhere\nwithin a code block. The local variables of a code block can
be\ndetermined by scanning the entire text of the block for name
binding\noperations.\n\nIf the global statement occurs within a block, all
uses of the name\nspecified in the statement refer to the binding of that
name in the\ntop-level namespace. Names are resolved in the top-level
namespace by\nsearching the global namespace, i.e. the namespace of the
module\ncontaining the code block, and the builtins namespace, the
namespace\nof the module ``__builtin__``. The global namespace is
searched\nfirst. If the name is not found there, the builtins namespace
is\nsearched. The global statement must precede all uses of the
name.\n\nThe builtins namespace associated with the execution of a code
block\nis actually found by looking up the name ``__builtins__`` in
its\nglobal namespace; this should be a dictionary or a module (in
the\nlatter case the module\'s dictionary is used). By default, when
in the\n``__main__`` module, ``__builtins__`` is the built-in
module\n``__builtin__`` (note: no \'s\'); when in any other
module,\n``__builtins__`` is an alias for the dictionary of the
``__builtin__``\nmodule itself. ``__builtins__`` can be set to a
user-created\ndictionary to create a weak form of restricted
execution.\n\n**CPython implementation detail:** Users should not
touch\n``__builtins__``; it is strictly an implementation detail.
Users\nwanting to override values in the builtins namespace should
``import``\nthe ``__builtin__`` (no \'s\') module and modify its
attributes\nappropriately.\n\nThe namespace for a module is automatically
created the first time a\nmodule is imported. The main module for a script
is always called\n``__main__``.\n\nThe ``global`` statement has the same
scope as a name binding\noperation in the same block. If the nearest
enclosing scope for a\nfree variable contains a global statement, the free
variable is\ntreated as a global.\n\nA class definition is an executable
statement that may use and define\nnames. These references follow the
normal rules for name resolution.\nThe namespace of the class definition
becomes the attribute dictionary\nof the class. Names defined at the class
scope are not visible in\nmethods.\n\n\nInteraction with dynamic
features\n---------------------------------\n\nThere are several cases
where Python statements are illegal when used\nin conjunction with nested
scopes that contain free variables.\n\nIf a variable is referenced in an
enclosing scope, it is illegal to\ndelete the name. An error will be
reported at compile time.\n\nIf the wild card form of import --- ``import
*`` --- is used in a\nfunction and the function contains or is a nested
block with free\nvariables, the compiler will raise a
``SyntaxError``.\n\nIf ``exec`` is used in a function and the function
contains or is a\nnested block with free variables, the compiler will raise
a\n``SyntaxError`` unless the exec explicitly specifies the
local\nnamespace for the ``exec``. (In other words, ``exec obj`` would
be\nillegal, but ``exec obj in ns`` would be legal.)\n\nThe ``eval()``,
``execfile()``, and ``input()`` functions and the\n``exec`` statement do
not have access to the full environment for\nresolving names. Names may be
resolved in the local and global\nnamespaces of the caller. Free variables
are not resolved in the\nnearest enclosing namespace, but in the global
namespace. [1] The\n``exec`` statement and the ``eval()`` and
``execfile()`` functions\nhave optional arguments to override the global
and local namespace.\nIf only one namespace is specified, it is used for
both.\n\n\nExceptions\n==========\n\nExceptions are a means of breaking out
of the normal flow of control\nof a code block in order to handle errors or
other exceptional\nconditions. An exception is *raised* at the point where
the error is\ndetected; it may be *handled* by the surrounding code block
or by any\ncode block that directly or indirectly invoked the code block
where\nthe error occurred.\n\nThe Python interpreter raises an exception
when it detects a run-time\nerror (such as division by zero). A Python
program can also\nexplicitly raise an exception with the ``raise``
statement. Exception\nhandlers are specified with the ``try`` ...
``except`` statement. The\n``finally`` clause of such a statement can be
used to specify cleanup\ncode which does not handle the exception, but is
executed whether an\nexception occurred or not in the preceding
code.\n\nPython uses the "termination" model of error handling:
an exception\nhandler can find out what happened and continue execution at
an outer\nlevel, but it cannot repair the cause of the error and retry
the\nfailing operation (except by re-entering the offending piece of
code\nfrom the top).\n\nWhen an exception is not handled at all, the
interpreter terminates\nexecution of the program, or returns to its
interactive main loop. In\neither case, it prints a stack backtrace,
except when the exception is\n``SystemExit``.\n\nExceptions are identified
by class instances. The ``except`` clause\nis selected depending on the
class of the instance: it must reference\nthe class of the instance or a
base class thereof. The instance can\nbe received by the handler and can
carry additional information about\nthe exceptional
condition.\n\nExceptions can also be identified by strings, in which case
the\n``except`` clause is selected by object identity. An arbitrary
value\ncan be raised along with the identifying string which can be passed
to\nthe handler.\n\nNote: Messages to exceptions are not part of the Python
API. Their\n contents may change from one version of Python to the next
without\n warning and should not be relied on by code which will run
under\n multiple versions of the interpreter.\n\nSee also the description
of the ``try`` statement in section *The try\nstatement* and ``raise``
statement in section *The raise statement*.\n\n-[ Footnotes ]-\n\n[1] This
limitation occurs because the code that is executed by these\n
operations is not available at the time the module is compiled.\n',
'exprlists': '\nExpression lists\n****************\n\n
expression_list ::= expression ( "," expression )*
[","]\n\nAn expression list containing at least one comma yields
a tuple. The\nlength of the tuple is the number of expressions in the
list. The\nexpressions are evaluated from left to right.\n\nThe trailing
comma is required only to create a single tuple (a.k.a. a\n*singleton*); it
is optional in all other cases. A single expression\nwithout a trailing
comma doesn\'t create a tuple, but rather yields the\nvalue of that
expression. (To create an empty tuple, use an empty pair\nof parentheses:
``()``.)\n',
'floating': '\nFloating point
literals\n***********************\n\nFloating point literals are described
by the following lexical\ndefinitions:\n\n floatnumber ::= pointfloat |
exponentfloat\n pointfloat ::= [intpart] fraction | intpart
"."\n exponentfloat ::= (intpart | pointfloat) exponent\n
intpart ::= digit+\n fraction ::= "." digit+\n
exponent ::= ("e" | "E") ["+" |
"-"] digit+\n\nNote that the integer and exponent parts of
floating point numbers can\nlook like octal integers, but are interpreted
using radix 10. For\nexample, ``077e010`` is legal, and denotes the same
number as\n``77e10``. The allowed range of floating point literals
is\nimplementation-dependent. Some examples of floating point literals:\n\n
3.14 10. .001 1e100 3.14e-10 0e0\n\nNote that numeric
literals do not include a sign; a phrase like ``-1``\nis actually an
expression composed of the unary operator ``-`` and the\nliteral
``1``.\n',
'for': '\nThe ``for``
statement\n*********************\n\nThe ``for`` statement is used to
iterate over the elements of a\nsequence (such as a string, tuple or list)
or other iterable object:\n\n for_stmt ::= "for" target_list
"in" expression_list ":" suite\n
["else" ":" suite]\n\nThe expression list is evaluated
once; it should yield an iterable\nobject. An iterator is created for the
result of the\n``expression_list``. The suite is then executed once for
each item\nprovided by the iterator, in the order of ascending indices.
Each\nitem in turn is assigned to the target list using the standard
rules\nfor assignments, and then the suite is executed. When the items
are\nexhausted (which is immediately when the sequence is empty), the
suite\nin the ``else`` clause, if present, is executed, and the
loop\nterminates.\n\nA ``break`` statement executed in the first suite
terminates the loop\nwithout executing the ``else`` clause\'s suite.
A ``continue``\nstatement executed in the first suite skips the rest of the
suite and\ncontinues with the next item, or with the ``else`` clause if
there was\nno next item.\n\nThe suite may assign to the variable(s) in the
target list; this does\nnot affect the next item assigned to it.\n\nThe
target list is not deleted when the loop is finished, but if the\nsequence
is empty, it will not have been assigned to at all by the\nloop. Hint: the
built-in function ``range()`` returns a sequence of\nintegers suitable to
emulate the effect of Pascal\'s ``for i := a to b\ndo``; e.g.,
``range(3)`` returns the list ``[0, 1, 2]``.\n\nNote: There is a subtlety
when the sequence is being modified by the loop\n (this can only occur for
mutable sequences, i.e. lists). An internal\n counter is used to keep
track of which item is used next, and this\n is incremented on each
iteration. When this counter has reached the\n length of the sequence the
loop terminates. This means that if the\n suite deletes the current (or a
previous) item from the sequence,\n the next item will be skipped (since
it gets the index of the\n current item which has already been treated).
Likewise, if the\n suite inserts an item in the sequence before the
current item, the\n current item will be treated again the next time
through the loop.\n This can lead to nasty bugs that can be avoided by
making a\n temporary copy using a slice of the whole sequence, e.g.,\n\n
for x in a[:]:\n if x < 0: a.remove(x)\n',
'formatstrings': '\nFormat String
Syntax\n********************\n\nThe ``str.format()`` method and the
``Formatter`` class share the same\nsyntax for format strings (although in
the case of ``Formatter``,\nsubclasses can define their own format string
syntax).\n\nFormat strings contain "replacement fields"
surrounded by curly braces\n``{}``. Anything that is not contained in
braces is considered literal\ntext, which is copied unchanged to the
output. If you need to include\na brace character in the literal text, it
can be escaped by doubling:\n``{{`` and ``}}``.\n\nThe grammar for a
replacement field is as follows:\n\n replacement_field ::=
"{" [field_name] ["!" conversion] [":"
format_spec] "}"\n field_name ::= arg_name
("." attribute_name | "[" element_index
"]")*\n arg_name ::= [identifier | integer]\n
attribute_name ::= identifier\n element_index ::= integer |
index_string\n index_string ::= <any source character except
"]"> +\n conversion ::= "r" |
"s"\n format_spec ::= <described in the next
section>\n\nIn less formal terms, the replacement field can start with
a\n*field_name* that specifies the object whose value is to be
formatted\nand inserted into the output instead of the replacement field.
The\n*field_name* is optionally followed by a *conversion* field, which
is\npreceded by an exclamation point ``\'!\'``, and a
*format_spec*, which\nis preceded by a colon ``\':\'``. These
specify a non-default format\nfor the replacement value.\n\nSee also the
*Format Specification Mini-Language* section.\n\nThe *field_name* itself
begins with an *arg_name* that is either a\nnumber or a keyword. If
it\'s a number, it refers to a positional\nargument, and if it\'s
a keyword, it refers to a named keyword\nargument. If the numerical
arg_names in a format string are 0, 1, 2,\n... in sequence, they can all be
omitted (not just some) and the\nnumbers 0, 1, 2, ... will be automatically
inserted in that order.\nBecause *arg_name* is not quote-delimited, it is
not possible to\nspecify arbitrary dictionary keys (e.g., the strings
``\'10\'`` or\n``\':-]\'``) within a format string. The
*arg_name* can be followed by\nany number of index or attribute
expressions. An expression of the\nform ``\'.name\'`` selects the
named attribute using ``getattr()``,\nwhile an expression of the form
``\'[index]\'`` does an index lookup\nusing
``__getitem__()``.\n\nChanged in version 2.7: The positional argument
specifiers can be\nomitted, so ``\'{} {}\'`` is equivalent to
``\'{0} {1}\'``.\n\nSome simple format string examples:\n\n
"First, thou shalt count to {0}" # References first positional
argument\n "Bring me a {}" # Implicitly
references the first positional argument\n "From {} to {}"
# Same as "From {0} to {1}"\n "My quest is
{name}" # References keyword argument \'name\'\n
"Weight in tons {0.weight}" # \'weight\'
attribute of first positional arg\n "Units destroyed:
{players[0]}" # First element of keyword argument
\'players\'.\n\nThe *conversion* field causes a type coercion
before formatting.\nNormally, the job of formatting a value is done by
the\n``__format__()`` method of the value itself. However, in some
cases\nit is desirable to force a type to be formatted as a
string,\noverriding its own definition of formatting. By converting the
value\nto a string before calling ``__format__()``, the normal
formatting\nlogic is bypassed.\n\nTwo conversion flags are currently
supported: ``\'!s\'`` which calls\n``str()`` on the value, and
``\'!r\'`` which calls ``repr()``.\n\nSome examples:\n\n
"Harold\'s a clever {0!s}" # Calls str() on the
argument first\n "Bring out the holy {name!r}" # Calls
repr() on the argument first\n\nThe *format_spec* field contains a
specification of how the value\nshould be presented, including such details
as field width, alignment,\npadding, decimal precision and so on. Each
value type can define its\nown "formatting mini-language" or
interpretation of the *format_spec*.\n\nMost built-in types support a
common formatting mini-language, which\nis described in the next
section.\n\nA *format_spec* field can also include nested replacement
fields\nwithin it. These nested replacement fields can contain only a
field\nname; conversion flags and format specifications are not allowed.
The\nreplacement fields within the format_spec are substituted before
the\n*format_spec* string is interpreted. This allows the formatting of
a\nvalue to be dynamically specified.\n\nSee the *Format examples* section
for some examples.\n\n\nFormat Specification
Mini-Language\n==================================\n\n"Format
specifications" are used within replacement fields contained\nwithin a
format string to define how individual values are presented\n(see *Format
String Syntax*). They can also be passed directly to the\nbuilt-in
``format()`` function. Each formattable type may define how\nthe format
specification is to be interpreted.\n\nMost built-in types implement the
following options for format\nspecifications, although some of the
formatting options are only\nsupported by the numeric types.\n\nA general
convention is that an empty format string (``""``) produces\nthe
same result as if you had called ``str()`` on the value. A non-\nempty
format string typically modifies the result.\n\nThe general form of a
*standard format specifier* is:\n\n format_spec ::=
[[fill]align][sign][#][0][width][,][.precision][type]\n fill ::=
<any character>\n align ::= "<" |
">" | "=" | "^"\n sign ::=
"+" | "-" | " "\n width ::= integer\n
precision ::= integer\n type ::= "b" | "c"
| "d" | "e" | "E" | "f" |
"F" | "g" | "G" | "n" |
"o" | "s" | "x" | "X" |
"%"\n\nIf a valid *align* value is specified, it can be preceded
by a *fill*\ncharacter that can be any character and defaults to a space
if\nomitted. Note that it is not possible to use ``{`` and ``}`` as
*fill*\nchar while using the ``str.format()`` method; this limitation
however\ndoesn\'t affect the ``format()`` function.\n\nThe meaning of
the various alignment options is as follows:\n\n
+-----------+------------------------------------------------------------+\n
| Option | Meaning
|\n
+===========+============================================================+\n
| ``\'<\'`` | Forces the field to be left-aligned within
the available |\n | | space (this is the default for most
objects). |\n
+-----------+------------------------------------------------------------+\n
| ``\'>\'`` | Forces the field to be right-aligned within
the available |\n | | space (this is the default for numbers).
|\n
+-----------+------------------------------------------------------------+\n
| ``\'=\'`` | Forces the padding to be placed after the sign
(if any) |\n | | but before the digits. This is used for
printing fields |\n | | in the form \'+000000120\'.
This alignment option is only |\n | | valid for numeric
types. |\n
+-----------+------------------------------------------------------------+\n
| ``\'^\'`` | Forces the field to be centered within the
available |\n | | space.
|\n
+-----------+------------------------------------------------------------+\n\nNote
that unless a minimum field width is defined, the field width\nwill always
be the same size as the data to fill it, so that the\nalignment option has
no meaning in this case.\n\nThe *sign* option is only valid for number
types, and can be one of\nthe following:\n\n
+-----------+------------------------------------------------------------+\n
| Option | Meaning
|\n
+===========+============================================================+\n
| ``\'+\'`` | indicates that a sign should be used for both
positive as |\n | | well as negative numbers.
|\n
+-----------+------------------------------------------------------------+\n
| ``\'-\'`` | indicates that a sign should be used only for
negative |\n | | numbers (this is the default behavior).
|\n
+-----------+------------------------------------------------------------+\n
| space | indicates that a leading space should be used on positive
|\n | | numbers, and a minus sign on negative numbers.
|\n
+-----------+------------------------------------------------------------+\n\nThe
``\'#\'`` option is only valid for integers, and only for
binary,\noctal, or hexadecimal output. If present, it specifies that
the\noutput will be prefixed by ``\'0b\'``, ``\'0o\'``,
or ``\'0x\'``,\nrespectively.\n\nThe ``\',\'`` option
signals the use of a comma for a thousands\nseparator. For a locale aware
separator, use the ``\'n\'`` integer\npresentation type
instead.\n\nChanged in version 2.7: Added the ``\',\'`` option
(see also **PEP\n378**).\n\n*width* is a decimal integer defining the
minimum field width. If not\nspecified, then the field width will be
determined by the content.\n\nPreceding the *width* field by a zero
(``\'0\'``) character enables\nsign-aware zero-padding for
numeric types. This is equivalent to a\n*fill* character of
``\'0\'`` with an *alignment* type of ``\'=\'``.\n\nThe
*precision* is a decimal number indicating how many digits should\nbe
displayed after the decimal point for a floating point value\nformatted
with ``\'f\'`` and ``\'F\'``, or before and after the
decimal\npoint for a floating point value formatted with
``\'g\'`` or ``\'G\'``.\nFor non-number types the field
indicates the maximum field size - in\nother words, how many characters
will be used from the field content.\nThe *precision* is not allowed for
integer values.\n\nFinally, the *type* determines how the data should be
presented.\n\nThe available string presentation types are:\n\n
+-----------+------------------------------------------------------------+\n
| Type | Meaning
|\n
+===========+============================================================+\n
| ``\'s\'`` | String format. This is the default type for
strings and |\n | | may be omitted.
|\n
+-----------+------------------------------------------------------------+\n
| None | The same as ``\'s\'``.
|\n
+-----------+------------------------------------------------------------+\n\nThe
available integer presentation types are:\n\n
+-----------+------------------------------------------------------------+\n
| Type | Meaning
|\n
+===========+============================================================+\n
| ``\'b\'`` | Binary format. Outputs the number in base 2.
|\n
+-----------+------------------------------------------------------------+\n
| ``\'c\'`` | Character. Converts the integer to the
corresponding |\n | | unicode character before printing.
|\n
+-----------+------------------------------------------------------------+\n
| ``\'d\'`` | Decimal Integer. Outputs the number in base 10.
|\n
+-----------+------------------------------------------------------------+\n
| ``\'o\'`` | Octal format. Outputs the number in base 8.
|\n
+-----------+------------------------------------------------------------+\n
| ``\'x\'`` | Hex format. Outputs the number in base 16,
using lower- |\n | | case letters for the digits above 9.
|\n
+-----------+------------------------------------------------------------+\n
| ``\'X\'`` | Hex format. Outputs the number in base 16,
using upper- |\n | | case letters for the digits above 9.
|\n
+-----------+------------------------------------------------------------+\n
| ``\'n\'`` | Number. This is the same as
``\'d\'``, except that it uses |\n | | the current
locale setting to insert the appropriate |\n | | number
separator characters. |\n
+-----------+------------------------------------------------------------+\n
| None | The same as ``\'d\'``.
|\n
+-----------+------------------------------------------------------------+\n\nIn
addition to the above presentation types, integers can be formatted\nwith
the floating point presentation types listed below
(except\n``\'n\'`` and None). When doing so, ``float()`` is used
to convert the\ninteger to a floating point number before
formatting.\n\nThe available presentation types for floating point and
decimal values\nare:\n\n
+-----------+------------------------------------------------------------+\n
| Type | Meaning
|\n
+===========+============================================================+\n
| ``\'e\'`` | Exponent notation. Prints the number in
scientific |\n | | notation using the letter
\'e\' to indicate the exponent. |\n | | The
default precision is ``6``. |\n
+-----------+------------------------------------------------------------+\n
| ``\'E\'`` | Exponent notation. Same as ``\'e\'``
except it uses an upper |\n | | case \'E\' as the
separator character. |\n
+-----------+------------------------------------------------------------+\n
| ``\'f\'`` | Fixed point. Displays the number as a
fixed-point number. |\n | | The default precision is ``6``.
|\n
+-----------+------------------------------------------------------------+\n
| ``\'F\'`` | Fixed point. Same as ``\'f\'``.
|\n
+-----------+------------------------------------------------------------+\n
| ``\'g\'`` | General format. For a given precision ``p
>= 1``, this |\n | | rounds the number to ``p``
significant digits and then |\n | | formats the result in
either fixed-point format or in |\n | | scientific
notation, depending on its magnitude. The |\n | | precise
rules are as follows: suppose that the result |\n | |
formatted with presentation type ``\'e\'`` and precision |\n
| | ``p-1`` would have exponent ``exp``. Then if ``-4 <= exp
|\n | | < p``, the number is formatted with presentation
type |\n | | ``\'f\'`` and precision
``p-1-exp``. Otherwise, the number |\n | | is formatted with
presentation type ``\'e\'`` and precision |\n | |
``p-1``. In both cases insignificant trailing zeros are |\n |
| removed from the significand, and the decimal point is |\n |
| also removed if there are no remaining digits following |\n |
| it. Positive and negative infinity, positive and negative |\n |
| zero, and nans, are formatted as ``inf``, ``-inf``, ``0``, |\n
| | ``-0`` and ``nan`` respectively, regardless of the
|\n | | precision. A precision of ``0`` is treated as
equivalent |\n | | to a precision of ``1``. The default
precision is ``6``. |\n
+-----------+------------------------------------------------------------+\n
| ``\'G\'`` | General format. Same as ``\'g\'``
except switches to ``\'E\'`` |\n | | if the number
gets too large. The representations of |\n | | infinity
and NaN are uppercased, too. |\n
+-----------+------------------------------------------------------------+\n
| ``\'n\'`` | Number. This is the same as
``\'g\'``, except that it uses |\n | | the current
locale setting to insert the appropriate |\n | | number
separator characters. |\n
+-----------+------------------------------------------------------------+\n
| ``\'%\'`` | Percentage. Multiplies the number by 100 and
displays in |\n | | fixed (``\'f\'``) format,
followed by a percent sign. |\n
+-----------+------------------------------------------------------------+\n
| None | The same as ``\'g\'``.
|\n
+-----------+------------------------------------------------------------+\n\n\nFormat
examples\n===============\n\nThis section contains examples of the new
format syntax and comparison\nwith the old ``%``-formatting.\n\nIn most of
the cases the syntax is similar to the old\n``%``-formatting, with the
addition of the ``{}`` and with ``:`` used\ninstead of ``%``. For example,
``\'%03.2f\'`` can be translated
to\n``\'{:03.2f}\'``.\n\nThe new format syntax also supports new
and different options, shown\nin the follow examples.\n\nAccessing
arguments by position:\n\n >>> \'{0}, {1},
{2}\'.format(\'a\', \'b\', \'c\')\n
\'a, b, c\'\n >>> \'{}, {},
{}\'.format(\'a\', \'b\', \'c\') # 2.7+
only\n \'a, b, c\'\n >>> \'{2}, {1},
{0}\'.format(\'a\', \'b\', \'c\')\n
\'c, b, a\'\n >>> \'{2}, {1},
{0}\'.format(*\'abc\') # unpacking argument sequence\n
\'c, b, a\'\n >>>
\'{0}{1}{0}\'.format(\'abra\', \'cad\') #
arguments\' indices can be repeated\n
\'abracadabra\'\n\nAccessing arguments by name:\n\n
>>> \'Coordinates: {latitude},
{longitude}\'.format(latitude=\'37.24N\',
longitude=\'-115.81W\')\n \'Coordinates: 37.24N,
-115.81W\'\n >>> coord = {\'latitude\':
\'37.24N\', \'longitude\': \'-115.81W\'}\n
>>> \'Coordinates: {latitude},
{longitude}\'.format(**coord)\n \'Coordinates: 37.24N,
-115.81W\'\n\nAccessing arguments\' attributes:\n\n
>>> c = 3-5j\n >>> (\'The complex number {0} is
formed from the real part {0.real} \'\n ... \'and the
imaginary part {0.imag}.\').format(c)\n \'The complex number
(3-5j) is formed from the real part 3.0 and the imaginary part
-5.0.\'\n >>> class Point(object):\n ... def
__init__(self, x, y):\n ... self.x, self.y = x, y\n ... def
__str__(self):\n ... return \'Point({self.x},
{self.y})\'.format(self=self)\n ...\n >>> str(Point(4,
2))\n \'Point(4, 2)\'\n\nAccessing arguments\' items:\n\n
>>> coord = (3, 5)\n >>> \'X: {0[0]}; Y:
{0[1]}\'.format(coord)\n \'X: 3; Y: 5\'\n\nReplacing
``%s`` and ``%r``:\n\n >>> "repr() shows quotes: {!r};
str() doesn\'t: {!s}".format(\'test1\',
\'test2\')\n "repr() shows quotes: \'test1\';
str() doesn\'t: test2"\n\nAligning the text and specifying a
width:\n\n >>> \'{:<30}\'.format(\'left
aligned\')\n \'left aligned \'\n
>>> \'{:>30}\'.format(\'right aligned\')\n
\' right aligned\'\n >>>
\'{:^30}\'.format(\'centered\')\n \'
centered \'\n >>>
\'{:*^30}\'.format(\'centered\') # use \'*\'
as a fill char\n
\'***********centered***********\'\n\nReplacing ``%+f``, ``%-f``,
and ``% f`` and specifying a sign:\n\n >>> \'{:+f};
{:+f}\'.format(3.14, -3.14) # show it always\n \'+3.140000;
-3.140000\'\n >>> \'{: f}; {: f}\'.format(3.14,
-3.14) # show a space for positive numbers\n \' 3.140000;
-3.140000\'\n >>> \'{:-f}; {:-f}\'.format(3.14,
-3.14) # show only the minus -- same as \'{:f}; {:f}\'\n
\'3.140000; -3.140000\'\n\nReplacing ``%x`` and ``%o`` and
converting the value to different\nbases:\n\n >>> # format also
supports binary numbers\n >>> "int: {0:d}; hex: {0:x};
oct: {0:o}; bin: {0:b}".format(42)\n \'int: 42; hex: 2a;
oct: 52; bin: 101010\'\n >>> # with 0x, 0o, or 0b as
prefix:\n >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o};
bin: {0:#b}".format(42)\n \'int: 42; hex: 0x2a; oct: 0o52;
bin: 0b101010\'\n\nUsing the comma as a thousands separator:\n\n
>>> \'{:,}\'.format(1234567890)\n
\'1,234,567,890\'\n\nExpressing a percentage:\n\n >>>
points = 19.5\n >>> total = 22\n >>> \'Correct
answers: {:.2%}\'.format(points/total)\n \'Correct answers:
88.64%\'\n\nUsing type-specific formatting:\n\n >>> import
datetime\n >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\n
>>> \'{:%Y-%m-%d %H:%M:%S}\'.format(d)\n
\'2010-07-04 12:15:58\'\n\nNesting arguments and more complex
examples:\n\n >>> for align, text in
zip(\'<^>\', [\'left\', \'center\',
\'right\']):\n ...
\'{0:{fill}{align}16}\'.format(text, fill=align, align=align)\n
...\n
\'left<<<<<<<<<<<<\'\n
\'^^^^^center^^^^^\'\n
\'>>>>>>>>>>>right\'\n
>>>\n >>> octets = [192, 168, 0, 1]\n >>>
\'{:02X}{:02X}{:02X}{:02X}\'.format(*octets)\n
\'C0A80001\'\n >>> int(_, 16)\n 3232235521\n
>>>\n >>> width = 5\n >>> for num in
range(5,12):\n ... for base in \'dXob\':\n ...
print \'{0:{width}{base}}\'.format(num, base=base,
width=width),\n ... print\n ...\n 5 5 5 101\n
6 6 6 110\n 7 7 7 111\n 8 8 10
1000\n 9 9 11 1001\n 10 A 12 1010\n 11
B 13 1011\n',
'function': '\nFunction
definitions\n********************\n\nA function definition defines a
user-defined function object (see\nsection *The standard type
hierarchy*):\n\n decorated ::= decorators (classdef | funcdef)\n
decorators ::= decorator+\n decorator ::= "@"
dotted_name ["(" [argument_list [","]] ")"]
NEWLINE\n funcdef ::= "def" funcname "("
[parameter_list] ")" ":" suite\n dotted_name ::=
identifier ("." identifier)*\n parameter_list ::= (defparameter
",")*\n ( "*" identifier
["," "**" identifier]\n |
"**" identifier\n | defparameter
[","] )\n defparameter ::= parameter ["="
expression]\n sublist ::= parameter ("," parameter)*
[","]\n parameter ::= identifier | "(" sublist
")"\n funcname ::= identifier\n\nA function definition is
an executable statement. Its execution binds\nthe function name in the
current local namespace to a function object\n(a wrapper around the
executable code for the function). This\nfunction object contains a
reference to the current global namespace\nas the global namespace to be
used when the function is called.\n\nThe function definition does not
execute the function body; this gets\nexecuted only when the function is
called. [3]\n\nA function definition may be wrapped by one or more
*decorator*\nexpressions. Decorator expressions are evaluated when the
function is\ndefined, in the scope that contains the function definition.
The\nresult must be a callable, which is invoked with the function
object\nas the only argument. The returned value is bound to the function
name\ninstead of the function object. Multiple decorators are applied
in\nnested fashion. For example, the following code:\n\n @f1(arg)\n
@f2\n def func(): pass\n\nis equivalent to:\n\n def func(): pass\n
func = f1(arg)(f2(func))\n\nWhen one or more top-level *parameters* have
the form *parameter*\n``=`` *expression*, the function is said to have
"default parameter\nvalues." For a parameter with a default
value, the corresponding\n*argument* may be omitted from a call, in which
case the parameter\'s\ndefault value is substituted. If a parameter
has a default value, all\nfollowing parameters must also have a default
value --- this is a\nsyntactic restriction that is not expressed by the
grammar.\n\n**Default parameter values are evaluated when the function
definition\nis executed.** This means that the expression is evaluated
once, when\nthe function is defined, and that the same
"pre-computed" value is\nused for each call. This is especially
important to understand when a\ndefault parameter is a mutable object, such
as a list or a dictionary:\nif the function modifies the object (e.g. by
appending an item to a\nlist), the default value is in effect modified.
This is generally not\nwhat was intended. A way around this is to use
``None`` as the\ndefault, and explicitly test for it in the body of the
function, e.g.:\n\n def whats_on_the_telly(penguin=None):\n if
penguin is None:\n penguin = []\n
penguin.append("property of the zoo")\n return
penguin\n\nFunction call semantics are described in more detail in
section\n*Calls*. A function call always assigns values to all
parameters\nmentioned in the parameter list, either from position
arguments, from\nkeyword arguments, or from default values. If the
form\n"``*identifier``" is present, it is initialized to a tuple
receiving\nany excess positional parameters, defaulting to the empty tuple.
If\nthe form "``**identifier``" is present, it is initialized to
a new\ndictionary receiving any excess keyword arguments, defaulting to a
new\nempty dictionary.\n\nIt is also possible to create anonymous functions
(functions not bound\nto a name), for immediate use in expressions. This
uses lambda forms,\ndescribed in section *Lambdas*. Note that the lambda
form is merely a\nshorthand for a simplified function definition; a
function defined in\na "``def``" statement can be passed around
or assigned to another name\njust like a function defined by a lambda form.
The "``def``" form is\nactually more powerful since it allows
the execution of multiple\nstatements.\n\n**Programmer\'s note:**
Functions are first-class objects. A "``def``"\nform executed
inside a function definition defines a local function\nthat can be returned
or passed around. Free variables used in the\nnested function can access
the local variables of the function\ncontaining the def. See section
*Naming and binding* for details.\n',
'global': '\nThe ``global``
statement\n************************\n\n global_stmt ::=
"global" identifier ("," identifier)*\n\nThe ``global``
statement is a declaration which holds for the entire\ncurrent code block.
It means that the listed identifiers are to be\ninterpreted as globals. It
would be impossible to assign to a global\nvariable without ``global``,
although free variables may refer to\nglobals without being declared
global.\n\nNames listed in a ``global`` statement must not be used in the
same\ncode block textually preceding that ``global`` statement.\n\nNames
listed in a ``global`` statement must not be defined as formal\nparameters
or in a ``for`` loop control target, ``class`` definition,\nfunction
definition, or ``import`` statement.\n\n**CPython implementation detail:**
The current implementation does not\nenforce the latter two restrictions,
but programs should not abuse\nthis freedom, as future implementations may
enforce them or silently\nchange the meaning of the
program.\n\n**Programmer\'s note:** the ``global`` is a directive to
the parser.\nIt applies only to code parsed at the same time as the
``global``\nstatement. In particular, a ``global`` statement contained in
an\n``exec`` statement does not affect the code block *containing*
the\n``exec`` statement, and code contained in an ``exec`` statement
is\nunaffected by ``global`` statements in the code containing
the\n``exec`` statement. The same applies to the
``eval()``,\n``execfile()`` and ``compile()`` functions.\n',
'id-classes': '\nReserved classes of
identifiers\n*******************************\n\nCertain classes of
identifiers (besides keywords) have special\nmeanings. These classes are
identified by the patterns of leading and\ntrailing underscore
characters:\n\n``_*``\n Not imported by ``from module import *``. The
special identifier\n ``_`` is used in the interactive interpreter to
store the result of\n the last evaluation; it is stored in the
``__builtin__`` module.\n When not in interactive mode, ``_`` has no
special meaning and is\n not defined. See section *The import
statement*.\n\n Note: The name ``_`` is often used in conjunction with\n
internationalization; refer to the documentation for the\n
``gettext`` module for more information on this convention.\n\n``__*__``\n
System-defined names. These names are defined by the interpreter\n and
its implementation (including the standard library). Current\n system
names are discussed in the *Special method names* section\n and
elsewhere. More will likely be defined in future versions of\n Python.
*Any* use of ``__*__`` names, in any context, that does\n not follow
explicitly documented use, is subject to breakage\n without
warning.\n\n``__*``\n Class-private names. Names in this category, when
used within the\n context of a class definition, are re-written to use a
mangled form\n to help avoid name clashes between "private"
attributes of base and\n derived classes. See section *Identifiers
(Names)*.\n',
'identifiers': '\nIdentifiers and
keywords\n************************\n\nIdentifiers (also referred to as
*names*) are described by the\nfollowing lexical definitions:\n\n
identifier ::= (letter|"_") (letter | digit | "_")*\n
letter ::= lowercase | uppercase\n lowercase ::=
"a"..."z"\n uppercase ::=
"A"..."Z"\n digit ::=
"0"..."9"\n\nIdentifiers are unlimited in length. Case
is significant.\n\n\nKeywords\n========\n\nThe following identifiers are
used as reserved words, or *keywords* of\nthe language, and cannot be used
as ordinary identifiers. They must\nbe spelled exactly as written
here:\n\n and del from not while\n as
elif global or with\n assert else if pass
yield\n break except import print\n class exec in
raise\n continue finally is return\n def for
lambda try\n\nChanged in version 2.4: ``None`` became a constant and
is now\nrecognized by the compiler as a name for the built-in object
``None``.\nAlthough it is not a keyword, you cannot assign a different
object to\nit.\n\nChanged in version 2.5: Using ``as`` and ``with`` as
identifiers\ntriggers a warning. To use them as keywords, enable
the\n``with_statement`` future feature .\n\nChanged in version 2.6: ``as``
and ``with`` are full keywords.\n\n\nReserved classes of
identifiers\n===============================\n\nCertain classes of
identifiers (besides keywords) have special\nmeanings. These classes are
identified by the patterns of leading and\ntrailing underscore
characters:\n\n``_*``\n Not imported by ``from module import *``. The
special identifier\n ``_`` is used in the interactive interpreter to
store the result of\n the last evaluation; it is stored in the
``__builtin__`` module.\n When not in interactive mode, ``_`` has no
special meaning and is\n not defined. See section *The import
statement*.\n\n Note: The name ``_`` is often used in conjunction with\n
internationalization; refer to the documentation for the\n
``gettext`` module for more information on this convention.\n\n``__*__``\n
System-defined names. These names are defined by the interpreter\n and
its implementation (including the standard library). Current\n system
names are discussed in the *Special method names* section\n and
elsewhere. More will likely be defined in future versions of\n Python.
*Any* use of ``__*__`` names, in any context, that does\n not follow
explicitly documented use, is subject to breakage\n without
warning.\n\n``__*``\n Class-private names. Names in this category, when
used within the\n context of a class definition, are re-written to use a
mangled form\n to help avoid name clashes between "private"
attributes of base and\n derived classes. See section *Identifiers
(Names)*.\n',
'if': '\nThe ``if`` statement\n********************\n\nThe
``if`` statement is used for conditional execution:\n\n if_stmt ::=
"if" expression ":" suite\n (
"elif" expression ":" suite )*\n
["else" ":" suite]\n\nIt selects exactly one of the
suites by evaluating the expressions one\nby one until one is found to be
true (see section *Boolean operations*\nfor the definition of true and
false); then that suite is executed\n(and no other part of the ``if``
statement is executed or evaluated).\nIf all expressions are false, the
suite of the ``else`` clause, if\npresent, is executed.\n',
'imaginary': '\nImaginary
literals\n******************\n\nImaginary literals are described by the
following lexical definitions:\n\n imagnumber ::= (floatnumber | intpart)
("j" | "J")\n\nAn imaginary literal yields a complex
number with a real part of 0.0.\nComplex numbers are represented as a pair
of floating point numbers\nand have the same restrictions on their range.
To create a complex\nnumber with a nonzero real part, add a floating point
number to it,\ne.g., ``(3+4j)``. Some examples of imaginary literals:\n\n
3.14j 10.j 10j .001j 1e100j 3.14e-10j\n',
'import': '\nThe ``import``
statement\n************************\n\n import_stmt ::=
"import" module ["as" name] ( "," module
["as" name] )*\n | "from"
relative_module "import" identifier ["as" name]\n
( "," identifier ["as" name] )*\n
| "from" relative_module "import" "("
identifier ["as" name]\n ( ","
identifier ["as" name] )* [","] ")"\n
| "from" module "import" "*"\n
module ::= (identifier ".")* identifier\n
relative_module ::= "."* module | "."+\n name
::= identifier\n\nImport statements are executed in two steps: (1) find
a module, and\ninitialize it if necessary; (2) define a name or names in
the local\nnamespace (of the scope where the ``import`` statement occurs).
The\nstatement comes in two forms differing on whether it uses the
``from``\nkeyword. The first form (without ``from``) repeats these steps
for\neach identifier in the list. The form with ``from`` performs step
(1)\nonce, and then performs step (2) repeatedly.\n\nTo understand how step
(1) occurs, one must first understand how\nPython handles hierarchical
naming of modules. To help organize\nmodules and provide a hierarchy in
naming, Python has a concept of\npackages. A package can contain other
packages and modules while\nmodules cannot contain other modules or
packages. From a file system\nperspective, packages are directories and
modules are files. The\noriginal specification for packages is still
available to read,\nalthough minor details have changed since the writing
of that\ndocument.\n\nOnce the name of the module is known (unless
otherwise specified, the\nterm "module" will refer to both
packages and modules), searching for\nthe module or package can begin. The
first place checked is\n``sys.modules``, the cache of all modules that have
been imported\npreviously. If the module is found there then it is used in
step (2)\nof import.\n\nIf the module is not found in the cache, then
``sys.meta_path`` is\nsearched (the specification for ``sys.meta_path`` can
be found in\n**PEP 302**). The object is a list of *finder* objects which
are\nqueried in order as to whether they know how to load the module
by\ncalling their ``find_module()`` method with the name of the module.
If\nthe module happens to be contained within a package (as denoted by
the\nexistence of a dot in the name), then a second argument
to\n``find_module()`` is given as the value of the ``__path__``
attribute\nfrom the parent package (everything up to the last dot in the
name of\nthe module being imported). If a finder can find the module it
returns\na *loader* (discussed later) or returns ``None``.\n\nIf none of
the finders on ``sys.meta_path`` are able to find the\nmodule then some
implicitly defined finders are queried.\nImplementations of Python vary in
what implicit meta path finders are\ndefined. The one they all do define,
though, is one that handles\n``sys.path_hooks``,
``sys.path_importer_cache``, and ``sys.path``.\n\nThe implicit finder
searches for the requested module in the "paths"\nspecified in
one of two places ("paths" do not have to be file system\npaths).
If the module being imported is supposed to be contained\nwithin a package
then the second argument passed to ``find_module()``,\n``__path__`` on the
parent package, is used as the source of paths. If\nthe module is not
contained in a package then ``sys.path`` is used as\nthe source of
paths.\n\nOnce the source of paths is chosen it is iterated over to find
a\nfinder that can handle that path. The dict
at\n``sys.path_importer_cache`` caches finders for paths and is
checked\nfor a finder. If the path does not have a finder cached
then\n``sys.path_hooks`` is searched by calling each object in the list
with\na single argument of the path, returning a finder or
raises\n``ImportError``. If a finder is returned then it is cached
in\n``sys.path_importer_cache`` and then used for that path entry. If
no\nfinder can be found but the path exists then a value of ``None``
is\nstored in ``sys.path_importer_cache`` to signify that an
implicit,\nfile-based finder that handles modules stored as individual
files\nshould be used for that path. If the path does not exist then a
finder\nwhich always returns ``None`` is placed in the cache for the
path.\n\nIf no finder can find the module then ``ImportError`` is
raised.\nOtherwise some finder returned a loader whose ``load_module()``
method\nis called with the name of the module to load (see **PEP 302** for
the\noriginal definition of loaders). A loader has several
responsibilities\nto perform on a module it loads. First, if the module
already exists\nin ``sys.modules`` (a possibility if the loader is called
outside of\nthe import machinery) then it is to use that module for
initialization\nand not a new module. But if the module does not exist
in\n``sys.modules`` then it is to be added to that dict
before\ninitialization begins. If an error occurs during loading of the
module\nand it was added to ``sys.modules`` it is to be removed from the
dict.\nIf an error occurs but the module was already in ``sys.modules`` it
is\nleft in the dict.\n\nThe loader must set several attributes on the
module. ``__name__`` is\nto be set to the name of the module. ``__file__``
is to be the "path"\nto the file unless the module is built-in
(and thus listed in\n``sys.builtin_module_names``) in which case the
attribute is not set.\nIf what is being imported is a package then
``__path__`` is to be set\nto a list of paths to be searched when looking
for modules and\npackages contained within the package being imported.
``__package__``\nis optional but should be set to the name of package that
contains the\nmodule or package (the empty string is used for module not
contained\nin a package). ``__loader__`` is also optional but should be set
to\nthe loader object that is loading the module.\n\nIf an error occurs
during loading then the loader raises\n``ImportError`` if some other
exception is not already being\npropagated. Otherwise the loader returns
the module that was loaded\nand initialized.\n\nWhen step (1) finishes
without raising an exception, step (2) can\nbegin.\n\nThe first form of
``import`` statement binds the module name in the\nlocal namespace to the
module object, and then goes on to import the\nnext identifier, if any. If
the module name is followed by ``as``,\nthe name following ``as`` is used
as the local name for the module.\n\nThe ``from`` form does not bind the
module name: it goes through the\nlist of identifiers, looks each one of
them up in the module found in\nstep (1), and binds the name in the local
namespace to the object thus\nfound. As with the first form of ``import``,
an alternate local name\ncan be supplied by specifying "``as``
localname". If a name is not\nfound, ``ImportError`` is raised. If
the list of identifiers is\nreplaced by a star (``\'*\'``), all
public names defined in the module\nare bound in the local namespace of the
``import`` statement..\n\nThe *public names* defined by a module are
determined by checking the\nmodule\'s namespace for a variable named
``__all__``; if defined, it\nmust be a sequence of strings which are names
defined or imported by\nthat module. The names given in ``__all__`` are
all considered public\nand are required to exist. If ``__all__`` is not
defined, the set of\npublic names includes all names found in the
module\'s namespace which\ndo not begin with an underscore character
(``\'_\'``). ``__all__``\nshould contain the entire public API.
It is intended to avoid\naccidentally exporting items that are not part of
the API (such as\nlibrary modules which were imported and used within the
module).\n\nThe ``from`` form with ``*`` may only occur in a module scope.
If the\nwild card form of import --- ``import *`` --- is used in a
function\nand the function contains or is a nested block with free
variables,\nthe compiler will raise a ``SyntaxError``.\n\nWhen specifying
what module to import you do not have to specify the\nabsolute name of the
module. When a module or package is contained\nwithin another package it is
possible to make a relative import within\nthe same top package without
having to mention the package name. By\nusing leading dots in the specified
module or package after ``from``\nyou can specify how high to traverse up
the current package hierarchy\nwithout specifying exact names. One leading
dot means the current\npackage where the module making the import exists.
Two dots means up\none package level. Three dots is up two levels, etc. So
if you execute\n``from . import mod`` from a module in the ``pkg`` package
then you\nwill end up importing ``pkg.mod``. If you execute ``from
..subpkg2\nimport mod`` from within ``pkg.subpkg1`` you will
import\n``pkg.subpkg2.mod``. The specification for relative imports
is\ncontained within **PEP 328**.\n\n``importlib.import_module()`` is
provided to support applications that\ndetermine which modules need to be
loaded dynamically.\n\n\nFuture statements\n=================\n\nA *future
statement* is a directive to the compiler that a particular\nmodule should
be compiled using syntax or semantics that will be\navailable in a
specified future release of Python. The future\nstatement is intended to
ease migration to future versions of Python\nthat introduce incompatible
changes to the language. It allows use of\nthe new features on a
per-module basis before the release in which the\nfeature becomes
standard.\n\n future_statement ::= "from"
"__future__" "import" feature ["as" name]\n
("," feature ["as" name])*\n
| "from" "__future__"
"import" "(" feature ["as" name]\n
("," feature ["as" name])* [","]
")"\n feature ::= identifier\n name ::=
identifier\n\nA future statement must appear near the top of the module.
The only\nlines that can appear before a future statement are:\n\n* the
module docstring (if any),\n\n* comments,\n\n* blank lines, and\n\n* other
future statements.\n\nThe features recognized by Python 2.6 are
``unicode_literals``,\n``print_function``, ``absolute_import``,
``division``, ``generators``,\n``nested_scopes`` and ``with_statement``.
``generators``,\n``with_statement``, ``nested_scopes`` are redundant in
Python version\n2.6 and above because they are always enabled.\n\nA future
statement is recognized and treated specially at compile\ntime: Changes to
the semantics of core constructs are often\nimplemented by generating
different code. It may even be the case\nthat a new feature introduces new
incompatible syntax (such as a new\nreserved word), in which case the
compiler may need to parse the\nmodule differently. Such decisions cannot
be pushed off until\nruntime.\n\nFor any given release, the compiler knows
which feature names have\nbeen defined, and raises a compile-time error if
a future statement\ncontains a feature not known to it.\n\nThe direct
runtime semantics are the same as for any import statement:\nthere is a
standard module ``__future__``, described later, and it\nwill be imported
in the usual way at the time the future statement is\nexecuted.\n\nThe
interesting runtime semantics depend on the specific feature\nenabled by
the future statement.\n\nNote that there is nothing special about the
statement:\n\n import __future__ [as name]\n\nThat is not a future
statement; it\'s an ordinary import statement with\nno special
semantics or syntax restrictions.\n\nCode compiled by an ``exec`` statement
or calls to the built-in\nfunctions ``compile()`` and ``execfile()`` that
occur in a module\n``M`` containing a future statement will, by default,
use the new\nsyntax or semantics associated with the future statement.
This can,\nstarting with Python 2.2 be controlled by optional arguments
to\n``compile()`` --- see the documentation of that function for
details.\n\nA future statement typed at an interactive interpreter prompt
will\ntake effect for the rest of the interpreter session. If
an\ninterpreter is started with the *-i* option, is passed a script
name\nto execute, and the script includes a future statement, it will be
in\neffect in the interactive session started after the script
is\nexecuted.\n\nSee also:\n\n **PEP 236** - Back to the __future__\n
The original proposal for the __future__ mechanism.\n',
'in': '\nComparisons\n***********\n\nUnlike C, all
comparison operations in Python have the same priority,\nwhich is lower
than that of any arithmetic, shifting or bitwise\noperation. Also unlike
C, expressions like ``a < b < c`` have the\ninterpretation that is
conventional in mathematics:\n\n comparison ::= or_expr (
comp_operator or_expr )*\n comp_operator ::= "<" |
">" | "==" | ">=" | "<=" |
"<>" | "!="\n |
"is" ["not"] | ["not"]
"in"\n\nComparisons yield boolean values: ``True`` or
``False``.\n\nComparisons can be chained arbitrarily, e.g., ``x < y
<= z`` is\nequivalent to ``x < y and y <= z``, except that ``y``
is evaluated\nonly once (but in both cases ``z`` is not evaluated at all
when ``x <\ny`` is found to be false).\n\nFormally, if *a*, *b*, *c*,
..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison
operators, then ``a op1 b op2 c ... y\nopN z`` is equivalent to ``a op1 b
and b op2 c and ... y opN z``,\nexcept that each expression is evaluated at
most once.\n\nNote that ``a op1 b op2 c`` doesn\'t imply any kind of
comparison\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is
perfectly legal\n(though perhaps not pretty).\n\nThe forms ``<>`` and
``!=`` are equivalent; for consistency with C,\n``!=`` is preferred; where
``!=`` is mentioned below ``<>`` is also\naccepted. The ``<>``
spelling is considered obsolescent.\n\nThe operators ``<``, ``>``,
``==``, ``>=``, ``<=``, and ``!=`` compare\nthe values of two
objects. The objects need not have the same type.\nIf both are numbers,
they are converted to a common type. Otherwise,\nobjects of different
types *always* compare unequal, and are ordered\nconsistently but
arbitrarily. You can control comparison behavior of\nobjects of
non-built-in types by defining a ``__cmp__`` method or rich\ncomparison
methods like ``__gt__``, described in section *Special\nmethod
names*.\n\n(This unusual definition of comparison was used to simplify
the\ndefinition of operations like sorting and the ``in`` and ``not
in``\noperators. In the future, the comparison rules for objects
of\ndifferent types are likely to change.)\n\nComparison of objects of the
same type depends on the type:\n\n* Numbers are compared
arithmetically.\n\n* Strings are compared lexicographically using the
numeric equivalents\n (the result of the built-in function ``ord()``) of
their characters.\n Unicode and 8-bit strings are fully interoperable in
this behavior.\n [4]\n\n* Tuples and lists are compared lexicographically
using comparison of\n corresponding elements. This means that to compare
equal, each\n element must compare equal and the two sequences must be of
the same\n type and have the same length.\n\n If not equal, the sequences
are ordered the same as their first\n differing elements. For example,
``cmp([1,2,x], [1,2,y])`` returns\n the same as ``cmp(x,y)``. If the
corresponding element does not\n exist, the shorter sequence is ordered
first (for example, ``[1,2] <\n [1,2,3]``).\n\n* Mappings
(dictionaries) compare equal if and only if their sorted\n (key, value)
lists compare equal. [5] Outcomes other than equality\n are resolved
consistently, but are not otherwise defined. [6]\n\n* Most other objects of
built-in types compare unequal unless they are\n the same object; the
choice whether one object is considered smaller\n or larger than another
one is made arbitrarily but consistently\n within one execution of a
program.\n\nThe operators ``in`` and ``not in`` test for collection
membership.\n``x in s`` evaluates to true if *x* is a member of the
collection *s*,\nand false otherwise. ``x not in s`` returns the negation
of ``x in\ns``. The collection membership test has traditionally been bound
to\nsequences; an object is a member of a collection if the collection
is\na sequence and contains an element equal to that object. However,
it\nmake sense for many other object types to support membership
tests\nwithout being a sequence. In particular, dictionaries (for keys)
and\nsets support membership testing.\n\nFor the list and tuple types, ``x
in y`` is true if and only if there\nexists an index *i* such that ``x ==
y[i]`` is true.\n\nFor the Unicode and string types, ``x in y`` is true if
and only if\n*x* is a substring of *y*. An equivalent test is ``y.find(x)
!= -1``.\nNote, *x* and *y* need not be the same type; consequently,
``u\'ab\' in\n\'abc\'`` will return ``True``. Empty
strings are always considered to\nbe a substring of any other string, so
``"" in "abc"`` will return\n``True``.\n\nChanged in
version 2.3: Previously, *x* was required to be a string of\nlength
``1``.\n\nFor user-defined classes which define the ``__contains__()``
method,\n``x in y`` is true if and only if ``y.__contains__(x)`` is
true.\n\nFor user-defined classes which do not define ``__contains__()``
but do\ndefine ``__iter__()``, ``x in y`` is true if some value ``z`` with
``x\n== z`` is produced while iterating over ``y``. If an exception
is\nraised during the iteration, it is as if ``in`` raised that
exception.\n\nLastly, the old-style iteration protocol is tried: if a class
defines\n``__getitem__()``, ``x in y`` is true if and only if there is a
non-\nnegative integer index *i* such that ``x == y[i]``, and all
lower\ninteger indices do not raise ``IndexError`` exception. (If any
other\nexception is raised, it is as if ``in`` raised that
exception).\n\nThe operator ``not in`` is defined to have the inverse true
value of\n``in``.\n\nThe operators ``is`` and ``is not`` test for object
identity: ``x is\ny`` is true if and only if *x* and *y* are the same
object. ``x is\nnot y`` yields the inverse truth value. [7]\n',
'integers': '\nInteger and long integer
literals\n*********************************\n\nInteger and long integer
literals are described by the following\nlexical definitions:\n\n
longinteger ::= integer ("l" | "L")\n integer
::= decimalinteger | octinteger | hexinteger | bininteger\n
decimalinteger ::= nonzerodigit digit* | "0"\n octinteger
::= "0" ("o" | "O") octdigit+ | "0"
octdigit+\n hexinteger ::= "0" ("x" |
"X") hexdigit+\n bininteger ::= "0"
("b" | "B") bindigit+\n nonzerodigit ::=
"1"..."9"\n octdigit ::=
"0"..."7"\n bindigit ::= "0" |
"1"\n hexdigit ::= digit | "a"..."f"
| "A"..."F"\n\nAlthough both lower case
``\'l\'`` and upper case ``\'L\'`` are allowed
as\nsuffix for long integers, it is strongly recommended to always
use\n``\'L\'``, since the letter ``\'l\'`` looks too
much like the digit\n``\'1\'``.\n\nPlain integer literals that
are above the largest representable plain\ninteger (e.g., 2147483647 when
using 32-bit arithmetic) are accepted\nas if they were long integers
instead. [1] There is no limit for long\ninteger literals apart from what
can be stored in available memory.\n\nSome examples of plain integer
literals (first row) and long integer\nliterals (second and third
rows):\n\n 7 2147483647 0177\n 3L
79228162514264337593543950336L 0377L 0x100000000L\n
79228162514264337593543950336 0xdeadbeef\n',
'lambda': '\nLambdas\n*******\n\n lambda_form ::=
"lambda" [parameter_list]: expression\n old_lambda_form ::=
"lambda" [parameter_list]: old_expression\n\nLambda forms (lambda
expressions) have the same syntactic position as\nexpressions. They are a
shorthand to create anonymous functions; the\nexpression ``lambda
arguments: expression`` yields a function object.\nThe unnamed object
behaves like a function object defined with\n\n def name(arguments):\n
return expression\n\nSee section *Function definitions* for the syntax
of parameter lists.\nNote that functions created with lambda forms cannot
contain\nstatements.\n',
'lists': '\nList displays\n*************\n\nA list display
is a possibly empty series of expressions enclosed in\nsquare brackets:\n\n
list_display ::= "[" [expression_list |
list_comprehension] "]"\n list_comprehension ::= expression
list_for\n list_for ::= "for" target_list
"in" old_expression_list [list_iter]\n old_expression_list ::=
old_expression [("," old_expression)+ [","]]\n
old_expression ::= or_test | old_lambda_form\n list_iter
::= list_for | list_if\n list_if ::= "if"
old_expression [list_iter]\n\nA list display yields a new list object. Its
contents are specified\nby providing either a list of expressions or a list
comprehension.\nWhen a comma-separated list of expressions is supplied, its
elements\nare evaluated from left to right and placed into the list object
in\nthat order. When a list comprehension is supplied, it consists of
a\nsingle expression followed by at least one ``for`` clause and zero
or\nmore ``for`` or ``if`` clauses. In this case, the elements of the
new\nlist are those that would be produced by considering each of
the\n``for`` or ``if`` clauses a block, nesting from left to right,
and\nevaluating the expression to produce a list element each time
the\ninnermost block is reached [1].\n',
'naming': "\nNaming and
binding\n******************\n\n*Names* refer to objects. Names are
introduced by name binding\noperations. Each occurrence of a name in the
program text refers to\nthe *binding* of that name established in the
innermost function block\ncontaining the use.\n\nA *block* is a piece of
Python program text that is executed as a\nunit. The following are blocks:
a module, a function body, and a class\ndefinition. Each command typed
interactively is a block. A script\nfile (a file given as standard input
to the interpreter or specified\non the interpreter command line the first
argument) is a code block.\nA script command (a command specified on the
interpreter command line\nwith the '**-c**' option) is a code
block. The file read by the\nbuilt-in function ``execfile()`` is a code
block. The string argument\npassed to the built-in function ``eval()`` and
to the ``exec``\nstatement is a code block. The expression read and
evaluated by the\nbuilt-in function ``input()`` is a code block.\n\nA code
block is executed in an *execution frame*. A frame contains\nsome
administrative information (used for debugging) and determines\nwhere and
how execution continues after the code block's execution
has\ncompleted.\n\nA *scope* defines the visibility of a name within a
block. If a local\nvariable is defined in a block, its scope includes that
block. If the\ndefinition occurs in a function block, the scope extends to
any blocks\ncontained within the defining one, unless a contained block
introduces\na different binding for the name. The scope of names defined
in a\nclass block is limited to the class block; it does not extend to
the\ncode blocks of methods -- this includes generator expressions
since\nthey are implemented using a function scope. This means that
the\nfollowing will fail:\n\n class A:\n a = 42\n b = list(a
+ i for i in range(10))\n\nWhen a name is used in a code block, it is
resolved using the nearest\nenclosing scope. The set of all such scopes
visible to a code block\nis called the block's *environment*.\n\nIf a
name is bound in a block, it is a local variable of that block.\nIf a name
is bound at the module level, it is a global variable. (The\nvariables of
the module code block are local and global.) If a\nvariable is used in a
code block but not defined there, it is a *free\nvariable*.\n\nWhen a name
is not found at all, a ``NameError`` exception is raised.\nIf the name
refers to a local variable that has not been bound,
a\n``UnboundLocalError`` exception is raised. ``UnboundLocalError`` is
a\nsubclass of ``NameError``.\n\nThe following constructs bind names:
formal parameters to functions,\n``import`` statements, class and function
definitions (these bind the\nclass or function name in the defining block),
and targets that are\nidentifiers if occurring in an assignment, ``for``
loop header, in the\nsecond position of an ``except`` clause header or
after ``as`` in a\n``with`` statement. The ``import`` statement of the
form ``from ...\nimport *`` binds all names defined in the imported module,
except\nthose beginning with an underscore. This form may only be used at
the\nmodule level.\n\nA target occurring in a ``del`` statement is also
considered bound for\nthis purpose (though the actual semantics are to
unbind the name). It\nis illegal to unbind a name that is referenced by an
enclosing scope;\nthe compiler will report a ``SyntaxError``.\n\nEach
assignment or import statement occurs within a block defined by a\nclass or
function definition or at the module level (the top-level\ncode
block).\n\nIf a name binding operation occurs anywhere within a code block,
all\nuses of the name within the block are treated as references to
the\ncurrent block. This can lead to errors when a name is used within
a\nblock before it is bound. This rule is subtle. Python
lacks\ndeclarations and allows name binding operations to occur
anywhere\nwithin a code block. The local variables of a code block can
be\ndetermined by scanning the entire text of the block for name
binding\noperations.\n\nIf the global statement occurs within a block, all
uses of the name\nspecified in the statement refer to the binding of that
name in the\ntop-level namespace. Names are resolved in the top-level
namespace by\nsearching the global namespace, i.e. the namespace of the
module\ncontaining the code block, and the builtins namespace, the
namespace\nof the module ``__builtin__``. The global namespace is
searched\nfirst. If the name is not found there, the builtins namespace
is\nsearched. The global statement must precede all uses of the
name.\n\nThe builtins namespace associated with the execution of a code
block\nis actually found by looking up the name ``__builtins__`` in
its\nglobal namespace; this should be a dictionary or a module (in
the\nlatter case the module's dictionary is used). By default, when
in the\n``__main__`` module, ``__builtins__`` is the built-in
module\n``__builtin__`` (note: no 's'); when in any other
module,\n``__builtins__`` is an alias for the dictionary of the
``__builtin__``\nmodule itself. ``__builtins__`` can be set to a
user-created\ndictionary to create a weak form of restricted
execution.\n\n**CPython implementation detail:** Users should not
touch\n``__builtins__``; it is strictly an implementation detail.
Users\nwanting to override values in the builtins namespace should
``import``\nthe ``__builtin__`` (no 's') module and modify its
attributes\nappropriately.\n\nThe namespace for a module is automatically
created the first time a\nmodule is imported. The main module for a script
is always called\n``__main__``.\n\nThe ``global`` statement has the same
scope as a name binding\noperation in the same block. If the nearest
enclosing scope for a\nfree variable contains a global statement, the free
variable is\ntreated as a global.\n\nA class definition is an executable
statement that may use and define\nnames. These references follow the
normal rules for name resolution.\nThe namespace of the class definition
becomes the attribute dictionary\nof the class. Names defined at the class
scope are not visible in\nmethods.\n\n\nInteraction with dynamic
features\n=================================\n\nThere are several cases
where Python statements are illegal when used\nin conjunction with nested
scopes that contain free variables.\n\nIf a variable is referenced in an
enclosing scope, it is illegal to\ndelete the name. An error will be
reported at compile time.\n\nIf the wild card form of import --- ``import
*`` --- is used in a\nfunction and the function contains or is a nested
block with free\nvariables, the compiler will raise a
``SyntaxError``.\n\nIf ``exec`` is used in a function and the function
contains or is a\nnested block with free variables, the compiler will raise
a\n``SyntaxError`` unless the exec explicitly specifies the
local\nnamespace for the ``exec``. (In other words, ``exec obj`` would
be\nillegal, but ``exec obj in ns`` would be legal.)\n\nThe ``eval()``,
``execfile()``, and ``input()`` functions and the\n``exec`` statement do
not have access to the full environment for\nresolving names. Names may be
resolved in the local and global\nnamespaces of the caller. Free variables
are not resolved in the\nnearest enclosing namespace, but in the global
namespace. [1] The\n``exec`` statement and the ``eval()`` and
``execfile()`` functions\nhave optional arguments to override the global
and local namespace.\nIf only one namespace is specified, it is used for
both.\n",
'numbers': "\nNumeric literals\n****************\n\nThere
are four types of numeric literals: plain integers, long\nintegers,
floating point numbers, and imaginary numbers. There are no\ncomplex
literals (complex numbers can be formed by adding a real\nnumber and an
imaginary number).\n\nNote that numeric literals do not include a sign; a
phrase like ``-1``\nis actually an expression composed of the unary
operator '``-``' and\nthe literal ``1``.\n",
'numeric-types': '\nEmulating numeric
types\n***********************\n\nThe following methods can be defined to
emulate numeric objects.\nMethods corresponding to operations that are not
supported by the\nparticular kind of number implemented (e.g., bitwise
operations for\nnon-integral numbers) should be left
undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self,
other)\nobject.__mul__(self, other)\nobject.__floordiv__(self,
other)\nobject.__mod__(self, other)\nobject.__divmod__(self,
other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self,
other)\nobject.__rshift__(self, other)\nobject.__and__(self,
other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n These
methods are called to implement the binary arithmetic\n operations
(``+``, ``-``, ``*``, ``//``, ``%``, ``divmod()``,\n ``pow()``, ``**``,
``<<``, ``>>``, ``&``, ``^``, ``|``). For\n instance, to
evaluate the expression ``x + y``, where *x* is an\n instance of a class
that has an ``__add__()`` method,\n ``x.__add__(y)`` is called. The
``__divmod__()`` method should be\n the equivalent to using
``__floordiv__()`` and ``__mod__()``; it\n should not be related to
``__truediv__()`` (described below). Note\n that ``__pow__()`` should be
defined to accept an optional third\n argument if the ternary version of
the built-in ``pow()`` function\n is to be supported.\n\n If one of
those methods does not support the operation with the\n supplied
arguments, it should return ``NotImplemented``.\n\nobject.__div__(self,
other)\nobject.__truediv__(self, other)\n\n The division operator (``/``)
is implemented by these methods. The\n ``__truediv__()`` method is used
when ``__future__.division`` is in\n effect, otherwise ``__div__()`` is
used. If only one of these two\n methods is defined, the object will not
support division in the\n alternate context; ``TypeError`` will be raised
instead.\n\nobject.__radd__(self, other)\nobject.__rsub__(self,
other)\nobject.__rmul__(self, other)\nobject.__rdiv__(self,
other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self,
other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self,
other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self,
other)\nobject.__rrshift__(self, other)\nobject.__rand__(self,
other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n
These methods are called to implement the binary arithmetic\n operations
(``+``, ``-``, ``*``, ``/``, ``%``, ``divmod()``,\n ``pow()``, ``**``,
``<<``, ``>>``, ``&``, ``^``, ``|``) with\n reflected
(swapped) operands. These functions are only called if\n the left
operand does not support the corresponding operation and\n the operands
are of different types. [2] For instance, to evaluate\n the expression
``x - y``, where *y* is an instance of a class that\n has an
``__rsub__()`` method, ``y.__rsub__(x)`` is called if\n ``x.__sub__(y)``
returns *NotImplemented*.\n\n Note that ternary ``pow()`` will not try
calling ``__rpow__()``\n (the coercion rules would become too
complicated).\n\n Note: If the right operand\'s type is a subclass
of the left operand\'s\n type and that subclass provides the
reflected method for the\n operation, this method will be called before
the left operand\'s\n non-reflected method. This behavior allows
subclasses to\n override their ancestors\'
operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self,
other)\nobject.__imul__(self, other)\nobject.__idiv__(self,
other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self,
other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[,
modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self,
other)\nobject.__iand__(self, other)\nobject.__ixor__(self,
other)\nobject.__ior__(self, other)\n\n These methods are called to
implement the augmented arithmetic\n assignments (``+=``, ``-=``, ``*=``,
``/=``, ``//=``, ``%=``,\n ``**=``, ``<<=``, ``>>=``,
``&=``, ``^=``, ``|=``). These methods\n should attempt to do the
operation in-place (modifying *self*) and\n return the result (which
could be, but does not have to be,\n *self*). If a specific method is
not defined, the augmented\n assignment falls back to the normal methods.
For instance, to\n execute the statement ``x += y``, where *x* is an
instance of a\n class that has an ``__iadd__()`` method,
``x.__iadd__(y)`` is\n called. If *x* is an instance of a class that
does not define a\n ``__iadd__()`` method, ``x.__add__(y)`` and
``y.__radd__(x)`` are\n considered, as with the evaluation of ``x +
y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n
Called to implement the unary arithmetic operations (``-``, ``+``,\n
``abs()`` and
``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__long__(self)\nobject.__float__(self)\n\n
Called to implement the built-in functions ``complex()``,\n ``int()``,
``long()``, and ``float()``. Should return a value of\n the appropriate
type.\n\nobject.__oct__(self)\nobject.__hex__(self)\n\n Called to
implement the built-in functions ``oct()`` and ``hex()``.\n Should return
a string value.\n\nobject.__index__(self)\n\n Called to implement
``operator.index()``. Also called whenever\n Python needs an integer
object (such as in slicing). Must return\n an integer (int or long).\n\n
New in version 2.5.\n\nobject.__coerce__(self, other)\n\n Called to
implement "mixed-mode" numeric arithmetic. Should either\n
return a 2-tuple containing *self* and *other* converted to a\n common
numeric type, or ``None`` if conversion is impossible. When\n the common
type would be the type of ``other``, it is sufficient to\n return
``None``, since the interpreter will also ask the other\n object to
attempt a coercion (but sometimes, if the implementation\n of the other
type cannot be changed, it is useful to do the\n conversion to the other
type here). A return value of\n ``NotImplemented`` is equivalent to
returning ``None``.\n',
'objects': '\nObjects, values and
types\n*************************\n\n*Objects* are Python\'s
abstraction for data. All data in a Python\nprogram is represented by
objects or by relations between objects. (In\na sense, and in conformance
to Von Neumann\'s model of a "stored\nprogram computer,"
code is also represented by objects.)\n\nEvery object has an identity, a
type and a value. An object\'s\n*identity* never changes once it has
been created; you may think of it\nas the object\'s address in memory.
The \'``is``\' operator compares the\nidentity of two objects;
the ``id()`` function returns an integer\nrepresenting its identity
(currently implemented as its address). An\nobject\'s *type* is also
unchangeable. [1] An object\'s type determines\nthe operations that
the object supports (e.g., "does it have a\nlength?") and also
defines the possible values for objects of that\ntype. The ``type()``
function returns an object\'s type (which is an\nobject itself). The
*value* of some objects can change. Objects\nwhose value can change are
said to be *mutable*; objects whose value\nis unchangeable once they are
created are called *immutable*. (The\nvalue of an immutable container
object that contains a reference to a\nmutable object can change when the
latter\'s value is changed; however\nthe container is still considered
immutable, because the collection of\nobjects it contains cannot be
changed. So, immutability is not\nstrictly the same as having an
unchangeable value, it is more subtle.)\nAn object\'s mutability is
determined by its type; for instance,\nnumbers, strings and tuples are
immutable, while dictionaries and\nlists are mutable.\n\nObjects are never
explicitly destroyed; however, when they become\nunreachable they may be
garbage-collected. An implementation is\nallowed to postpone garbage
collection or omit it altogether --- it is\na matter of implementation
quality how garbage collection is\nimplemented, as long as no objects are
collected that are still\nreachable.\n\n**CPython implementation detail:**
CPython currently uses a reference-\ncounting scheme with (optional)
delayed detection of cyclically linked\ngarbage, which collects most
objects as soon as they become\nunreachable, but is not guaranteed to
collect garbage containing\ncircular references. See the documentation of
the ``gc`` module for\ninformation on controlling the collection of cyclic
garbage. Other\nimplementations act differently and CPython may change. Do
not depend\non immediate finalization of objects when they become
unreachable (ex:\nalways close files).\n\nNote that the use of the
implementation\'s tracing or debugging\nfacilities may keep objects
alive that would normally be collectable.\nAlso note that catching an
exception with a \'``try``...``except``\'\nstatement may keep
objects alive.\n\nSome objects contain references to "external"
resources such as open\nfiles or windows. It is understood that these
resources are freed\nwhen the object is garbage-collected, but since
garbage collection is\nnot guaranteed to happen, such objects also provide
an explicit way to\nrelease the external resource, usually a ``close()``
method. Programs\nare strongly recommended to explicitly close such
objects. The\n\'``try``...``finally``\' statement provides a
convenient way to do\nthis.\n\nSome objects contain references to other
objects; these are called\n*containers*. Examples of containers are tuples,
lists and\ndictionaries. The references are part of a container\'s
value. In\nmost cases, when we talk about the value of a container, we
imply the\nvalues, not the identities of the contained objects; however,
when we\ntalk about the mutability of a container, only the identities of
the\nimmediately contained objects are implied. So, if an
immutable\ncontainer (like a tuple) contains a reference to a mutable
object, its\nvalue changes if that mutable object is changed.\n\nTypes
affect almost all aspects of object behavior. Even the\nimportance of
object identity is affected in some sense: for immutable\ntypes, operations
that compute new values may actually return a\nreference to any existing
object with the same type and value, while\nfor mutable objects this is not
allowed. E.g., after ``a = 1; b =\n1``, ``a`` and ``b`` may or may not
refer to the same object with the\nvalue one, depending on the
implementation, but after ``c = []; d =\n[]``, ``c`` and ``d`` are
guaranteed to refer to two different,\nunique, newly created empty lists.
(Note that ``c = d = []`` assigns\nthe same object to both ``c`` and
``d``.)\n',
'operator-summary': '\nOperator
precedence\n*******************\n\nThe following table summarizes the
operator precedences in Python,\nfrom lowest precedence (least binding) to
highest precedence (most\nbinding). Operators in the same box have the same
precedence. Unless\nthe syntax is explicitly given, operators are binary.
Operators in\nthe same box group left to right (except for comparisons,
including\ntests, which all have the same precedence and chain from left to
right\n--- see section *Comparisons* --- and exponentiation, which
groups\nfrom right to
left).\n\n+-------------------------------------------------+---------------------------------------+\n|
Operator | Description
|\n+=================================================+=======================================+\n|
``lambda`` | Lambda expression
|\n+-------------------------------------------------+---------------------------------------+\n|
``if`` -- ``else`` | Conditional expression
|\n+-------------------------------------------------+---------------------------------------+\n|
``or`` | Boolean OR
|\n+-------------------------------------------------+---------------------------------------+\n|
``and`` | Boolean AND
|\n+-------------------------------------------------+---------------------------------------+\n|
``not`` ``x`` | Boolean NOT
|\n+-------------------------------------------------+---------------------------------------+\n|
``in``, ``not in``, ``is``, ``is not``, ``<``, | Comparisons, including
membership |\n| ``<=``, ``>``, ``>=``, ``<>``, ``!=``,
``==`` | tests and identity tests
|\n+-------------------------------------------------+---------------------------------------+\n|
``|`` | Bitwise OR
|\n+-------------------------------------------------+---------------------------------------+\n|
``^`` | Bitwise XOR
|\n+-------------------------------------------------+---------------------------------------+\n|
``&`` | Bitwise AND
|\n+-------------------------------------------------+---------------------------------------+\n|
``<<``, ``>>`` | Shifts
|\n+-------------------------------------------------+---------------------------------------+\n|
``+``, ``-`` | Addition and subtraction
|\n+-------------------------------------------------+---------------------------------------+\n|
``*``, ``/``, ``//``, ``%`` | Multiplication, division,
remainder |\n| | [8]
|\n+-------------------------------------------------+---------------------------------------+\n|
``+x``, ``-x``, ``~x`` | Positive, negative,
bitwise NOT
|\n+-------------------------------------------------+---------------------------------------+\n|
``**`` | Exponentiation [9]
|\n+-------------------------------------------------+---------------------------------------+\n|
``x[index]``, ``x[index:index]``, | Subscription, slicing,
call, |\n| ``x(arguments...)``, ``x.attribute`` |
attribute reference
|\n+-------------------------------------------------+---------------------------------------+\n|
``(expressions...)``, ``[expressions...]``, | Binding or tuple display,
list |\n| ``{key: value...}``, ```expressions...``` | display,
dictionary display, string |\n|
| conversion
|\n+-------------------------------------------------+---------------------------------------+\n\n-[
Footnotes ]-\n\n[1] In Python 2.3 and later releases, a list comprehension
"leaks" the\n control variables of each ``for`` it contains
into the containing\n scope. However, this behavior is deprecated, and
relying on it\n will not work in Python 3.\n\n[2] While ``abs(x%y) <
abs(y)`` is true mathematically, for floats it\n may not be true
numerically due to roundoff. For example, and\n assuming a platform on
which a Python float is an IEEE 754 double-\n precision number, in order
that ``-1e-100 % 1e100`` have the same\n sign as ``1e100``, the computed
result is ``-1e-100 + 1e100``,\n which is numerically exactly equal to
``1e100``. The function\n ``math.fmod()`` returns a result whose sign
matches the sign of\n the first argument instead, and so returns
``-1e-100`` in this\n case. Which approach is more appropriate depends
on the\n application.\n\n[3] If x is very close to an exact integer
multiple of y, it\'s\n possible for ``floor(x/y)`` to be one larger
than ``(x-x%y)/y``\n due to rounding. In such cases, Python returns the
latter result,\n in order to preserve that ``divmod(x,y)[0] * y + x %
y`` be very\n close to ``x``.\n\n[4] While comparisons between unicode
strings make sense at the byte\n level, they may be counter-intuitive to
users. For example, the\n strings ``u"\\u00C7"`` and
``u"\\u0043\\u0327"`` compare differently,\n even though they
both represent the same unicode character (LATIN\n CAPITAL LETTER C WITH
CEDILLA). To compare strings in a human\n recognizable way, compare
using ``unicodedata.normalize()``.\n\n[5] The implementation computes this
efficiently, without constructing\n lists or sorting.\n\n[6] Earlier
versions of Python used lexicographic comparison of the\n sorted (key,
value) lists, but this was very expensive for the\n common case of
comparing for equality. An even earlier version of\n Python compared
dictionaries by identity only, but this caused\n surprises because
people expected to be able to test a dictionary\n for emptiness by
comparing it to ``{}``.\n\n[7] Due to automatic garbage-collection, free
lists, and the dynamic\n nature of descriptors, you may notice seemingly
unusual behaviour\n in certain uses of the ``is`` operator, like those
involving\n comparisons between instance methods, or constants. Check
their\n documentation for more info.\n\n[8] The ``%`` operator is also
used for string formatting; the same\n precedence applies.\n\n[9] The
power operator ``**`` binds less tightly than an arithmetic or\n bitwise
unary operator on its right, that is, ``2**-1`` is\n ``0.5``.\n',
'pass': '\nThe ``pass``
statement\n**********************\n\n pass_stmt ::=
"pass"\n\n``pass`` is a null operation --- when it is executed,
nothing happens.\nIt is useful as a placeholder when a statement is
required\nsyntactically, but no code needs to be executed, for example:\n\n
def f(arg): pass # a function that does nothing (yet)\n\n class C:
pass # a class with no methods (yet)\n',
'power': '\nThe power operator\n******************\n\nThe
power operator binds more tightly than unary operators on its\nleft; it
binds less tightly than unary operators on its right. The\nsyntax is:\n\n
power ::= primary ["**" u_expr]\n\nThus, in an unparenthesized
sequence of power and unary operators, the\noperators are evaluated from
right to left (this does not constrain\nthe evaluation order for the
operands): ``-1**2`` results in ``-1``.\n\nThe power operator has the same
semantics as the built-in ``pow()``\nfunction, when called with two
arguments: it yields its left argument\nraised to the power of its right
argument. The numeric arguments are\nfirst converted to a common type.
The result type is that of the\narguments after coercion.\n\nWith mixed
operand types, the coercion rules for binary arithmetic\noperators apply.
For int and long int operands, the result has the\nsame type as the
operands (after coercion) unless the second argument\nis negative; in that
case, all arguments are converted to float and a\nfloat result is
delivered. For example, ``10**2`` returns ``100``, but\n``10**-2`` returns
``0.01``. (This last feature was added in Python\n2.2. In Python 2.1 and
before, if both arguments were of integer types\nand the second argument
was negative, an exception was raised).\n\nRaising ``0.0`` to a negative
power results in a\n``ZeroDivisionError``. Raising a negative number to a
fractional power\nresults in a ``ValueError``.\n',
'print': '\nThe ``print``
statement\n***********************\n\n print_stmt ::= "print"
([expression ("," expression)* [","]]\n
| ">>" expression [("," expression)+
[","]])\n\n``print`` evaluates each expression in turn and writes
the resulting\nobject to standard output (see below). If an object is not
a string,\nit is first converted to a string using the rules for
string\nconversions. The (resulting or original) string is then written.
A\nspace is written before each object is (converted and) written,
unless\nthe output system believes it is positioned at the beginning of
a\nline. This is the case (1) when no characters have yet been written\nto
standard output, (2) when the last character written to standard\noutput is
a whitespace character except ``\' \'``, or (3) when the
last\nwrite operation on standard output was not a ``print`` statement.
(In\nsome cases it may be functional to write an empty string to
standard\noutput for this reason.)\n\nNote: Objects which act like file
objects but which are not the built-in\n file objects often do not
properly emulate this aspect of the file\n object\'s behavior, so it
is best not to rely on this.\n\nA ``\'\\n\'`` character is
written at the end, unless the ``print``\nstatement ends with a comma.
This is the only action if the statement\ncontains just the keyword
``print``.\n\nStandard output is defined as the file object named
``stdout`` in the\nbuilt-in module ``sys``. If no such object exists, or
if it does not\nhave a ``write()`` method, a ``RuntimeError`` exception is
raised.\n\n``print`` also has an extended form, defined by the second
portion of\nthe syntax described above. This form is sometimes referred to
as\n"``print`` chevron." In this form, the first expression after
the\n``>>`` must evaluate to a "file-like" object,
specifically an object\nthat has a ``write()`` method as described above.
With this extended\nform, the subsequent expressions are printed to this
file object. If\nthe first expression evaluates to ``None``, then
``sys.stdout`` is\nused as the file for output.\n',
'raise': '\nThe ``raise``
statement\n***********************\n\n raise_stmt ::= "raise"
[expression ["," expression ["," expression]]]\n\nIf no
expressions are present, ``raise`` re-raises the last exception\nthat was
active in the current scope. If no exception is active in\nthe current
scope, a ``TypeError`` exception is raised indicating that\nthis is an
error (if running under IDLE, a ``Queue.Empty`` exception\nis raised
instead).\n\nOtherwise, ``raise`` evaluates the expressions to get three
objects,\nusing ``None`` as the value of omitted expressions. The first
two\nobjects are used to determine the *type* and *value* of the
exception.\n\nIf the first object is an instance, the type of the exception
is the\nclass of the instance, the instance itself is the value, and
the\nsecond object must be ``None``.\n\nIf the first object is a class, it
becomes the type of the exception.\nThe second object is used to determine
the exception value: If it is\nan instance of the class, the instance
becomes the exception value. If\nthe second object is a tuple, it is used
as the argument list for the\nclass constructor; if it is ``None``, an
empty argument list is used,\nand any other object is treated as a single
argument to the\nconstructor. The instance so created by calling the
constructor is\nused as the exception value.\n\nIf a third object is
present and not ``None``, it must be a traceback\nobject (see section *The
standard type hierarchy*), and it is\nsubstituted instead of the current
location as the place where the\nexception occurred. If the third object
is present and not a\ntraceback object or ``None``, a ``TypeError``
exception is raised.\nThe three-expression form of ``raise`` is useful to
re-raise an\nexception transparently in an except clause, but ``raise``
with no\nexpressions should be preferred if the exception to be re-raised
was\nthe most recently active exception in the current scope.\n\nAdditional
information on exceptions can be found in section\n*Exceptions*, and
information about handling exceptions is in section\n*The try
statement*.\n',
'return': '\nThe ``return``
statement\n************************\n\n return_stmt ::=
"return" [expression_list]\n\n``return`` may only occur
syntactically nested in a function\ndefinition, not within a nested class
definition.\n\nIf an expression list is present, it is evaluated, else
``None`` is\nsubstituted.\n\n``return`` leaves the current function call
with the expression list\n(or ``None``) as return value.\n\nWhen ``return``
passes control out of a ``try`` statement with a\n``finally`` clause, that
``finally`` clause is executed before really\nleaving the function.\n\nIn a
generator function, the ``return`` statement is not allowed to\ninclude an
``expression_list``. In that context, a bare ``return``\nindicates that
the generator is done and will cause ``StopIteration``\nto be
raised.\n',
'sequence-types': "\nEmulating container
types\n*************************\n\nThe following methods can be defined to
implement container objects.\nContainers usually are sequences (such as
lists or tuples) or mappings\n(like dictionaries), but can represent other
containers as well. The\nfirst set of methods is used either to emulate a
sequence or to\nemulate a mapping; the difference is that for a sequence,
the\nallowable keys should be the integers *k* for which ``0 <= k <
N``\nwhere *N* is the length of the sequence, or slice objects,
which\ndefine a range of items. (For backwards compatibility, the
method\n``__getslice__()`` (see below) can also be defined to handle
simple,\nbut not extended slices.) It is also recommended that mappings
provide\nthe methods ``keys()``, ``values()``, ``items()``,
``has_key()``,\n``get()``, ``clear()``, ``setdefault()``,
``iterkeys()``,\n``itervalues()``, ``iteritems()``, ``pop()``,
``popitem()``,\n``copy()``, and ``update()`` behaving similar to those for
Python's\nstandard dictionary objects. The ``UserDict`` module
provides a\n``DictMixin`` class to help create those methods from a base
set of\n``__getitem__()``, ``__setitem__()``, ``__delitem__()``,
and\n``keys()``. Mutable sequences should provide methods
``append()``,\n``count()``, ``index()``, ``extend()``, ``insert()``,
``pop()``,\n``remove()``, ``reverse()`` and ``sort()``, like Python
standard list\nobjects. Finally, sequence types should implement addition
(meaning\nconcatenation) and multiplication (meaning repetition) by
defining the\nmethods ``__add__()``, ``__radd__()``, ``__iadd__()``,
``__mul__()``,\n``__rmul__()`` and ``__imul__()`` described below; they
should not\ndefine ``__coerce__()`` or other numerical operators. It
is\nrecommended that both mappings and sequences implement
the\n``__contains__()`` method to allow efficient use of the
``in``\noperator; for mappings, ``in`` should be equivalent of
``has_key()``;\nfor sequences, it should search through the values. It is
further\nrecommended that both mappings and sequences implement
the\n``__iter__()`` method to allow efficient iteration through
the\ncontainer; for mappings, ``__iter__()`` should be the same
as\n``iterkeys()``; for sequences, it should iterate through the
values.\n\nobject.__len__(self)\n\n Called to implement the built-in
function ``len()``. Should return\n the length of the object, an integer
``>=`` 0. Also, an object\n that doesn't define a
``__nonzero__()`` method and whose\n ``__len__()`` method returns zero is
considered to be false in a\n Boolean
context.\n\nobject.__getitem__(self, key)\n\n Called to implement
evaluation of ``self[key]``. For sequence\n types, the accepted keys
should be integers and slice objects.\n Note that the special
interpretation of negative indexes (if the\n class wishes to emulate a
sequence type) is up to the\n ``__getitem__()`` method. If *key* is of an
inappropriate type,\n ``TypeError`` may be raised; if of a value outside
the set of\n indexes for the sequence (after any special interpretation
of\n negative values), ``IndexError`` should be raised. For mapping\n
types, if *key* is missing (not in the container), ``KeyError``\n should
be raised.\n\n Note: ``for`` loops expect that an ``IndexError`` will be
raised for\n illegal indexes to allow proper detection of the end of
the\n sequence.\n\nobject.__setitem__(self, key, value)\n\n Called to
implement assignment to ``self[key]``. Same note as for\n
``__getitem__()``. This should only be implemented for mappings if\n the
objects support changes to the values for keys, or if new keys\n can be
added, or for sequences if elements can be replaced. The\n same
exceptions should be raised for improper *key* values as for\n the
``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\n Called to
implement deletion of ``self[key]``. Same note as for\n
``__getitem__()``. This should only be implemented for mappings if\n the
objects support removal of keys, or for sequences if elements\n can be
removed from the sequence. The same exceptions should be\n raised for
improper *key* values as for the ``__getitem__()``\n
method.\n\nobject.__iter__(self)\n\n This method is called when an
iterator is required for a container.\n This method should return a new
iterator object that can iterate\n over all the objects in the container.
For mappings, it should\n iterate over the keys of the container, and
should also be made\n available as the method ``iterkeys()``.\n\n
Iterator objects also need to implement this method; they are\n required
to return themselves. For more information on iterator\n objects, see
*Iterator Types*.\n\nobject.__reversed__(self)\n\n Called (if present) by
the ``reversed()`` built-in to implement\n reverse iteration. It should
return a new iterator object that\n iterates over all the objects in the
container in reverse order.\n\n If the ``__reversed__()`` method is not
provided, the\n ``reversed()`` built-in will fall back to using the
sequence\n protocol (``__len__()`` and ``__getitem__()``). Objects
that\n support the sequence protocol should only provide\n
``__reversed__()`` if they can provide an implementation that is\n more
efficient than the one provided by ``reversed()``.\n\n New in version
2.6.\n\nThe membership test operators (``in`` and ``not in``) are
normally\nimplemented as an iteration through a sequence. However,
container\nobjects can supply the following special method with a more
efficient\nimplementation, which also does not require the object be a
sequence.\n\nobject.__contains__(self, item)\n\n Called to implement
membership test operators. Should return true\n if *item* is in *self*,
false otherwise. For mapping objects, this\n should consider the keys of
the mapping rather than the values or\n the key-item pairs.\n\n For
objects that don't define ``__contains__()``, the membership\n test
first tries iteration via ``__iter__()``, then the old\n sequence
iteration protocol via ``__getitem__()``, see *this\n section in the
language reference*.\n",
'shifting': '\nShifting
operations\n*******************\n\nThe shifting operations have lower
priority than the arithmetic\noperations:\n\n shift_expr ::= a_expr |
shift_expr ( "<<" | ">>" ) a_expr\n\nThese
operators accept plain or long integers as arguments. The\narguments are
converted to a common type. They shift the first\nargument to the left or
right by the number of bits given by the\nsecond argument.\n\nA right shift
by *n* bits is defined as division by ``pow(2, n)``. A\nleft shift by *n*
bits is defined as multiplication with ``pow(2,\nn)``. Negative shift
counts raise a ``ValueError`` exception.\n\nNote: In the current
implementation, the right-hand operand is required to\n be at most
``sys.maxsize``. If the right-hand operand is larger\n than
``sys.maxsize`` an ``OverflowError`` exception is raised.\n',
'slicings': '\nSlicings\n********\n\nA slicing selects a
range of items in a sequence object (e.g., a\nstring, tuple or list).
Slicings may be used as expressions or as\ntargets in assignment or ``del``
statements. The syntax for a\nslicing:\n\n slicing ::=
simple_slicing | extended_slicing\n simple_slicing ::= primary
"[" short_slice "]"\n extended_slicing ::= primary
"[" slice_list "]"\n slice_list ::= slice_item
("," slice_item)* [","]\n slice_item ::=
expression | proper_slice | ellipsis\n proper_slice ::= short_slice |
long_slice\n short_slice ::= [lower_bound] ":"
[upper_bound]\n long_slice ::= short_slice ":" [stride]\n
lower_bound ::= expression\n upper_bound ::= expression\n
stride ::= expression\n ellipsis ::=
"..."\n\nThere is ambiguity in the formal syntax here: anything
that looks like\nan expression list also looks like a slice list, so any
subscription\ncan be interpreted as a slicing. Rather than further
complicating the\nsyntax, this is disambiguated by defining that in this
case the\ninterpretation as a subscription takes priority over
the\ninterpretation as a slicing (this is the case if the slice
list\ncontains no proper slice nor ellipses). Similarly, when the
slice\nlist has exactly one short slice and no trailing comma,
the\ninterpretation as a simple slicing takes priority over that as
an\nextended slicing.\n\nThe semantics for a simple slicing are as follows.
The primary must\nevaluate to a sequence object. The lower and upper
bound expressions,\nif present, must evaluate to plain integers; defaults
are zero and the\n``sys.maxint``, respectively. If either bound is
negative, the\nsequence\'s length is added to it. The slicing now
selects all items\nwith index *k* such that ``i <= k < j`` where *i*
and *j* are the\nspecified lower and upper bounds. This may be an empty
sequence. It\nis not an error if *i* or *j* lie outside the range of valid
indexes\n(such items don\'t exist so they aren\'t
selected).\n\nThe semantics for an extended slicing are as follows. The
primary\nmust evaluate to a mapping object, and it is indexed with a key
that\nis constructed from the slice list, as follows. If the slice
list\ncontains at least one comma, the key is a tuple containing
the\nconversion of the slice items; otherwise, the conversion of the
lone\nslice item is the key. The conversion of a slice item that is
an\nexpression is that expression. The conversion of an ellipsis
slice\nitem is the built-in ``Ellipsis`` object. The conversion of a
proper\nslice is a slice object (see section *The standard type
hierarchy*)\nwhose ``start``, ``stop`` and ``step`` attributes are the
values of\nthe expressions given as lower bound, upper bound and
stride,\nrespectively, substituting ``None`` for missing
expressions.\n',
'specialattrs': '\nSpecial
Attributes\n******************\n\nThe implementation adds a few special
read-only attributes to several\nobject types, where they are relevant.
Some of these are not reported\nby the ``dir()`` built-in
function.\n\nobject.__dict__\n\n A dictionary or other mapping object
used to store an object\'s\n (writable)
attributes.\n\nobject.__methods__\n\n Deprecated since version 2.2: Use
the built-in function ``dir()``\n to get a list of an object\'s
attributes. This attribute is no\n longer
available.\n\nobject.__members__\n\n Deprecated since version 2.2: Use
the built-in function ``dir()``\n to get a list of an object\'s
attributes. This attribute is no\n longer
available.\n\ninstance.__class__\n\n The class to which a class instance
belongs.\n\nclass.__bases__\n\n The tuple of base classes of a class
object.\n\nclass.__name__\n\n The name of the class or type.\n\nThe
following attributes are only supported by *new-style
class*es.\n\nclass.__mro__\n\n This attribute is a tuple of classes that
are considered when\n looking for base classes during method
resolution.\n\nclass.mro()\n\n This method can be overridden by a
metaclass to customize the\n method resolution order for its instances.
It is called at class\n instantiation, and its result is stored in
``__mro__``.\n\nclass.__subclasses__()\n\n Each new-style class keeps a
list of weak references to its\n immediate subclasses. This method
returns a list of all those\n references still alive. Example:\n\n
>>> int.__subclasses__()\n [<type
\'bool\'>]\n\n-[ Footnotes ]-\n\n[1] Additional information on
these special methods may be found in\n the Python Reference Manual
(*Basic customization*).\n\n[2] As a consequence, the list ``[1, 2]`` is
considered equal to\n ``[1.0, 2.0]``, and similarly for tuples.\n\n[3]
They must have since the parser can\'t tell the type of the\n
operands.\n\n[4] Cased characters are those with general category property
being\n one of "Lu" (Letter, uppercase), "Ll"
(Letter, lowercase), or "Lt"\n (Letter, titlecase).\n\n[5] To
format only a tuple you should therefore provide a singleton\n tuple
whose only element is the tuple to be formatted.\n\n[6] The advantage of
leaving the newline on is that returning an empty\n string is then an
unambiguous EOF indication. It is also possible\n (in cases where it
might matter, for example, if you want to make\n an exact copy of a file
while scanning its lines) to tell whether\n the last line of a file
ended in a newline or not (yes this\n happens!).\n',
'specialnames': '\nSpecial method
names\n********************\n\nA class can implement certain operations
that are invoked by special\nsyntax (such as arithmetic operations or
subscripting and slicing) by\ndefining methods with special names. This is
Python\'s approach to\n*operator overloading*, allowing classes to
define their own behavior\nwith respect to language operators. For
instance, if a class defines\na method named ``__getitem__()``, and ``x``
is an instance of this\nclass, then ``x[i]`` is roughly equivalent to
``x.__getitem__(i)`` for\nold-style classes and ``type(x).__getitem__(x,
i)`` for new-style\nclasses. Except where mentioned, attempts to execute
an operation\nraise an exception when no appropriate method is defined
(typically\n``AttributeError`` or ``TypeError``).\n\nWhen implementing a
class that emulates any built-in type, it is\nimportant that the emulation
only be implemented to the degree that it\nmakes sense for the object being
modelled. For example, some\nsequences may work well with retrieval of
individual elements, but\nextracting a slice may not make sense. (One
example of this is the\n``NodeList`` interface in the W3C\'s Document
Object Model.)\n\n\nBasic
customization\n===================\n\nobject.__new__(cls[, ...])\n\n
Called to create a new instance of class *cls*. ``__new__()`` is a\n
static method (special-cased so you need not declare it as such)\n that
takes the class of which an instance was requested as its\n first
argument. The remaining arguments are those passed to the\n object
constructor expression (the call to the class). The return\n value of
``__new__()`` should be the new object instance (usually\n an instance of
*cls*).\n\n Typical implementations create a new instance of the class
by\n invoking the superclass\'s ``__new__()`` method using\n
``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n
arguments and then modifying the newly-created instance as\n necessary
before returning it.\n\n If ``__new__()`` returns an instance of *cls*,
then the new\n instance\'s ``__init__()`` method will be invoked
like\n ``__init__(self[, ...])``, where *self* is the new instance and
the\n remaining arguments are the same as were passed to
``__new__()``.\n\n If ``__new__()`` does not return an instance of *cls*,
then the new\n instance\'s ``__init__()`` method will not be
invoked.\n\n ``__new__()`` is intended mainly to allow subclasses of
immutable\n types (like int, str, or tuple) to customize instance
creation. It\n is also commonly overridden in custom metaclasses in
order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n
Called when the instance is created. The arguments are those\n passed
to the class constructor expression. If a base class has an\n
``__init__()`` method, the derived class\'s ``__init__()`` method,\n
if any, must explicitly call it to ensure proper initialization of\n the
base class part of the instance; for example:\n
``BaseClass.__init__(self, [args...])``. As a special constraint\n on
constructors, no value may be returned; doing so will cause a\n
``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n Called
when the instance is about to be destroyed. This is also\n called a
destructor. If a base class has a ``__del__()`` method,\n the derived
class\'s ``__del__()`` method, if any, must explicitly\n call it to
ensure proper deletion of the base class part of the\n instance. Note
that it is possible (though not recommended!) for\n the ``__del__()``
method to postpone destruction of the instance by\n creating a new
reference to it. It may then be called at a later\n time when this new
reference is deleted. It is not guaranteed that\n ``__del__()`` methods
are called for objects that still exist when\n the interpreter exits.\n\n
Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the
former\n decrements the reference count for ``x`` by one, and the
latter\n is only called when ``x``\'s reference count reaches
zero. Some\n common situations that may prevent the reference count of
an\n object from going to zero include: circular references between\n
objects (e.g., a doubly-linked list or a tree data structure with\n
parent and child pointers); a reference to the object on the\n stack
frame of a function that caught an exception (the traceback\n stored in
``sys.exc_traceback`` keeps the stack frame alive); or\n a reference to
the object on the stack frame that raised an\n unhandled exception in
interactive mode (the traceback stored in\n ``sys.last_traceback``
keeps the stack frame alive). The first\n situation can only be
remedied by explicitly breaking the cycles;\n the latter two situations
can be resolved by storing ``None`` in\n ``sys.exc_traceback`` or
``sys.last_traceback``. Circular\n references which are garbage are
detected when the option cycle\n detector is enabled (it\'s on by
default), but can only be cleaned\n up if there are no Python-level
``__del__()`` methods involved.\n Refer to the documentation for the
``gc`` module for more\n information about how ``__del__()`` methods
are handled by the\n cycle detector, particularly the description of
the ``garbage``\n value.\n\n Warning: Due to the precarious
circumstances under which ``__del__()``\n methods are invoked,
exceptions that occur during their execution\n are ignored, and a
warning is printed to ``sys.stderr`` instead.\n Also, when
``__del__()`` is invoked in response to a module being\n deleted (e.g.,
when execution of the program is done), other\n globals referenced by
the ``__del__()`` method may already have\n been deleted or in the
process of being torn down (e.g. the\n import machinery shutting down).
For this reason, ``__del__()``\n methods should do the absolute
minimum needed to maintain\n external invariants. Starting with
version 1.5, Python\n guarantees that globals whose name begins with a
single\n underscore are deleted from their module before other globals
are\n deleted; if no other references to such globals exist, this may\n
help in assuring that imported modules are still available at the\n
time when the ``__del__()`` method is called.\n\n See also the *-R*
command-line option.\n\nobject.__repr__(self)\n\n Called by the
``repr()`` built-in function and by string\n conversions (reverse quotes)
to compute the "official" string\n representation of an object.
If at all possible, this should look\n like a valid Python expression
that could be used to recreate an\n object with the same value (given an
appropriate environment). If\n this is not possible, a string of the
form ``<...some useful\n description...>`` should be returned. The
return value must be a\n string object. If a class defines ``__repr__()``
but not\n ``__str__()``, then ``__repr__()`` is also used when an
"informal"\n string representation of instances of that class
is required.\n\n This is typically used for debugging, so it is important
that the\n representation is information-rich and
unambiguous.\n\nobject.__str__(self)\n\n Called by the ``str()`` built-in
function and by the ``print``\n statement to compute the
"informal" string representation of an\n object. This differs
from ``__repr__()`` in that it does not have\n to be a valid Python
expression: a more convenient or concise\n representation may be used
instead. The return value must be a\n string
object.\n\nobject.__lt__(self, other)\nobject.__le__(self,
other)\nobject.__eq__(self, other)\nobject.__ne__(self,
other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n New in
version 2.1.\n\n These are the so-called "rich comparison"
methods, and are called\n for comparison operators in preference to
``__cmp__()`` below. The\n correspondence between operator symbols and
method names is as\n follows: ``x<y`` calls ``x.__lt__(y)``,
``x<=y`` calls\n ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``,
``x!=y`` and\n ``x<>y`` call ``x.__ne__(y)``, ``x>y`` calls
``x.__gt__(y)``, and\n ``x>=y`` calls ``x.__ge__(y)``.\n\n A rich
comparison method may return the singleton\n ``NotImplemented`` if it
does not implement the operation for a\n given pair of arguments. By
convention, ``False`` and ``True`` are\n returned for a successful
comparison. However, these methods can\n return any value, so if the
comparison operator is used in a\n Boolean context (e.g., in the
condition of an ``if`` statement),\n Python will call ``bool()`` on the
value to determine if the result\n is true or false.\n\n There are no
implied relationships among the comparison operators.\n The truth of
``x==y`` does not imply that ``x!=y`` is false.\n Accordingly, when
defining ``__eq__()``, one should also define\n ``__ne__()`` so that the
operators will behave as expected. See\n the paragraph on ``__hash__()``
for some important notes on\n creating *hashable* objects which support
custom comparison\n operations and are usable as dictionary keys.\n\n
There are no swapped-argument versions of these methods (to be used\n
when the left argument does not support the operation but the right\n
argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n
other\'s reflection, ``__le__()`` and ``__ge__()`` are each
other\'s\n reflection, and ``__eq__()`` and ``__ne__()`` are their
own\n reflection.\n\n Arguments to rich comparison methods are never
coerced.\n\n To automatically generate ordering operations from a single
root\n operation, see
``functools.total_ordering()``.\n\nobject.__cmp__(self, other)\n\n Called
by comparison operations if rich comparison (see above) is\n not defined.
Should return a negative integer if ``self < other``,\n zero if
``self == other``, a positive integer if ``self > other``.\n If no
``__cmp__()``, ``__eq__()`` or ``__ne__()`` operation is\n defined, class
instances are compared by object identity\n ("address"). See
also the description of ``__hash__()`` for some\n important notes on
creating *hashable* objects which support custom\n comparison operations
and are usable as dictionary keys. (Note: the\n restriction that
exceptions are not propagated by ``__cmp__()`` has\n been removed since
Python 1.5.)\n\nobject.__rcmp__(self, other)\n\n Changed in version 2.1:
No longer supported.\n\nobject.__hash__(self)\n\n Called by built-in
function ``hash()`` and for operations on\n members of hashed collections
including ``set``, ``frozenset``, and\n ``dict``. ``__hash__()`` should
return an integer. The only\n required property is that objects which
compare equal have the same\n hash value; it is advised to somehow mix
together (e.g. using\n exclusive or) the hash values for the components
of the object that\n also play a part in comparison of objects.\n\n If
a class does not define a ``__cmp__()`` or ``__eq__()`` method\n it
should not define a ``__hash__()`` operation either; if it\n defines
``__cmp__()`` or ``__eq__()`` but not ``__hash__()``, its\n instances
will not be usable in hashed collections. If a class\n defines mutable
objects and implements a ``__cmp__()`` or\n ``__eq__()`` method, it
should not implement ``__hash__()``, since\n hashable collection
implementations require that a object\'s hash\n value is immutable
(if the object\'s hash value changes, it will be\n in the wrong hash
bucket).\n\n User-defined classes have ``__cmp__()`` and ``__hash__()``
methods\n by default; with them, all objects compare unequal (except
with\n themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n Classes
which inherit a ``__hash__()`` method from a parent class\n but change
the meaning of ``__cmp__()`` or ``__eq__()`` such that\n the hash value
returned is no longer appropriate (e.g. by switching\n to a value-based
concept of equality instead of the default\n identity based equality) can
explicitly flag themselves as being\n unhashable by setting ``__hash__ =
None`` in the class definition.\n Doing so means that not only will
instances of the class raise an\n appropriate ``TypeError`` when a
program attempts to retrieve their\n hash value, but they will also be
correctly identified as\n unhashable when checking ``isinstance(obj,
collections.Hashable)``\n (unlike classes which define their own
``__hash__()`` to explicitly\n raise ``TypeError``).\n\n Changed in
version 2.5: ``__hash__()`` may now also return a long\n integer object;
the 32-bit integer is then derived from the hash of\n that object.\n\n
Changed in version 2.6: ``__hash__`` may now be set to ``None`` to\n
explicitly flag instances of a class as
unhashable.\n\nobject.__nonzero__(self)\n\n Called to implement truth
value testing and the built-in operation\n ``bool()``; should return
``False`` or ``True``, or their integer\n equivalents ``0`` or ``1``.
When this method is not defined,\n ``__len__()`` is called, if it is
defined, and the object is\n considered true if its result is nonzero. If
a class defines\n neither ``__len__()`` nor ``__nonzero__()``, all its
instances are\n considered true.\n\nobject.__unicode__(self)\n\n Called
to implement ``unicode()`` built-in; should return a Unicode\n object.
When this method is not defined, string conversion is\n attempted, and
the result of string conversion is converted to\n Unicode using the
system default encoding.\n\n\nCustomizing attribute
access\n============================\n\nThe following methods can be
defined to customize the meaning of\nattribute access (use of, assignment
to, or deletion of ``x.name``)\nfor class
instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute
lookup has not found the attribute in the\n usual places (i.e. it is not
an instance attribute nor is it found\n in the class tree for ``self``).
``name`` is the attribute name.\n This method should return the
(computed) attribute value or raise\n an ``AttributeError``
exception.\n\n Note that if the attribute is found through the normal
mechanism,\n ``__getattr__()`` is not called. (This is an intentional
asymmetry\n between ``__getattr__()`` and ``__setattr__()``.) This is
done both\n for efficiency reasons and because otherwise
``__getattr__()``\n would have no way to access other attributes of the
instance. Note\n that at least for instance variables, you can fake
total control by\n not inserting any values in the instance attribute
dictionary (but\n instead inserting them in another object). See the\n
``__getattribute__()`` method below for a way to actually get total\n
control in new-style classes.\n\nobject.__setattr__(self, name, value)\n\n
Called when an attribute assignment is attempted. This is called\n
instead of the normal mechanism (i.e. store the value in the\n instance
dictionary). *name* is the attribute name, *value* is the\n value to be
assigned to it.\n\n If ``__setattr__()`` wants to assign to an instance
attribute, it\n should not simply execute ``self.name = value`` --- this
would\n cause a recursive call to itself. Instead, it should insert
the\n value in the dictionary of instance attributes, e.g.,\n
``self.__dict__[name] = value``. For new-style classes, rather\n than
accessing the instance dictionary, it should call the base\n class method
with the same name, for example,\n ``object.__setattr__(self, name,
value)``.\n\nobject.__delattr__(self, name)\n\n Like ``__setattr__()``
but for attribute deletion instead of\n assignment. This should only be
implemented if ``del obj.name`` is\n meaningful for the object.\n\n\nMore
attribute access for new-style
classes\n-------------------------------------------\n\nThe following
methods only apply to new-style classes.\n\nobject.__getattribute__(self,
name)\n\n Called unconditionally to implement attribute accesses for\n
instances of the class. If the class also defines\n ``__getattr__()``,
the latter will not be called unless\n ``__getattribute__()`` either
calls it explicitly or raises an\n ``AttributeError``. This method should
return the (computed)\n attribute value or raise an ``AttributeError``
exception. In order\n to avoid infinite recursion in this method, its
implementation\n should always call the base class method with the same
name to\n access any attributes it needs, for example,\n
``object.__getattribute__(self, name)``.\n\n Note: This method may still
be bypassed when looking up special methods\n as the result of implicit
invocation via language syntax or\n built-in functions. See *Special
method lookup for new-style\n classes*.\n\n\nImplementing
Descriptors\n------------------------\n\nThe following methods only apply
when an instance of the class\ncontaining the method (a so-called
*descriptor* class) appears in an\n*owner* class (the descriptor must be in
either the owner\'s class\ndictionary or in the class dictionary for
one of its parents). In the\nexamples below, "the attribute"
refers to the attribute whose name is\nthe key of the property in the owner
class\' ``__dict__``.\n\nobject.__get__(self, instance, owner)\n\n
Called to get the attribute of the owner class (class attribute\n access)
or of an instance of that class (instance attribute\n access). *owner* is
always the owner class, while *instance* is the\n instance that the
attribute was accessed through, or ``None`` when\n the attribute is
accessed through the *owner*. This method should\n return the (computed)
attribute value or raise an\n ``AttributeError``
exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the
attribute on an instance *instance* of the owner\n class to a new value,
*value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the
attribute on an instance *instance* of the\n owner class.\n\n\nInvoking
Descriptors\n--------------------\n\nIn general, a descriptor is an object
attribute with "binding\nbehavior", one whose attribute access
has been overridden by methods\nin the descriptor protocol: ``__get__()``,
``__set__()``, and\n``__delete__()``. If any of those methods are defined
for an object,\nit is said to be a descriptor.\n\nThe default behavior for
attribute access is to get, set, or delete\nthe attribute from an
object\'s dictionary. For instance, ``a.x`` has a\nlookup chain
starting with ``a.__dict__[\'x\']``,
then\n``type(a).__dict__[\'x\']``, and continuing through the
base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the
looked-up value is an object defining one of the\ndescriptor methods, then
Python may override the default behavior and\ninvoke the descriptor method
instead. Where this occurs in the\nprecedence chain depends on which
descriptor methods were defined and\nhow they were called. Note that
descriptors are only invoked for new\nstyle objects or classes (ones that
subclass ``object()`` or\n``type()``).\n\nThe starting point for descriptor
invocation is a binding, ``a.x``.\nHow the arguments are assembled depends
on ``a``:\n\nDirect Call\n The simplest and least common call is when
user code directly\n invokes a descriptor method:
``x.__get__(a)``.\n\nInstance Binding\n If binding to a new-style object
instance, ``a.x`` is transformed\n into the call:
``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass
Binding\n If binding to a new-style class, ``A.x`` is transformed into
the\n call: ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper
Binding\n If ``a`` is an instance of ``super``, then the binding
``super(B,\n obj).m()`` searches ``obj.__class__.__mro__`` for the base
class\n ``A`` immediately preceding ``B`` and then invokes the
descriptor\n with the call: ``A.__dict__[\'m\'].__get__(obj,
obj.__class__)``.\n\nFor instance bindings, the precedence of descriptor
invocation depends\non the which descriptor methods are defined. A
descriptor can define\nany combination of ``__get__()``, ``__set__()`` and
``__delete__()``.\nIf it does not define ``__get__()``, then accessing the
attribute will\nreturn the descriptor object itself unless there is a value
in the\nobject\'s instance dictionary. If the descriptor defines
``__set__()``\nand/or ``__delete__()``, it is a data descriptor; if it
defines\nneither, it is a non-data descriptor. Normally, data
descriptors\ndefine both ``__get__()`` and ``__set__()``, while
non-data\ndescriptors have just the ``__get__()`` method. Data descriptors
with\n``__set__()`` and ``__get__()`` defined always override a
redefinition\nin an instance dictionary. In contrast, non-data descriptors
can be\noverridden by instances.\n\nPython methods (including
``staticmethod()`` and ``classmethod()``)\nare implemented as non-data
descriptors. Accordingly, instances can\nredefine and override methods.
This allows individual instances to\nacquire behaviors that differ from
other instances of the same class.\n\nThe ``property()`` function is
implemented as a data descriptor.\nAccordingly, instances cannot override
the behavior of a property.\n\n\n__slots__\n---------\n\nBy default,
instances of both old and new-style classes have a\ndictionary for
attribute storage. This wastes space for objects\nhaving very few instance
variables. The space consumption can become\nacute when creating large
numbers of instances.\n\nThe default can be overridden by defining
*__slots__* in a new-style\nclass definition. The *__slots__* declaration
takes a sequence of\ninstance variables and reserves just enough space in
each instance to\nhold a value for each variable. Space is saved because
*__dict__* is\nnot created for each instance.\n\n__slots__\n\n This class
variable can be assigned a string, iterable, or sequence\n of strings
with variable names used by instances. If defined in a\n new-style
class, *__slots__* reserves space for the declared\n variables and
prevents the automatic creation of *__dict__* and\n *__weakref__* for
each instance.\n\n New in version 2.2.\n\nNotes on using *__slots__*\n\n*
When inheriting from a class without *__slots__*, the *__dict__*\n
attribute of that class will always be accessible, so a *__slots__*\n
definition in the subclass is meaningless.\n\n* Without a *__dict__*
variable, instances cannot be assigned new\n variables not listed in the
*__slots__* definition. Attempts to\n assign to an unlisted variable name
raises ``AttributeError``. If\n dynamic assignment of new variables is
desired, then add\n ``\'__dict__\'`` to the sequence of strings
in the *__slots__*\n declaration.\n\n Changed in version 2.3: Previously,
adding ``\'__dict__\'`` to the\n *__slots__* declaration would
not enable the assignment of new\n attributes not specifically listed in
the sequence of instance\n variable names.\n\n* Without a *__weakref__*
variable for each instance, classes defining\n *__slots__* do not support
weak references to its instances. If weak\n reference support is needed,
then add ``\'__weakref__\'`` to the\n sequence of strings in the
*__slots__* declaration.\n\n Changed in version 2.3: Previously, adding
``\'__weakref__\'`` to the\n *__slots__* declaration would not
enable support for weak\n references.\n\n* *__slots__* are implemented at
the class level by creating\n descriptors (*Implementing Descriptors*) for
each variable name. As\n a result, class attributes cannot be used to set
default values for\n instance variables defined by *__slots__*; otherwise,
the class\n attribute would overwrite the descriptor assignment.\n\n* The
action of a *__slots__* declaration is limited to the class\n where it is
defined. As a result, subclasses will have a *__dict__*\n unless they
also define *__slots__* (which must only contain names\n of any
*additional* slots).\n\n* If a class defines a slot also defined in a base
class, the instance\n variable defined by the base class slot is
inaccessible (except by\n retrieving its descriptor directly from the base
class). This\n renders the meaning of the program undefined. In the
future, a\n check may be added to prevent this.\n\n* Nonempty *__slots__*
does not work for classes derived from\n "variable-length"
built-in types such as ``long``, ``str`` and\n ``tuple``.\n\n* Any
non-string iterable may be assigned to *__slots__*. Mappings may\n also be
used; however, in the future, special meaning may be\n assigned to the
values corresponding to each key.\n\n* *__class__* assignment works only if
both classes have the same\n *__slots__*.\n\n Changed in version 2.6:
Previously, *__class__* assignment raised an\n error if either new or old
class had *__slots__*.\n\n\nCustomizing class
creation\n==========================\n\nBy default, new-style classes are
constructed using ``type()``. A\nclass definition is read into a separate
namespace and the value of\nclass name is bound to the result of
``type(name, bases, dict)``.\n\nWhen the class definition is read, if
*__metaclass__* is defined then\nthe callable assigned to it will be called
instead of ``type()``. This\nallows classes or functions to be written
which monitor or alter the\nclass creation process:\n\n* Modifying the
class dictionary prior to the class being created.\n\n* Returning an
instance of another class -- essentially performing the\n role of a
factory function.\n\nThese steps will have to be performed in the
metaclass\'s ``__new__()``\nmethod -- ``type.__new__()`` can then be
called from this method to\ncreate a class with different properties. This
example adds a new\nelement to the class dictionary before creating the
class:\n\n class metacls(type):\n def __new__(mcs, name, bases,
dict):\n dict[\'foo\'] = \'metacls was
here\'\n return type.__new__(mcs, name, bases, dict)\n\nYou
can of course also override other class methods (or add new\nmethods); for
example defining a custom ``__call__()`` method in the\nmetaclass allows
custom behavior when the class is called, e.g. not\nalways creating a new
instance.\n\n__metaclass__\n\n This variable can be any callable
accepting arguments for ``name``,\n ``bases``, and ``dict``. Upon class
creation, the callable is used\n instead of the built-in ``type()``.\n\n
New in version 2.2.\n\nThe appropriate metaclass is determined by the
following precedence\nrules:\n\n* If ``dict[\'__metaclass__\']``
exists, it is used.\n\n* Otherwise, if there is at least one base class,
its metaclass is\n used (this looks for a *__class__* attribute first and
if not found,\n uses its type).\n\n* Otherwise, if a global variable named
__metaclass__ exists, it is\n used.\n\n* Otherwise, the old-style, classic
metaclass (types.ClassType) is\n used.\n\nThe potential uses for
metaclasses are boundless. Some ideas that have\nbeen explored including
logging, interface checking, automatic\ndelegation, automatic property
creation, proxies, frameworks, and\nautomatic resource
locking/synchronization.\n\n\nCustomizing instance and subclass
checks\n========================================\n\nNew in version
2.6.\n\nThe following methods are used to override the default behavior of
the\n``isinstance()`` and ``issubclass()`` built-in functions.\n\nIn
particular, the metaclass ``abc.ABCMeta`` implements these methods\nin
order to allow the addition of Abstract Base Classes (ABCs)
as\n"virtual base classes" to any class or type (including
built-in\ntypes), including other ABCs.\n\nclass.__instancecheck__(self,
instance)\n\n Return true if *instance* should be considered a (direct
or\n indirect) instance of *class*. If defined, called to implement\n
``isinstance(instance, class)``.\n\nclass.__subclasscheck__(self,
subclass)\n\n Return true if *subclass* should be considered a (direct
or\n indirect) subclass of *class*. If defined, called to implement\n
``issubclass(subclass, class)``.\n\nNote that these methods are looked up
on the type (metaclass) of a\nclass. They cannot be defined as class
methods in the actual class.\nThis is consistent with the lookup of special
methods that are called\non instances, only in this case the instance is
itself a class.\n\nSee also:\n\n **PEP 3119** - Introducing Abstract Base
Classes\n Includes the specification for customizing ``isinstance()``
and\n ``issubclass()`` behavior through ``__instancecheck__()`` and\n
``__subclasscheck__()``, with motivation for this functionality\n
in the context of adding Abstract Base Classes (see the ``abc``\n
module) to the language.\n\n\nEmulating callable
objects\n==========================\n\nobject.__call__(self[, args...])\n\n
Called when the instance is "called" as a function; if this
method\n is defined, ``x(arg1, arg2, ...)`` is a shorthand for\n
``x.__call__(arg1, arg2, ...)``.\n\n\nEmulating container
types\n=========================\n\nThe following methods can be defined to
implement container objects.\nContainers usually are sequences (such as
lists or tuples) or mappings\n(like dictionaries), but can represent other
containers as well. The\nfirst set of methods is used either to emulate a
sequence or to\nemulate a mapping; the difference is that for a sequence,
the\nallowable keys should be the integers *k* for which ``0 <= k <
N``\nwhere *N* is the length of the sequence, or slice objects,
which\ndefine a range of items. (For backwards compatibility, the
method\n``__getslice__()`` (see below) can also be defined to handle
simple,\nbut not extended slices.) It is also recommended that mappings
provide\nthe methods ``keys()``, ``values()``, ``items()``,
``has_key()``,\n``get()``, ``clear()``, ``setdefault()``,
``iterkeys()``,\n``itervalues()``, ``iteritems()``, ``pop()``,
``popitem()``,\n``copy()``, and ``update()`` behaving similar to those for
Python\'s\nstandard dictionary objects. The ``UserDict`` module
provides a\n``DictMixin`` class to help create those methods from a base
set of\n``__getitem__()``, ``__setitem__()``, ``__delitem__()``,
and\n``keys()``. Mutable sequences should provide methods
``append()``,\n``count()``, ``index()``, ``extend()``, ``insert()``,
``pop()``,\n``remove()``, ``reverse()`` and ``sort()``, like Python
standard list\nobjects. Finally, sequence types should implement addition
(meaning\nconcatenation) and multiplication (meaning repetition) by
defining the\nmethods ``__add__()``, ``__radd__()``, ``__iadd__()``,
``__mul__()``,\n``__rmul__()`` and ``__imul__()`` described below; they
should not\ndefine ``__coerce__()`` or other numerical operators. It
is\nrecommended that both mappings and sequences implement
the\n``__contains__()`` method to allow efficient use of the
``in``\noperator; for mappings, ``in`` should be equivalent of
``has_key()``;\nfor sequences, it should search through the values. It is
further\nrecommended that both mappings and sequences implement
the\n``__iter__()`` method to allow efficient iteration through
the\ncontainer; for mappings, ``__iter__()`` should be the same
as\n``iterkeys()``; for sequences, it should iterate through the
values.\n\nobject.__len__(self)\n\n Called to implement the built-in
function ``len()``. Should return\n the length of the object, an integer
``>=`` 0. Also, an object\n that doesn\'t define a
``__nonzero__()`` method and whose\n ``__len__()`` method returns zero is
considered to be false in a\n Boolean
context.\n\nobject.__getitem__(self, key)\n\n Called to implement
evaluation of ``self[key]``. For sequence\n types, the accepted keys
should be integers and slice objects.\n Note that the special
interpretation of negative indexes (if the\n class wishes to emulate a
sequence type) is up to the\n ``__getitem__()`` method. If *key* is of an
inappropriate type,\n ``TypeError`` may be raised; if of a value outside
the set of\n indexes for the sequence (after any special interpretation
of\n negative values), ``IndexError`` should be raised. For mapping\n
types, if *key* is missing (not in the container), ``KeyError``\n should
be raised.\n\n Note: ``for`` loops expect that an ``IndexError`` will be
raised for\n illegal indexes to allow proper detection of the end of
the\n sequence.\n\nobject.__setitem__(self, key, value)\n\n Called to
implement assignment to ``self[key]``. Same note as for\n
``__getitem__()``. This should only be implemented for mappings if\n the
objects support changes to the values for keys, or if new keys\n can be
added, or for sequences if elements can be replaced. The\n same
exceptions should be raised for improper *key* values as for\n the
``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\n Called to
implement deletion of ``self[key]``. Same note as for\n
``__getitem__()``. This should only be implemented for mappings if\n the
objects support removal of keys, or for sequences if elements\n can be
removed from the sequence. The same exceptions should be\n raised for
improper *key* values as for the ``__getitem__()``\n
method.\n\nobject.__iter__(self)\n\n This method is called when an
iterator is required for a container.\n This method should return a new
iterator object that can iterate\n over all the objects in the container.
For mappings, it should\n iterate over the keys of the container, and
should also be made\n available as the method ``iterkeys()``.\n\n
Iterator objects also need to implement this method; they are\n required
to return themselves. For more information on iterator\n objects, see
*Iterator Types*.\n\nobject.__reversed__(self)\n\n Called (if present) by
the ``reversed()`` built-in to implement\n reverse iteration. It should
return a new iterator object that\n iterates over all the objects in the
container in reverse order.\n\n If the ``__reversed__()`` method is not
provided, the\n ``reversed()`` built-in will fall back to using the
sequence\n protocol (``__len__()`` and ``__getitem__()``). Objects
that\n support the sequence protocol should only provide\n
``__reversed__()`` if they can provide an implementation that is\n more
efficient than the one provided by ``reversed()``.\n\n New in version
2.6.\n\nThe membership test operators (``in`` and ``not in``) are
normally\nimplemented as an iteration through a sequence. However,
container\nobjects can supply the following special method with a more
efficient\nimplementation, which also does not require the object be a
sequence.\n\nobject.__contains__(self, item)\n\n Called to implement
membership test operators. Should return true\n if *item* is in *self*,
false otherwise. For mapping objects, this\n should consider the keys of
the mapping rather than the values or\n the key-item pairs.\n\n For
objects that don\'t define ``__contains__()``, the membership\n test
first tries iteration via ``__iter__()``, then the old\n sequence
iteration protocol via ``__getitem__()``, see *this\n section in the
language reference*.\n\n\nAdditional methods for emulation of sequence
types\n==================================================\n\nThe following
optional methods can be defined to further emulate\nsequence objects.
Immutable sequences methods should at most only\ndefine ``__getslice__()``;
mutable sequences might define all
three\nmethods.\n\nobject.__getslice__(self, i, j)\n\n Deprecated since
version 2.0: Support slice objects as parameters\n to the
``__getitem__()`` method. (However, built-in types in\n CPython currently
still implement ``__getslice__()``. Therefore,\n you have to override it
in derived classes when implementing\n slicing.)\n\n Called to
implement evaluation of ``self[i:j]``. The returned\n object should be of
the same type as *self*. Note that missing *i*\n or *j* in the slice
expression are replaced by zero or\n ``sys.maxint``, respectively. If
negative indexes are used in the\n slice, the length of the sequence is
added to that index. If the\n instance does not implement the
``__len__()`` method, an\n ``AttributeError`` is raised. No guarantee is
made that indexes\n adjusted this way are not still negative. Indexes
which are\n greater than the length of the sequence are not modified. If
no\n ``__getslice__()`` is found, a slice object is created instead,
and\n passed to ``__getitem__()`` instead.\n\nobject.__setslice__(self,
i, j, sequence)\n\n Called to implement assignment to ``self[i:j]``. Same
notes for *i*\n and *j* as for ``__getslice__()``.\n\n This method is
deprecated. If no ``__setslice__()`` is found, or\n for extended slicing
of the form ``self[i:j:k]``, a slice object is\n created, and passed to
``__setitem__()``, instead of\n ``__setslice__()`` being
called.\n\nobject.__delslice__(self, i, j)\n\n Called to implement
deletion of ``self[i:j]``. Same notes for *i*\n and *j* as for
``__getslice__()``. This method is deprecated. If no\n ``__delslice__()``
is found, or for extended slicing of the form\n ``self[i:j:k]``, a slice
object is created, and passed to\n ``__delitem__()``, instead of
``__delslice__()`` being called.\n\nNotice that these methods are only
invoked when a single slice with a\nsingle colon is used, and the slice
method is available. For slice\noperations involving extended slice
notation, or in absence of the\nslice methods, ``__getitem__()``,
``__setitem__()`` or\n``__delitem__()`` is called with a slice object as
argument.\n\nThe following example demonstrate how to make your program or
module\ncompatible with earlier versions of Python (assuming that
methods\n``__getitem__()``, ``__setitem__()`` and ``__delitem__()``
support\nslice objects as arguments):\n\n class MyClass:\n ...\n
def __getitem__(self, index):\n ...\n def
__setitem__(self, index, value):\n ...\n def
__delitem__(self, index):\n ...\n\n if sys.version_info
< (2, 0):\n # They won\'t be defined if version is at
least 2.0 final\n\n def __getslice__(self, i, j):\n
return self[max(0, i):max(0, j):]\n def __setslice__(self, i, j,
seq):\n self[max(0, i):max(0, j):] = seq\n def
__delslice__(self, i, j):\n del self[max(0, i):max(0, j):]\n
...\n\nNote the calls to ``max()``; these are necessary because of
the\nhandling of negative indices before the ``__*slice__()`` methods
are\ncalled. When negative indexes are used, the ``__*item__()``
methods\nreceive them as provided, but the ``__*slice__()`` methods get
a\n"cooked" form of the index values. For each negative index
value, the\nlength of the sequence is added to the index before calling the
method\n(which may still result in a negative index); this is the
customary\nhandling of negative indexes by the built-in sequence types, and
the\n``__*item__()`` methods are expected to do this as well.
However,\nsince they should already be doing that, negative indexes cannot
be\npassed in; they must be constrained to the bounds of the
sequence\nbefore being passed to the ``__*item__()`` methods. Calling
``max(0,\ni)`` conveniently returns the proper value.\n\n\nEmulating
numeric types\n=======================\n\nThe following methods can be
defined to emulate numeric objects.\nMethods corresponding to operations
that are not supported by the\nparticular kind of number implemented (e.g.,
bitwise operations for\nnon-integral numbers) should be left
undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self,
other)\nobject.__mul__(self, other)\nobject.__floordiv__(self,
other)\nobject.__mod__(self, other)\nobject.__divmod__(self,
other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self,
other)\nobject.__rshift__(self, other)\nobject.__and__(self,
other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n These
methods are called to implement the binary arithmetic\n operations
(``+``, ``-``, ``*``, ``//``, ``%``, ``divmod()``,\n ``pow()``, ``**``,
``<<``, ``>>``, ``&``, ``^``, ``|``). For\n instance, to
evaluate the expression ``x + y``, where *x* is an\n instance of a class
that has an ``__add__()`` method,\n ``x.__add__(y)`` is called. The
``__divmod__()`` method should be\n the equivalent to using
``__floordiv__()`` and ``__mod__()``; it\n should not be related to
``__truediv__()`` (described below). Note\n that ``__pow__()`` should be
defined to accept an optional third\n argument if the ternary version of
the built-in ``pow()`` function\n is to be supported.\n\n If one of
those methods does not support the operation with the\n supplied
arguments, it should return ``NotImplemented``.\n\nobject.__div__(self,
other)\nobject.__truediv__(self, other)\n\n The division operator (``/``)
is implemented by these methods. The\n ``__truediv__()`` method is used
when ``__future__.division`` is in\n effect, otherwise ``__div__()`` is
used. If only one of these two\n methods is defined, the object will not
support division in the\n alternate context; ``TypeError`` will be raised
instead.\n\nobject.__radd__(self, other)\nobject.__rsub__(self,
other)\nobject.__rmul__(self, other)\nobject.__rdiv__(self,
other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self,
other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self,
other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self,
other)\nobject.__rrshift__(self, other)\nobject.__rand__(self,
other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n
These methods are called to implement the binary arithmetic\n operations
(``+``, ``-``, ``*``, ``/``, ``%``, ``divmod()``,\n ``pow()``, ``**``,
``<<``, ``>>``, ``&``, ``^``, ``|``) with\n reflected
(swapped) operands. These functions are only called if\n the left
operand does not support the corresponding operation and\n the operands
are of different types. [2] For instance, to evaluate\n the expression
``x - y``, where *y* is an instance of a class that\n has an
``__rsub__()`` method, ``y.__rsub__(x)`` is called if\n ``x.__sub__(y)``
returns *NotImplemented*.\n\n Note that ternary ``pow()`` will not try
calling ``__rpow__()``\n (the coercion rules would become too
complicated).\n\n Note: If the right operand\'s type is a subclass
of the left operand\'s\n type and that subclass provides the
reflected method for the\n operation, this method will be called before
the left operand\'s\n non-reflected method. This behavior allows
subclasses to\n override their ancestors\'
operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self,
other)\nobject.__imul__(self, other)\nobject.__idiv__(self,
other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self,
other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[,
modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self,
other)\nobject.__iand__(self, other)\nobject.__ixor__(self,
other)\nobject.__ior__(self, other)\n\n These methods are called to
implement the augmented arithmetic\n assignments (``+=``, ``-=``, ``*=``,
``/=``, ``//=``, ``%=``,\n ``**=``, ``<<=``, ``>>=``,
``&=``, ``^=``, ``|=``). These methods\n should attempt to do the
operation in-place (modifying *self*) and\n return the result (which
could be, but does not have to be,\n *self*). If a specific method is
not defined, the augmented\n assignment falls back to the normal methods.
For instance, to\n execute the statement ``x += y``, where *x* is an
instance of a\n class that has an ``__iadd__()`` method,
``x.__iadd__(y)`` is\n called. If *x* is an instance of a class that
does not define a\n ``__iadd__()`` method, ``x.__add__(y)`` and
``y.__radd__(x)`` are\n considered, as with the evaluation of ``x +
y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n
Called to implement the unary arithmetic operations (``-``, ``+``,\n
``abs()`` and
``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__long__(self)\nobject.__float__(self)\n\n
Called to implement the built-in functions ``complex()``,\n ``int()``,
``long()``, and ``float()``. Should return a value of\n the appropriate
type.\n\nobject.__oct__(self)\nobject.__hex__(self)\n\n Called to
implement the built-in functions ``oct()`` and ``hex()``.\n Should return
a string value.\n\nobject.__index__(self)\n\n Called to implement
``operator.index()``. Also called whenever\n Python needs an integer
object (such as in slicing). Must return\n an integer (int or long).\n\n
New in version 2.5.\n\nobject.__coerce__(self, other)\n\n Called to
implement "mixed-mode" numeric arithmetic. Should either\n
return a 2-tuple containing *self* and *other* converted to a\n common
numeric type, or ``None`` if conversion is impossible. When\n the common
type would be the type of ``other``, it is sufficient to\n return
``None``, since the interpreter will also ask the other\n object to
attempt a coercion (but sometimes, if the implementation\n of the other
type cannot be changed, it is useful to do the\n conversion to the other
type here). A return value of\n ``NotImplemented`` is equivalent to
returning ``None``.\n\n\nCoercion rules\n==============\n\nThis section
used to document the rules for coercion. As the language\nhas evolved, the
coercion rules have become hard to document\nprecisely; documenting what
one version of one particular\nimplementation does is undesirable.
Instead, here are some informal\nguidelines regarding coercion. In Python
3, coercion will not be\nsupported.\n\n* If the left operand of a %
operator is a string or Unicode object,\n no coercion takes place and the
string formatting operation is\n invoked instead.\n\n* It is no longer
recommended to define a coercion operation. Mixed-\n mode operations on
types that don\'t define coercion pass the\n original arguments to
the operation.\n\n* New-style classes (those derived from ``object``) never
invoke the\n ``__coerce__()`` method in response to a binary operator; the
only\n time ``__coerce__()`` is invoked is when the built-in function\n
``coerce()`` is called.\n\n* For most intents and purposes, an operator
that returns\n ``NotImplemented`` is treated the same as one that is not\n
implemented at all.\n\n* Below, ``__op__()`` and ``__rop__()`` are used to
signify the\n generic method names corresponding to an operator;
``__iop__()`` is\n used for the corresponding in-place operator. For
example, for the\n operator \'``+``\', ``__add__()`` and
``__radd__()`` are used for the\n left and right variant of the binary
operator, and ``__iadd__()``\n for the in-place variant.\n\n* For objects
*x* and *y*, first ``x.__op__(y)`` is tried. If this is\n not implemented
or returns ``NotImplemented``, ``y.__rop__(x)`` is\n tried. If this is
also not implemented or returns\n ``NotImplemented``, a ``TypeError``
exception is raised. But see\n the following exception:\n\n* Exception to
the previous item: if the left operand is an instance\n of a built-in type
or a new-style class, and the right operand is an\n instance of a proper
subclass of that type or class and overrides\n the base\'s
``__rop__()`` method, the right operand\'s ``__rop__()``\n method is
tried *before* the left operand\'s ``__op__()`` method.\n\n This is
done so that a subclass can completely override binary\n operators.
Otherwise, the left operand\'s ``__op__()`` method would\n always
accept the right operand: when an instance of a given class\n is expected,
an instance of a subclass of that class is always\n acceptable.\n\n* When
either operand type defines a coercion, this coercion is called\n before
that type\'s ``__op__()`` or ``__rop__()`` method is called,\n but no
sooner. If the coercion returns an object of a different\n type for the
operand whose coercion is invoked, part of the process\n is redone using
the new object.\n\n* When an in-place operator (like \'``+=``\')
is used, if the left\n operand implements ``__iop__()``, it is invoked
without any\n coercion. When the operation falls back to ``__op__()``
and/or\n ``__rop__()``, the normal coercion rules apply.\n\n* In ``x +
y``, if *x* is a sequence that implements sequence\n concatenation,
sequence concatenation is invoked.\n\n* In ``x * y``, if one operand is a
sequence that implements sequence\n repetition, and the other is an
integer (``int`` or ``long``),\n sequence repetition is invoked.\n\n* Rich
comparisons (implemented by methods ``__eq__()`` and so on)\n never use
coercion. Three-way comparison (implemented by\n ``__cmp__()``) does use
coercion under the same conditions as other\n binary operations use
it.\n\n* In the current implementation, the built-in numeric types
``int``,\n ``long``, ``float``, and ``complex`` do not use coercion. All
these\n types implement a ``__coerce__()`` method, for use by the
built-in\n ``coerce()`` function.\n\n Changed in version 2.7.\n\n\nWith
Statement Context Managers\n===============================\n\nNew in
version 2.5.\n\nA *context manager* is an object that defines the runtime
context to\nbe established when executing a ``with`` statement. The
context\nmanager handles the entry into, and the exit from, the desired
runtime\ncontext for the execution of the block of code. Context managers
are\nnormally invoked using the ``with`` statement (described in
section\n*The with statement*), but can also be used by directly invoking
their\nmethods.\n\nTypical uses of context managers include saving and
restoring various\nkinds of global state, locking and unlocking resources,
closing opened\nfiles, etc.\n\nFor more information on context managers,
see *Context Manager Types*.\n\nobject.__enter__(self)\n\n Enter the
runtime context related to this object. The ``with``\n statement will
bind this method\'s return value to the target(s)\n specified in the
``as`` clause of the statement, if any.\n\nobject.__exit__(self, exc_type,
exc_value, traceback)\n\n Exit the runtime context related to this
object. The parameters\n describe the exception that caused the context
to be exited. If the\n context was exited without an exception, all three
arguments will\n be ``None``.\n\n If an exception is supplied, and the
method wishes to suppress the\n exception (i.e., prevent it from being
propagated), it should\n return a true value. Otherwise, the exception
will be processed\n normally upon exit from this method.\n\n Note that
``__exit__()`` methods should not reraise the passed-in\n exception; this
is the caller\'s responsibility.\n\nSee also:\n\n **PEP 0343** - The
"with" statement\n The specification, background, and
examples for the Python\n ``with`` statement.\n\n\nSpecial method
lookup for old-style
classes\n===========================================\n\nFor old-style
classes, special methods are always looked up in exactly\nthe same way as
any other method or attribute. This is the case\nregardless of whether the
method is being looked up explicitly as in\n``x.__getitem__(i)`` or
implicitly as in ``x[i]``.\n\nThis behaviour means that special methods may
exhibit different\nbehaviour for different instances of a single old-style
class if the\nappropriate special attributes are set differently:\n\n
>>> class C:\n ... pass\n ...\n >>> c1 = C()\n
>>> c2 = C()\n >>> c1.__len__ = lambda: 5\n
>>> c2.__len__ = lambda: 9\n >>> len(c1)\n 5\n
>>> len(c2)\n 9\n\n\nSpecial method lookup for new-style
classes\n===========================================\n\nFor new-style
classes, implicit invocations of special methods are\nonly guaranteed to
work correctly if defined on an object\'s type, not\nin the
object\'s instance dictionary. That behaviour is the reason why\nthe
following code raises an exception (unlike the equivalent example\nwith
old-style classes):\n\n >>> class C(object):\n ... pass\n
...\n >>> c = C()\n >>> c.__len__ = lambda: 5\n
>>> len(c)\n Traceback (most recent call last):\n File
"<stdin>", line 1, in <module>\n TypeError: object
of type \'C\' has no len()\n\nThe rationale behind this behaviour
lies with a number of special\nmethods such as ``__hash__()`` and
``__repr__()`` that are implemented\nby all objects, including type
objects. If the implicit lookup of\nthese methods used the conventional
lookup process, they would fail\nwhen invoked on the type object
itself:\n\n >>> 1 .__hash__() == hash(1)\n True\n
>>> int.__hash__() == hash(int)\n Traceback (most recent call
last):\n File "<stdin>", line 1, in <module>\n
TypeError: descriptor \'__hash__\' of \'int\' object
needs an argument\n\nIncorrectly attempting to invoke an unbound method of
a class in this\nway is sometimes referred to as \'metaclass
confusion\', and is avoided\nby bypassing the instance when looking up
special methods:\n\n >>> type(1).__hash__(1) == hash(1)\n
True\n >>> type(int).__hash__(int) == hash(int)\n True\n\nIn
addition to bypassing any instance attributes in the interest
of\ncorrectness, implicit special method lookup generally also
bypasses\nthe ``__getattribute__()`` method even of the object\'s
metaclass:\n\n >>> class Meta(type):\n ... def
__getattribute__(*args):\n ... print "Metaclass getattribute
invoked"\n ... return type.__getattribute__(*args)\n ...\n
>>> class C(object):\n ... __metaclass__ = Meta\n ...
def __len__(self):\n ... return 10\n ... def
__getattribute__(*args):\n ... print "Class getattribute
invoked"\n ... return object.__getattribute__(*args)\n
...\n >>> c = C()\n >>> c.__len__() #
Explicit lookup via instance\n Class getattribute invoked\n 10\n
>>> type(c).__len__(c) # Explicit lookup via type\n
Metaclass getattribute invoked\n 10\n >>> len(c)
# Implicit lookup\n 10\n\nBypassing the ``__getattribute__()``
machinery in this fashion\nprovides significant scope for speed
optimisations within the\ninterpreter, at the cost of some flexibility in
the handling of\nspecial methods (the special method *must* be set on the
class object\nitself in order to be consistently invoked by the
interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to
change an object\'s type, under\n certain controlled conditions. It
generally isn\'t a good idea\n though, since it can lead to some
very strange behaviour if it is\n handled incorrectly.\n\n[2] For
operands of the same type, it is assumed that if the non-\n reflected
method (such as ``__add__()``) fails the operation is\n not supported,
which is why the reflected method is not called.\n',
'string-methods': '\nString
Methods\n**************\n\nBelow are listed the string methods which both
8-bit strings and\nUnicode objects support. Some of them are also
available on\n``bytearray`` objects.\n\nIn addition, Python\'s strings
support the sequence type methods\ndescribed in the *Sequence Types ---
str, unicode, list, tuple,\nbytearray, buffer, xrange* section. To output
formatted strings use\ntemplate strings or the ``%`` operator described in
the *String\nFormatting Operations* section. Also, see the ``re`` module
for string\nfunctions based on regular expressions.\n\nstr.capitalize()\n\n
Return a copy of the string with its first character capitalized\n and
the rest lowercased.\n\n For 8-bit strings, this method is
locale-dependent.\n\nstr.center(width[, fillchar])\n\n Return centered in
a string of length *width*. Padding is done\n using the specified
*fillchar* (default is a space).\n\n Changed in version 2.4: Support for
the *fillchar* argument.\n\nstr.count(sub[, start[, end]])\n\n Return the
number of non-overlapping occurrences of substring *sub*\n in the range
[*start*, *end*]. Optional arguments *start* and\n *end* are interpreted
as in slice notation.\n\nstr.decode([encoding[, errors]])\n\n Decodes the
string using the codec registered for *encoding*.\n *encoding* defaults
to the default string encoding. *errors* may\n be given to set a
different error handling scheme. The default is\n
``\'strict\'``, meaning that encoding errors raise
``UnicodeError``.\n Other possible values are ``\'ignore\'``,
``\'replace\'`` and any other\n name registered via
``codecs.register_error()``, see section *Codec\n Base Classes*.\n\n
New in version 2.2.\n\n Changed in version 2.3: Support for other error
handling schemes\n added.\n\n Changed in version 2.7: Support for
keyword arguments added.\n\nstr.encode([encoding[, errors]])\n\n Return
an encoded version of the string. Default encoding is the\n current
default string encoding. *errors* may be given to set a\n different
error handling scheme. The default for *errors* is\n
``\'strict\'``, meaning that encoding errors raise a\n
``UnicodeError``. Other possible values are ``\'ignore\'``,\n
``\'replace\'``, ``\'xmlcharrefreplace\'``,
``\'backslashreplace\'`` and\n any other name registered via
``codecs.register_error()``, see\n section *Codec Base Classes*. For a
list of possible encodings, see\n section *Standard Encodings*.\n\n New
in version 2.0.\n\n Changed in version 2.3: Support for
``\'xmlcharrefreplace\'`` and\n
``\'backslashreplace\'`` and other error handling schemes
added.\n\n Changed in version 2.7: Support for keyword arguments
added.\n\nstr.endswith(suffix[, start[, end]])\n\n Return ``True`` if the
string ends with the specified *suffix*,\n otherwise return ``False``.
*suffix* can also be a tuple of\n suffixes to look for. With optional
*start*, test beginning at\n that position. With optional *end*, stop
comparing at that\n position.\n\n Changed in version 2.5: Accept tuples
as *suffix*.\n\nstr.expandtabs([tabsize])\n\n Return a copy of the string
where all tab characters are replaced\n by one or more spaces, depending
on the current column and the\n given tab size. Tab positions occur
every *tabsize* characters\n (default is 8, giving tab positions at
columns 0, 8, 16 and so on).\n To expand the string, the current column
is set to zero and the\n string is examined character by character. If
the character is a\n tab (``\\t``), one or more space characters are
inserted in the\n result until the current column is equal to the next
tab position.\n (The tab character itself is not copied.) If the
character is a\n newline (``\\n``) or return (``\\r``), it is copied and
the current\n column is reset to zero. Any other character is copied
unchanged\n and the current column is incremented by one regardless of
how the\n character is represented when printed.\n\n >>>
\'01\\t012\\t0123\\t01234\'.expandtabs()\n \'01 012
0123 01234\'\n >>>
\'01\\t012\\t0123\\t01234\'.expandtabs(4)\n \'01 012 0123
01234\'\n\nstr.find(sub[, start[, end]])\n\n Return the lowest
index in the string where substring *sub* is\n found, such that *sub* is
contained in the slice ``s[start:end]``.\n Optional arguments *start* and
*end* are interpreted as in slice\n notation. Return ``-1`` if *sub* is
not found.\n\n Note: The ``find()`` method should be used only if you
need to know the\n position of *sub*. To check if *sub* is a substring
or not, use\n the ``in`` operator:\n\n >>>
\'Py\' in \'Python\'\n True\n\nstr.format(*args,
**kwargs)\n\n Perform a string formatting operation. The string on which
this\n method is called can contain literal text or replacement fields\n
delimited by braces ``{}``. Each replacement field contains either\n
the numeric index of a positional argument, or the name of a\n keyword
argument. Returns a copy of the string where each\n replacement field is
replaced with the string value of the\n corresponding argument.\n\n
>>> "The sum of 1 + 2 is {0}".format(1+2)\n \'The
sum of 1 + 2 is 3\'\n\n See *Format String Syntax* for a description
of the various\n formatting options that can be specified in format
strings.\n\n This method of string formatting is the new standard in
Python 3,\n and should be preferred to the ``%`` formatting described
in\n *String Formatting Operations* in new code.\n\n New in version
2.6.\n\nstr.index(sub[, start[, end]])\n\n Like ``find()``, but raise
``ValueError`` when the substring is not\n found.\n\nstr.isalnum()\n\n
Return true if all characters in the string are alphanumeric and\n there
is at least one character, false otherwise.\n\n For 8-bit strings, this
method is locale-dependent.\n\nstr.isalpha()\n\n Return true if all
characters in the string are alphabetic and\n there is at least one
character, false otherwise.\n\n For 8-bit strings, this method is
locale-dependent.\n\nstr.isdigit()\n\n Return true if all characters in
the string are digits and there is\n at least one character, false
otherwise.\n\n For 8-bit strings, this method is
locale-dependent.\n\nstr.islower()\n\n Return true if all cased
characters [4] in the string are lowercase\n and there is at least one
cased character, false otherwise.\n\n For 8-bit strings, this method is
locale-dependent.\n\nstr.isspace()\n\n Return true if there are only
whitespace characters in the string\n and there is at least one
character, false otherwise.\n\n For 8-bit strings, this method is
locale-dependent.\n\nstr.istitle()\n\n Return true if the string is a
titlecased string and there is at\n least one character, for example
uppercase characters may only\n follow uncased characters and lowercase
characters only cased ones.\n Return false otherwise.\n\n For 8-bit
strings, this method is locale-dependent.\n\nstr.isupper()\n\n Return
true if all cased characters [4] in the string are uppercase\n and there
is at least one cased character, false otherwise.\n\n For 8-bit strings,
this method is locale-dependent.\n\nstr.join(iterable)\n\n Return a
string which is the concatenation of the strings in the\n *iterable*
*iterable*. The separator between elements is the\n string providing
this method.\n\nstr.ljust(width[, fillchar])\n\n Return the string left
justified in a string of length *width*.\n Padding is done using the
specified *fillchar* (default is a\n space). The original string is
returned if *width* is less than or\n equal to ``len(s)``.\n\n Changed
in version 2.4: Support for the *fillchar* argument.\n\nstr.lower()\n\n
Return a copy of the string with all the cased characters [4]\n converted
to lowercase.\n\n For 8-bit strings, this method is
locale-dependent.\n\nstr.lstrip([chars])\n\n Return a copy of the string
with leading characters removed. The\n *chars* argument is a string
specifying the set of characters to be\n removed. If omitted or
``None``, the *chars* argument defaults to\n removing whitespace. The
*chars* argument is not a prefix; rather,\n all combinations of its
values are stripped:\n\n >>> \' spacious
\'.lstrip()\n \'spacious \'\n >>>
\'www.example.com\'.lstrip(\'cmowz.\')\n
\'example.com\'\n\n Changed in version 2.2.2: Support for the
*chars* argument.\n\nstr.partition(sep)\n\n Split the string at the first
occurrence of *sep*, and return a\n 3-tuple containing the part before
the separator, the separator\n itself, and the part after the separator.
If the separator is not\n found, return a 3-tuple containing the string
itself, followed by\n two empty strings.\n\n New in version
2.5.\n\nstr.replace(old, new[, count])\n\n Return a copy of the string
with all occurrences of substring *old*\n replaced by *new*. If the
optional argument *count* is given, only\n the first *count* occurrences
are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n Return the highest
index in the string where substring *sub* is\n found, such that *sub* is
contained within ``s[start:end]``.\n Optional arguments *start* and *end*
are interpreted as in slice\n notation. Return ``-1`` on
failure.\n\nstr.rindex(sub[, start[, end]])\n\n Like ``rfind()`` but
raises ``ValueError`` when the substring *sub*\n is not
found.\n\nstr.rjust(width[, fillchar])\n\n Return the string right
justified in a string of length *width*.\n Padding is done using the
specified *fillchar* (default is a\n space). The original string is
returned if *width* is less than or\n equal to ``len(s)``.\n\n Changed
in version 2.4: Support for the *fillchar*
argument.\n\nstr.rpartition(sep)\n\n Split the string at the last
occurrence of *sep*, and return a\n 3-tuple containing the part before
the separator, the separator\n itself, and the part after the separator.
If the separator is not\n found, return a 3-tuple containing two empty
strings, followed by\n the string itself.\n\n New in version
2.5.\n\nstr.rsplit([sep[, maxsplit]])\n\n Return a list of the words in
the string, using *sep* as the\n delimiter string. If *maxsplit* is
given, at most *maxsplit* splits\n are done, the *rightmost* ones. If
*sep* is not specified or\n ``None``, any whitespace string is a
separator. Except for\n splitting from the right, ``rsplit()`` behaves
like ``split()``\n which is described in detail below.\n\n New in
version 2.4.\n\nstr.rstrip([chars])\n\n Return a copy of the string with
trailing characters removed. The\n *chars* argument is a string
specifying the set of characters to be\n removed. If omitted or
``None``, the *chars* argument defaults to\n removing whitespace. The
*chars* argument is not a suffix; rather,\n all combinations of its
values are stripped:\n\n >>> \' spacious
\'.rstrip()\n \' spacious\'\n >>>
\'mississippi\'.rstrip(\'ipz\')\n
\'mississ\'\n\n Changed in version 2.2.2: Support for the
*chars* argument.\n\nstr.split([sep[, maxsplit]])\n\n Return a list of
the words in the string, using *sep* as the\n delimiter string. If
*maxsplit* is given, at most *maxsplit*\n splits are done (thus, the list
will have at most ``maxsplit+1``\n elements). If *maxsplit* is not
specified or ``-1``, then there is\n no limit on the number of splits
(all possible splits are made).\n\n If *sep* is given, consecutive
delimiters are not grouped together\n and are deemed to delimit empty
strings (for example,\n ``\'1,,2\'.split(\',\')``
returns ``[\'1\', \'\', \'2\']``). The
*sep*\n argument may consist of multiple characters (for example,\n
``\'1<>2<>3\'.split(\'<>\')`` returns
``[\'1\', \'2\', \'3\']``). Splitting\n an
empty string with a specified separator returns ``[\'\']``.\n\n
If *sep* is not specified or is ``None``, a different splitting\n
algorithm is applied: runs of consecutive whitespace are regarded\n as a
single separator, and the result will contain no empty strings\n at the
start or end if the string has leading or trailing\n whitespace.
Consequently, splitting an empty string or a string\n consisting of just
whitespace with a ``None`` separator returns\n ``[]``.\n\n For example,
``\' 1 2 3 \'.split()`` returns ``[\'1\',
\'2\', \'3\']``,\n and ``\' 1 2 3
\'.split(None, 1)`` returns ``[\'1\', \'2 3
\']``.\n\nstr.splitlines([keepends])\n\n Return a list of the lines
in the string, breaking at line\n boundaries. This method uses the
*universal newlines* approach to\n splitting lines. Line breaks are not
included in the resulting list\n unless *keepends* is given and true.\n\n
For example, ``\'ab c\\n\\nde fg\\rkl\\r\\n\'.splitlines()``
returns\n ``[\'ab c\', \'\', \'de fg\',
\'kl\']``, while the same call with\n ``splitlines(True)``
returns ``[\'ab c\\n\', \'\\n\', \'de
fg\\r\',\n \'kl\\r\\n\']``.\n\n Unlike ``split()`` when
a delimiter string *sep* is given, this\n method returns an empty list
for the empty string, and a terminal\n line break does not result in an
extra line.\n\nstr.startswith(prefix[, start[, end]])\n\n Return ``True``
if string starts with the *prefix*, otherwise\n return ``False``.
*prefix* can also be a tuple of prefixes to look\n for. With optional
*start*, test string beginning at that\n position. With optional *end*,
stop comparing string at that\n position.\n\n Changed in version 2.5:
Accept tuples as *prefix*.\n\nstr.strip([chars])\n\n Return a copy of the
string with the leading and trailing\n characters removed. The *chars*
argument is a string specifying the\n set of characters to be removed. If
omitted or ``None``, the\n *chars* argument defaults to removing
whitespace. The *chars*\n argument is not a prefix or suffix; rather, all
combinations of its\n values are stripped:\n\n >>> \'
spacious \'.strip()\n \'spacious\'\n >>>
\'www.example.com\'.strip(\'cmowz.\')\n
\'example\'\n\n Changed in version 2.2.2: Support for the
*chars* argument.\n\nstr.swapcase()\n\n Return a copy of the string with
uppercase characters converted to\n lowercase and vice versa.\n\n For
8-bit strings, this method is locale-dependent.\n\nstr.title()\n\n Return
a titlecased version of the string where words start with an\n uppercase
character and the remaining characters are lowercase.\n\n The algorithm
uses a simple language-independent definition of a\n word as groups of
consecutive letters. The definition works in\n many contexts but it
means that apostrophes in contractions and\n possessives form word
boundaries, which may not be the desired\n result:\n\n >>>
"they\'re bill\'s friends from the UK".title()\n
"They\'Re Bill\'S Friends From The Uk"\n\n A
workaround for apostrophes can be constructed using regular\n
expressions:\n\n >>> import re\n >>> def
titlecase(s):\n ... return
re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n ...
lambda mo: mo.group(0)[0].upper() +\n ...
mo.group(0)[1:].lower(),\n ... s)\n ...\n
>>> titlecase("they\'re bill\'s friends.")\n
"They\'re Bill\'s Friends."\n\n For 8-bit
strings, this method is locale-dependent.\n\nstr.translate(table[,
deletechars])\n\n Return a copy of the string where all characters
occurring in the\n optional argument *deletechars* are removed, and the
remaining\n characters have been mapped through the given translation
table,\n which must be a string of length 256.\n\n You can use the
``maketrans()`` helper function in the ``string``\n module to create a
translation table. For string objects, set the\n *table* argument to
``None`` for translations that only delete\n characters:\n\n
>>> \'read this short text\'.translate(None,
\'aeiou\')\n \'rd ths shrt txt\'\n\n New in version
2.6: Support for a ``None`` *table* argument.\n\n For Unicode objects,
the ``translate()`` method does not accept the\n optional *deletechars*
argument. Instead, it returns a copy of the\n *s* where all characters
have been mapped through the given\n translation table which must be a
mapping of Unicode ordinals to\n Unicode ordinals, Unicode strings or
``None``. Unmapped characters\n are left untouched. Characters mapped to
``None`` are deleted.\n Note, a more flexible approach is to create a
custom character\n mapping codec using the ``codecs`` module (see
``encodings.cp1251``\n for an example).\n\nstr.upper()\n\n Return a
copy of the string with all the cased characters [4]\n converted to
uppercase. Note that ``str.upper().isupper()`` might\n be ``False`` if
``s`` contains uncased characters or if the Unicode\n category of the
resulting character(s) is not "Lu" (Letter,\n uppercase), but
e.g. "Lt" (Letter, titlecase).\n\n For 8-bit strings, this
method is locale-dependent.\n\nstr.zfill(width)\n\n Return the numeric
string left filled with zeros in a string of\n length *width*. A sign
prefix is handled correctly. The original\n string is returned if
*width* is less than or equal to ``len(s)``.\n\n New in version
2.2.2.\n\nThe following methods are present only on unicode
objects:\n\nunicode.isnumeric()\n\n Return ``True`` if there are only
numeric characters in S,\n ``False`` otherwise. Numeric characters
include digit characters,\n and all characters that have the Unicode
numeric value property,\n e.g. U+2155, VULGAR FRACTION ONE
FIFTH.\n\nunicode.isdecimal()\n\n Return ``True`` if there are only
decimal characters in S,\n ``False`` otherwise. Decimal characters
include digit characters,\n and all characters that can be used to form
decimal-radix numbers,\n e.g. U+0660, ARABIC-INDIC DIGIT ZERO.\n',
'strings': '\nString literals\n***************\n\nString
literals are described by the following lexical definitions:\n\n
stringliteral ::= [stringprefix](shortstring | longstring)\n
stringprefix ::= "r" | "u" | "ur" |
"R" | "U" | "UR" | "Ur" |
"uR"\n | "b" | "B" |
"br" | "Br" | "bR" | "BR"\n
shortstring ::= "\'" shortstringitem*
"\'" | \'"\' shortstringitem*
\'"\'\n longstring ::=
"\'\'\'" longstringitem*
"\'\'\'"\n |
\'"""\' longstringitem*
\'"""\'\n shortstringitem ::= shortstringchar |
escapeseq\n longstringitem ::= longstringchar | escapeseq\n
shortstringchar ::= <any source character except "\\" or
newline or the quote>\n longstringchar ::= <any source character
except "\\">\n escapeseq ::= "\\" <any
ASCII character>\n\nOne syntactic restriction not indicated by these
productions is that\nwhitespace is not allowed between the ``stringprefix``
and the rest of\nthe string literal. The source character set is defined by
the\nencoding declaration; it is ASCII if no encoding declaration is
given\nin the source file; see section *Encoding declarations*.\n\nIn plain
English: String literals can be enclosed in matching single\nquotes
(``\'``) or double quotes (``"``). They can also be enclosed
in\nmatching groups of three single or double quotes (these are
generally\nreferred to as *triple-quoted strings*). The backslash
(``\\``)\ncharacter is used to escape characters that otherwise have a
special\nmeaning, such as newline, backslash itself, or the quote
character.\nString literals may optionally be prefixed with a letter
``\'r\'`` or\n``\'R\'``; such strings are called *raw
strings* and use different rules\nfor interpreting backslash escape
sequences. A prefix of ``\'u\'`` or\n``\'U\'`` makes
the string a Unicode string. Unicode strings use the\nUnicode character
set as defined by the Unicode Consortium and ISO\n10646. Some additional
escape sequences, described below, are\navailable in Unicode strings. A
prefix of ``\'b\'`` or ``\'B\'`` is\nignored in Python
2; it indicates that the literal should become a\nbytes literal in Python 3
(e.g. when code is automatically converted\nwith 2to3). A
``\'u\'`` or ``\'b\'`` prefix may be followed by an
``\'r\'``\nprefix.\n\nIn triple-quoted strings, unescaped
newlines and quotes are allowed\n(and are retained), except that three
unescaped quotes in a row\nterminate the string. (A "quote" is
the character used to open the\nstring, i.e. either ``\'`` or
``"``.)\n\nUnless an ``\'r\'`` or ``\'R\'`` prefix
is present, escape sequences in\nstrings are interpreted according to rules
similar to those used by\nStandard C. The recognized escape sequences
are:\n\n+-------------------+-----------------------------------+---------+\n|
Escape Sequence | Meaning | Notes
|\n+===================+===================================+=========+\n|
``\\newline`` | Ignored |
|\n+-------------------+-----------------------------------+---------+\n|
``\\\\`` | Backslash (``\\``) |
|\n+-------------------+-----------------------------------+---------+\n|
``\\\'`` | Single quote (``\'``) |
|\n+-------------------+-----------------------------------+---------+\n|
``\\"`` | Double quote (``"``) |
|\n+-------------------+-----------------------------------+---------+\n|
``\\a`` | ASCII Bell (BEL) |
|\n+-------------------+-----------------------------------+---------+\n|
``\\b`` | ASCII Backspace (BS) |
|\n+-------------------+-----------------------------------+---------+\n|
``\\f`` | ASCII Formfeed (FF) |
|\n+-------------------+-----------------------------------+---------+\n|
``\\n`` | ASCII Linefeed (LF) |
|\n+-------------------+-----------------------------------+---------+\n|
``\\N{name}`` | Character named *name* in the | |\n|
| Unicode database (Unicode only) |
|\n+-------------------+-----------------------------------+---------+\n|
``\\r`` | ASCII Carriage Return (CR) |
|\n+-------------------+-----------------------------------+---------+\n|
``\\t`` | ASCII Horizontal Tab (TAB) |
|\n+-------------------+-----------------------------------+---------+\n|
``\\uxxxx`` | Character with 16-bit hex value | (1) |\n|
| *xxxx* (Unicode only) |
|\n+-------------------+-----------------------------------+---------+\n|
``\\Uxxxxxxxx`` | Character with 32-bit hex value | (2) |\n|
| *xxxxxxxx* (Unicode only) |
|\n+-------------------+-----------------------------------+---------+\n|
``\\v`` | ASCII Vertical Tab (VT) |
|\n+-------------------+-----------------------------------+---------+\n|
``\\ooo`` | Character with octal value *ooo* | (3,5)
|\n+-------------------+-----------------------------------+---------+\n|
``\\xhh`` | Character with hex value *hh* | (4,5)
|\n+-------------------+-----------------------------------+---------+\n\nNotes:\n\n1.
Individual code units which form parts of a surrogate pair can be\n
encoded using this escape sequence.\n\n2. Any Unicode character can be
encoded this way, but characters\n outside the Basic Multilingual Plane
(BMP) will be encoded using a\n surrogate pair if Python is compiled to
use 16-bit code units (the\n default). Individual code units which form
parts of a surrogate\n pair can be encoded using this escape
sequence.\n\n3. As in Standard C, up to three octal digits are
accepted.\n\n4. Unlike in Standard C, exactly two hex digits are
required.\n\n5. In a string literal, hexadecimal and octal escapes denote
the byte\n with the given value; it is not necessary that the byte
encodes a\n character in the source character set. In a Unicode literal,
these\n escapes denote a Unicode character with the given
value.\n\nUnlike Standard C, all unrecognized escape sequences are left in
the\nstring unchanged, i.e., *the backslash is left in the string*.
(This\nbehavior is useful when debugging: if an escape sequence is
mistyped,\nthe resulting output is more easily recognized as broken.) It
is also\nimportant to note that the escape sequences marked as
"(Unicode only)"\nin the table above fall into the category of
unrecognized escapes for\nnon-Unicode string literals.\n\nWhen an
``\'r\'`` or ``\'R\'`` prefix is present, a character
following a\nbackslash is included in the string without change, and
*all\nbackslashes are left in the string*. For example, the string
literal\n``r"\\n"`` consists of two characters: a backslash and a
lowercase\n``\'n\'``. String quotes can be escaped with a
backslash, but the\nbackslash remains in the string; for example,
``r"\\""`` is a valid\nstring literal consisting of two
characters: a backslash and a double\nquote; ``r"\\"`` is not a
valid string literal (even a raw string\ncannot end in an odd number of
backslashes). Specifically, *a raw\nstring cannot end in a single
backslash* (since the backslash would\nescape the following quote
character). Note also that a single\nbackslash followed by a newline is
interpreted as those two characters\nas part of the string, *not* as a line
continuation.\n\nWhen an ``\'r\'`` or ``\'R\'`` prefix
is used in conjunction with a\n``\'u\'`` or ``\'U\'``
prefix, then the ``\\uXXXX`` and ``\\UXXXXXXXX``\nescape sequences are
processed while *all other backslashes are left\nin the string*. For
example, the string literal ``ur"\\u0062\\n"``\nconsists of three
Unicode characters: \'LATIN SMALL LETTER B\',
\'REVERSE\nSOLIDUS\', and \'LATIN SMALL LETTER N\'.
Backslashes can be escaped with\na preceding backslash; however, both
remain in the string. As a\nresult, ``\\uXXXX`` escape sequences are only
recognized when there are\nan odd number of backslashes.\n',
'subscriptions': '\nSubscriptions\n*************\n\nA
subscription selects an item of a sequence (string, tuple or list)\nor
mapping (dictionary) object:\n\n subscription ::= primary "["
expression_list "]"\n\nThe primary must evaluate to an object of
a sequence or mapping type.\n\nIf the primary is a mapping, the expression
list must evaluate to an\nobject whose value is one of the keys of the
mapping, and the\nsubscription selects the value in the mapping that
corresponds to that\nkey. (The expression list is a tuple except if it has
exactly one\nitem.)\n\nIf the primary is a sequence, the expression (list)
must evaluate to a\nplain integer. If this value is negative, the length
of the sequence\nis added to it (so that, e.g., ``x[-1]`` selects the last
item of\n``x``.) The resulting value must be a nonnegative integer less
than\nthe number of items in the sequence, and the subscription selects
the\nitem whose index is that value (counting from zero).\n\nA
string\'s items are characters. A character is not a separate
data\ntype but a string of exactly one character.\n',
'truth': "\nTruth Value Testing\n*******************\n\nAny
object can be tested for truth value, for use in an ``if`` or\n``while``
condition or as operand of the Boolean operations below. The\nfollowing
values are considered false:\n\n* ``None``\n\n* ``False``\n\n* zero of any
numeric type, for example, ``0``, ``0L``, ``0.0``,\n ``0j``.\n\n* any
empty sequence, for example, ``''``, ``()``, ``[]``.\n\n* any
empty mapping, for example, ``{}``.\n\n* instances of user-defined classes,
if the class defines a\n ``__nonzero__()`` or ``__len__()`` method, when
that method returns\n the integer zero or ``bool`` value ``False``.
[1]\n\nAll other values are considered true --- so objects of many types
are\nalways true.\n\nOperations and built-in functions that have a Boolean
result always\nreturn ``0`` or ``False`` for false and ``1`` or ``True``
for true,\nunless otherwise stated. (Important exception: the Boolean
operations\n``or`` and ``and`` always return one of their
operands.)\n",
'try': '\nThe ``try``
statement\n*********************\n\nThe ``try`` statement specifies
exception handlers and/or cleanup code\nfor a group of statements:\n\n
try_stmt ::= try1_stmt | try2_stmt\n try1_stmt ::= "try"
":" suite\n ("except" [expression
[("as" | ",") target]] ":" suite)+\n
["else" ":" suite]\n
["finally" ":" suite]\n try2_stmt ::= "try"
":" suite\n "finally" ":"
suite\n\nChanged in version 2.5: In previous versions of
Python,\n``try``...``except``...``finally`` did not work.
``try``...``except``\nhad to be nested in ``try``...``finally``.\n\nThe
``except`` clause(s) specify one or more exception handlers. When\nno
exception occurs in the ``try`` clause, no exception handler is\nexecuted.
When an exception occurs in the ``try`` suite, a search for\nan exception
handler is started. This search inspects the except\nclauses in turn until
one is found that matches the exception. An\nexpression-less except
clause, if present, must be last; it matches\nany exception. For an except
clause with an expression, that\nexpression is evaluated, and the clause
matches the exception if the\nresulting object is "compatible"
with the exception. An object is\ncompatible with an exception if it is
the class or a base class of the\nexception object, or a tuple containing
an item compatible with the\nexception.\n\nIf no except clause matches the
exception, the search for an exception\nhandler continues in the
surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of
an expression in the header of an except clause\nraises an exception, the
original search for a handler is canceled and\na search starts for the new
exception in the surrounding code and on\nthe call stack (it is treated as
if the entire ``try`` statement\nraised the exception).\n\nWhen a matching
except clause is found, the exception is assigned to\nthe target specified
in that except clause, if present, and the except\nclause\'s suite is
executed. All except clauses must have an\nexecutable block. When the end
of this block is reached, execution\ncontinues normally after the entire
try statement. (This means that\nif two nested handlers exist for the same
exception, and the exception\noccurs in the try clause of the inner
handler, the outer handler will\nnot handle the exception.)\n\nBefore an
except clause\'s suite is executed, details about the\nexception are
assigned to three variables in the ``sys`` module:\n``sys.exc_type``
receives the object identifying the exception;\n``sys.exc_value`` receives
the exception\'s parameter;\n``sys.exc_traceback`` receives a
traceback object (see section *The\nstandard type hierarchy*) identifying
the point in the program where\nthe exception occurred. These details are
also available through the\n``sys.exc_info()`` function, which returns a
tuple ``(exc_type,\nexc_value, exc_traceback)``. Use of the corresponding
variables is\ndeprecated in favor of this function, since their use is
unsafe in a\nthreaded program. As of Python 1.5, the variables are
restored to\ntheir previous values (before the call) when returning from a
function\nthat handled an exception.\n\nThe optional ``else`` clause is
executed if and when control flows off\nthe end of the ``try`` clause. [2]
Exceptions in the ``else`` clause\nare not handled by the preceding
``except`` clauses.\n\nIf ``finally`` is present, it specifies a
\'cleanup\' handler. The\n``try`` clause is executed, including
any ``except`` and ``else``\nclauses. If an exception occurs in any of the
clauses and is not\nhandled, the exception is temporarily saved. The
``finally`` clause is\nexecuted. If there is a saved exception, it is
re-raised at the end\nof the ``finally`` clause. If the ``finally`` clause
raises another\nexception or executes a ``return`` or ``break`` statement,
the saved\nexception is discarded:\n\n def f():\n try:\n
1/0\n finally:\n return 42\n\n >>> f()\n
42\n\nThe exception information is not available to the program
during\nexecution of the ``finally`` clause.\n\nWhen a ``return``,
``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a
``try``...``finally`` statement, the\n``finally`` clause is also executed
\'on the way out.\' A ``continue``\nstatement is illegal in the
``finally`` clause. (The reason is a\nproblem with the current
implementation --- this restriction may be\nlifted in the
future).\n\nAdditional information on exceptions can be found in
section\n*Exceptions*, and information on using the ``raise`` statement
to\ngenerate exceptions may be found in section *The raise
statement*.\n',
'types': '\nThe standard type
hierarchy\n***************************\n\nBelow is a list of the types that
are built into Python. Extension\nmodules (written in C, Java, or other
languages, depending on the\nimplementation) can define additional types.
Future versions of\nPython may add types to the type hierarchy (e.g.,
rational numbers,\nefficiently stored arrays of integers, etc.).\n\nSome of
the type descriptions below contain a paragraph listing\n\'special
attributes.\' These are attributes that provide access to
the\nimplementation and are not intended for general use. Their
definition\nmay change in the future.\n\nNone\n This type has a single
value. There is a single object with this\n value. This object is
accessed through the built-in name ``None``.\n It is used to signify the
absence of a value in many situations,\n e.g., it is returned from
functions that don\'t explicitly return\n anything. Its truth value
is false.\n\nNotImplemented\n This type has a single value. There is a
single object with this\n value. This object is accessed through the
built-in name\n ``NotImplemented``. Numeric methods and rich comparison
methods may\n return this value if they do not implement the operation
for the\n operands provided. (The interpreter will then try the
reflected\n operation, or some other fallback, depending on the
operator.) Its\n truth value is true.\n\nEllipsis\n This type has a
single value. There is a single object with this\n value. This object is
accessed through the built-in name\n ``Ellipsis``. It is used to indicate
the presence of the ``...``\n syntax in a slice. Its truth value is
true.\n\n``numbers.Number``\n These are created by numeric literals and
returned as results by\n arithmetic operators and arithmetic built-in
functions. Numeric\n objects are immutable; once created their value
never changes.\n Python numbers are of course strongly related to
mathematical\n numbers, but subject to the limitations of numerical
representation\n in computers.\n\n Python distinguishes between
integers, floating point numbers, and\n complex numbers:\n\n
``numbers.Integral``\n These represent elements from the mathematical
set of integers\n (positive and negative).\n\n There are three
types of integers:\n\n Plain integers\n These represent
numbers in the range -2147483648 through\n 2147483647. (The range
may be larger on machines with a\n larger natural word size, but
not smaller.) When the result\n of an operation would fall outside
this range, the result is\n normally returned as a long integer (in
some cases, the\n exception ``OverflowError`` is raised instead).
For the\n purpose of shift and mask operations, integers are
assumed to\n have a binary, 2\'s complement notation using 32
or more bits,\n and hiding no bits from the user (i.e., all
4294967296\n different bit patterns correspond to different
values).\n\n Long integers\n These represent numbers in an
unlimited range, subject to\n available (virtual) memory only. For
the purpose of shift\n and mask operations, a binary representation
is assumed, and\n negative numbers are represented in a variant of
2\'s\n complement which gives the illusion of an infinite
string of\n sign bits extending to the left.\n\n Booleans\n
These represent the truth values False and True. The two\n
objects representing the values False and True are the only\n
Boolean objects. The Boolean type is a subtype of plain\n integers,
and Boolean values behave like the values 0 and 1,\n respectively,
in almost all contexts, the exception being\n that when converted
to a string, the strings ``"False"`` or\n
``"True"`` are returned, respectively.\n\n The rules for
integer representation are intended to give the\n most meaningful
interpretation of shift and mask operations\n involving negative
integers and the least surprises when\n switching between the plain
and long integer domains. Any\n operation, if it yields a result in
the plain integer domain,\n will yield the same result in the long
integer domain or when\n using mixed operands. The switch between
domains is transparent\n to the programmer.\n\n ``numbers.Real``
(``float``)\n These represent machine-level double precision floating
point\n numbers. You are at the mercy of the underlying machine\n
architecture (and C or Java implementation) for the accepted\n range
and handling of overflow. Python does not support single-\n precision
floating point numbers; the savings in processor and\n memory usage
that are usually the reason for using these is\n dwarfed by the
overhead of using objects in Python, so there is\n no reason to
complicate the language with two kinds of floating\n point
numbers.\n\n ``numbers.Complex``\n These represent complex numbers
as a pair of machine-level\n double precision floating point numbers.
The same caveats apply\n as for floating point numbers. The real and
imaginary parts of a\n complex number ``z`` can be retrieved through
the read-only\n attributes ``z.real`` and ``z.imag``.\n\nSequences\n
These represent finite ordered sets indexed by non-negative\n numbers.
The built-in function ``len()`` returns the number of\n items of a
sequence. When the length of a sequence is *n*, the\n index set contains
the numbers 0, 1, ..., *n*-1. Item *i* of\n sequence *a* is selected by
``a[i]``.\n\n Sequences also support slicing: ``a[i:j]`` selects all
items with\n index *k* such that *i* ``<=`` *k* ``<`` *j*. When
used as an\n expression, a slice is a sequence of the same type. This
implies\n that the index set is renumbered so that it starts at 0.\n\n
Some sequences also support "extended slicing" with a third
"step"\n parameter: ``a[i:j:k]`` selects all items of *a* with
index *x*\n where ``x = i + n*k``, *n* ``>=`` ``0`` and *i* ``<=``
*x* ``<``\n *j*.\n\n Sequences are distinguished according to their
mutability:\n\n Immutable sequences\n An object of an immutable
sequence type cannot change once it is\n created. (If the object
contains references to other objects,\n these other objects may be
mutable and may be changed; however,\n the collection of objects
directly referenced by an immutable\n object cannot change.)\n\n
The following types are immutable sequences:\n\n Strings\n The
items of a string are characters. There is no separate\n character
type; a character is represented by a string of one\n item.
Characters represent (at least) 8-bit bytes. The\n built-in
functions ``chr()`` and ``ord()`` convert between\n characters and
nonnegative integers representing the byte\n values. Bytes with
the values 0-127 usually represent the\n corresponding ASCII
values, but the interpretation of values\n is up to the program.
The string data type is also used to\n represent arrays of bytes,
e.g., to hold data read from a\n file.\n\n (On systems
whose native character set is not ASCII, strings\n may use EBCDIC
in their internal representation, provided the\n functions
``chr()`` and ``ord()`` implement a mapping between\n ASCII and
EBCDIC, and string comparison preserves the ASCII\n order. Or
perhaps someone can propose a better rule?)\n\n Unicode\n The
items of a Unicode object are Unicode code units. A\n Unicode code
unit is represented by a Unicode object of one\n item and can hold
either a 16-bit or 32-bit value\n representing a Unicode ordinal
(the maximum value for the\n ordinal is given in
``sys.maxunicode``, and depends on how\n Python is configured at
compile time). Surrogate pairs may\n be present in the Unicode
object, and will be reported as two\n separate items. The built-in
functions ``unichr()`` and\n ``ord()`` convert between code units
and nonnegative integers\n representing the Unicode ordinals as
defined in the Unicode\n Standard 3.0. Conversion from and to other
encodings are\n possible through the Unicode method ``encode()``
and the\n built-in function ``unicode()``.\n\n Tuples\n
The items of a tuple are arbitrary Python objects. Tuples of\n two
or more items are formed by comma-separated lists of\n expressions.
A tuple of one item (a \'singleton\') can be\n formed by
affixing a comma to an expression (an expression by\n itself does
not create a tuple, since parentheses must be\n usable for grouping
of expressions). An empty tuple can be\n formed by an empty pair
of parentheses.\n\n Mutable sequences\n Mutable sequences can be
changed after they are created. The\n subscription and slicing
notations can be used as the target of\n assignment and ``del``
(delete) statements.\n\n There are currently two intrinsic mutable
sequence types:\n\n Lists\n The items of a list are arbitrary
Python objects. Lists are\n formed by placing a comma-separated
list of expressions in\n square brackets. (Note that there are no
special cases needed\n to form lists of length 0 or 1.)\n\n
Byte Arrays\n A bytearray object is a mutable array. They are
created by\n the built-in ``bytearray()`` constructor. Aside from
being\n mutable (and hence unhashable), byte arrays otherwise
provide\n the same interface and functionality as immutable bytes\n
objects.\n\n The extension module ``array`` provides an
additional example of\n a mutable sequence type.\n\nSet types\n
These represent unordered, finite sets of unique, immutable\n objects. As
such, they cannot be indexed by any subscript. However,\n they can be
iterated over, and the built-in function ``len()``\n returns the number
of items in a set. Common uses for sets are fast\n membership testing,
removing duplicates from a sequence, and\n computing mathematical
operations such as intersection, union,\n difference, and symmetric
difference.\n\n For set elements, the same immutability rules apply as
for\n dictionary keys. Note that numeric types obey the normal rules
for\n numeric comparison: if two numbers compare equal (e.g., ``1`` and\n
``1.0``), only one of them can be contained in a set.\n\n There are
currently two intrinsic set types:\n\n Sets\n These represent a
mutable set. They are created by the built-in\n ``set()`` constructor
and can be modified afterwards by several\n methods, such as
``add()``.\n\n Frozen sets\n These represent an immutable set. They
are created by the\n built-in ``frozenset()`` constructor. As a
frozenset is\n immutable and *hashable*, it can be used again as an
element of\n another set, or as a dictionary key.\n\nMappings\n
These represent finite sets of objects indexed by arbitrary index\n sets.
The subscript notation ``a[k]`` selects the item indexed by\n ``k`` from
the mapping ``a``; this can be used in expressions and\n as the target of
assignments or ``del`` statements. The built-in\n function ``len()``
returns the number of items in a mapping.\n\n There is currently a single
intrinsic mapping type:\n\n Dictionaries\n These represent finite
sets of objects indexed by nearly\n arbitrary values. The only types
of values not acceptable as\n keys are values containing lists or
dictionaries or other\n mutable types that are compared by value
rather than by object\n identity, the reason being that the efficient
implementation of\n dictionaries requires a key\'s hash value to
remain constant.\n Numeric types used for keys obey the normal rules
for numeric\n comparison: if two numbers compare equal (e.g., ``1``
and\n ``1.0``) then they can be used interchangeably to index the
same\n dictionary entry.\n\n Dictionaries are mutable; they can
be created by the ``{...}``\n notation (see section *Dictionary
displays*).\n\n The extension modules ``dbm``, ``gdbm``, and ``bsddb``
provide\n additional examples of mapping types.\n\nCallable types\n
These are the types to which the function call operation (see\n section
*Calls*) can be applied:\n\n User-defined functions\n A user-defined
function object is created by a function\n definition (see section
*Function definitions*). It should be\n called with an argument list
containing the same number of items\n as the function\'s formal
parameter list.\n\n Special attributes:\n\n
+-------------------------+---------------------------------+-------------+\n
| Attribute | Meaning |
|\n
+=========================+=================================+=============+\n
| ``func_doc`` | The function\'s documentation |
Writable |\n | | string, or ``None`` if
| |\n | | unavailable
| |\n
+-------------------------+---------------------------------+-------------+\n
| ``__doc__`` | Another way of spelling | Writable
|\n | | ``func_doc`` |
|\n
+-------------------------+---------------------------------+-------------+\n
| ``func_name`` | The function\'s name |
Writable |\n
+-------------------------+---------------------------------+-------------+\n
| ``__name__`` | Another way of spelling | Writable
|\n | | ``func_name`` |
|\n
+-------------------------+---------------------------------+-------------+\n
| ``__module__`` | The name of the module the | Writable
|\n | | function was defined in, or |
|\n | | ``None`` if unavailable.
| |\n
+-------------------------+---------------------------------+-------------+\n
| ``func_defaults`` | A tuple containing default | Writable
|\n | | argument values for those |
|\n | | arguments that have
defaults, | |\n | | or ``None``
if no arguments | |\n | | have
a default value | |\n
+-------------------------+---------------------------------+-------------+\n
| ``func_code`` | The code object representing | Writable
|\n | | the compiled function body. |
|\n
+-------------------------+---------------------------------+-------------+\n
| ``func_globals`` | A reference to the dictionary |
Read-only |\n | | that holds the
function\'s | |\n | |
global variables --- the global | |\n |
| namespace of the module in | |\n |
| which the function was defined. | |\n
+-------------------------+---------------------------------+-------------+\n
| ``func_dict`` | The namespace supporting | Writable
|\n | | arbitrary function attributes. |
|\n
+-------------------------+---------------------------------+-------------+\n
| ``func_closure`` | ``None`` or a tuple of cells |
Read-only |\n | | that contain bindings for
the | |\n | | function\'s
free variables. | |\n
+-------------------------+---------------------------------+-------------+\n\n
Most of the attributes labelled "Writable" check the type of
the\n assigned value.\n\n Changed in version 2.4: ``func_name``
is now writable.\n\n Function objects also support getting and setting
arbitrary\n attributes, which can be used, for example, to attach
metadata\n to functions. Regular attribute dot-notation is used to
get and\n set such attributes. *Note that the current implementation
only\n supports function attributes on user-defined functions.
Function\n attributes on built-in functions may be supported in the\n
future.*\n\n Additional information about a function\'s
definition can be\n retrieved from its code object; see the
description of internal\n types below.\n\n User-defined methods\n
A user-defined method object combines a class, a class instance\n
(or ``None``) and any callable object (normally a user-defined\n
function).\n\n Special read-only attributes: ``im_self`` is the class
instance\n object, ``im_func`` is the function object; ``im_class`` is
the\n class of ``im_self`` for bound methods or the class that asked\n
for the method for unbound methods; ``__doc__`` is the
method\'s\n documentation (same as ``im_func.__doc__``);
``__name__`` is the\n method name (same as ``im_func.__name__``);
``__module__`` is\n the name of the module the method was defined in,
or ``None`` if\n unavailable.\n\n Changed in version 2.2:
``im_self`` used to refer to the class\n that defined the method.\n\n
Changed in version 2.6: For Python 3 forward-compatibility,\n
``im_func`` is also available as ``__func__``, and ``im_self``\n as
``__self__``.\n\n Methods also support accessing (but not setting) the
arbitrary\n function attributes on the underlying function object.\n\n
User-defined method objects may be created when getting an\n
attribute of a class (perhaps via an instance of that class), if\n
that attribute is a user-defined function object, an unbound\n
user-defined method object, or a class method object. When the\n
attribute is a user-defined method object, a new method object\n is
only created if the class from which it is being retrieved is\n the
same as, or a derived class of, the class stored in the\n original
method object; otherwise, the original method object is\n used as it
is.\n\n When a user-defined method object is created by retrieving a\n
user-defined function object from a class, its ``im_self``\n
attribute is ``None`` and the method object is said to be\n unbound.
When one is created by retrieving a user-defined\n function object
from a class via one of its instances, its\n ``im_self`` attribute is
the instance, and the method object is\n said to be bound. In either
case, the new method\'s ``im_class``\n attribute is the class
from which the retrieval takes place, and\n its ``im_func`` attribute
is the original function object.\n\n When a user-defined method object
is created by retrieving\n another method object from a class or
instance, the behaviour is\n the same as for a function object, except
that the ``im_func``\n attribute of the new instance is not the
original method object\n but its ``im_func`` attribute.\n\n When
a user-defined method object is created by retrieving a\n class method
object from a class or instance, its ``im_self``\n attribute is the
class itself, and its ``im_func`` attribute is\n the function object
underlying the class method.\n\n When an unbound user-defined method
object is called, the\n underlying function (``im_func``) is called,
with the\n restriction that the first argument must be an instance of
the\n proper class (``im_class``) or of a derived class thereof.\n\n
When a bound user-defined method object is called, the\n underlying
function (``im_func``) is called, inserting the class\n instance
(``im_self``) in front of the argument list. For\n instance, when
``C`` is a class which contains a definition for\n a function ``f()``,
and ``x`` is an instance of ``C``, calling\n ``x.f(1)`` is equivalent
to calling ``C.f(x, 1)``.\n\n When a user-defined method object is
derived from a class method\n object, the "class instance"
stored in ``im_self`` will actually\n be the class itself, so that
calling either ``x.f(1)`` or\n ``C.f(1)`` is equivalent to calling
``f(C,1)`` where ``f`` is\n the underlying function.\n\n Note
that the transformation from function object to (unbound or\n bound)
method object happens each time the attribute is\n retrieved from the
class or instance. In some cases, a fruitful\n optimization is to
assign the attribute to a local variable and\n call that local
variable. Also notice that this transformation\n only happens for
user-defined functions; other callable objects\n (and all non-callable
objects) are retrieved without\n transformation. It is also important
to note that user-defined\n functions which are attributes of a class
instance are not\n converted to bound methods; this *only* happens
when the\n function is an attribute of the class.\n\n Generator
functions\n A function or method which uses the ``yield`` statement
(see\n section *The yield statement*) is called a *generator
function*.\n Such a function, when called, always returns an iterator
object\n which can be used to execute the body of the function:
calling\n the iterator\'s ``next()`` method will cause the
function to\n execute until it provides a value using the ``yield``
statement.\n When the function executes a ``return`` statement or
falls off\n the end, a ``StopIteration`` exception is raised and the\n
iterator will have reached the end of the set of values to be\n
returned.\n\n Built-in functions\n A built-in function object is a
wrapper around a C function.\n Examples of built-in functions are
``len()`` and ``math.sin()``\n (``math`` is a standard built-in
module). The number and type of\n the arguments are determined by the
C function. Special read-\n only attributes: ``__doc__`` is the
function\'s documentation\n string, or ``None`` if unavailable;
``__name__`` is the\n function\'s name; ``__self__`` is set to
``None`` (but see the\n next item); ``__module__`` is the name of the
module the\n function was defined in or ``None`` if unavailable.\n\n
Built-in methods\n This is really a different disguise of a built-in
function, this\n time containing an object passed to the C function as
an\n implicit extra argument. An example of a built-in method is\n
``alist.append()``, assuming *alist* is a list object. In this\n
case, the special read-only attribute ``__self__`` is set to the\n
object denoted by *alist*.\n\n Class Types\n Class types, or
"new-style classes," are callable. These\n objects normally
act as factories for new instances of\n themselves, but variations are
possible for class types that\n override ``__new__()``. The arguments
of the call are passed to\n ``__new__()`` and, in the typical case, to
``__init__()`` to\n initialize the new instance.\n\n Classic
Classes\n Class objects are described below. When a class object is\n
called, a new class instance (also described below) is created\n
and returned. This implies a call to the class\'s ``__init__()``\n
method if it has one. Any arguments are passed on to the\n
``__init__()`` method. If there is no ``__init__()`` method,\n the
class must be called without arguments.\n\n Class instances\n Class
instances are described below. Class instances are\n callable only
when the class has a ``__call__()`` method;\n ``x(arguments)`` is a
shorthand for ``x.__call__(arguments)``.\n\nModules\n Modules are
imported by the ``import`` statement (see section *The\n import
statement*). A module object has a namespace implemented by\n a
dictionary object (this is the dictionary referenced by the\n
func_globals attribute of functions defined in the module).\n Attribute
references are translated to lookups in this dictionary,\n e.g., ``m.x``
is equivalent to ``m.__dict__["x"]``. A module object\n does
not contain the code object used to initialize the module\n (since it
isn\'t needed once the initialization is done).\n\n Attribute
assignment updates the module\'s namespace dictionary,\n e.g., ``m.x
= 1`` is equivalent to ``m.__dict__["x"] = 1``.\n\n Special
read-only attribute: ``__dict__`` is the module\'s namespace\n as a
dictionary object.\n\n **CPython implementation detail:** Because of the
way CPython\n clears module dictionaries, the module dictionary will be
cleared\n when the module falls out of scope even if the dictionary still
has\n live references. To avoid this, copy the dictionary or keep the\n
module around while using its dictionary directly.\n\n Predefined
(writable) attributes: ``__name__`` is the module\'s\n name;
``__doc__`` is the module\'s documentation string, or ``None``\n if
unavailable; ``__file__`` is the pathname of the file from which\n the
module was loaded, if it was loaded from a file. The\n ``__file__``
attribute is not present for C modules that are\n statically linked into
the interpreter; for extension modules\n loaded dynamically from a shared
library, it is the pathname of the\n shared library file.\n\nClasses\n
Both class types (new-style classes) and class objects (old-\n
style/classic classes) are typically created by class definitions\n (see
section *Class definitions*). A class has a namespace\n implemented by a
dictionary object. Class attribute references are\n translated to lookups
in this dictionary, e.g., ``C.x`` is\n translated to
``C.__dict__["x"]`` (although for new-style classes\n in
particular there are a number of hooks which allow for other\n means of
locating attributes). When the attribute name is not found\n there, the
attribute search continues in the base classes. For\n old-style classes,
the search is depth-first, left-to-right in the\n order of occurrence in
the base class list. New-style classes use\n the more complex C3 method
resolution order which behaves correctly\n even in the presence of
\'diamond\' inheritance structures where\n there are multiple
inheritance paths leading back to a common\n ancestor. Additional details
on the C3 MRO used by new-style\n classes can be found in the
documentation accompanying the 2.3\n release at
http://www.python.org/download/releases/2.3/mro/.\n\n When a class
attribute reference (for class ``C``, say) would yield\n a user-defined
function object or an unbound user-defined method\n object whose
associated class is either ``C`` or one of its base\n classes, it is
transformed into an unbound user-defined method\n object whose
``im_class`` attribute is ``C``. When it would yield a\n class method
object, it is transformed into a bound user-defined\n method object whose
``im_self`` attribute is ``C``. When it would\n yield a static method
object, it is transformed into the object\n wrapped by the static method
object. See section *Implementing\n Descriptors* for another way in which
attributes retrieved from a\n class may differ from those actually
contained in its ``__dict__``\n (note that only new-style classes support
descriptors).\n\n Class attribute assignments update the class\'s
dictionary, never\n the dictionary of a base class.\n\n A class object
can be called (see above) to yield a class instance\n (see below).\n\n
Special attributes: ``__name__`` is the class name; ``__module__``\n is
the module name in which the class was defined; ``__dict__`` is\n the
dictionary containing the class\'s namespace; ``__bases__`` is a\n
tuple (possibly empty or a singleton) containing the base classes,\n in
the order of their occurrence in the base class list;\n ``__doc__`` is
the class\'s documentation string, or None if\n undefined.\n\nClass
instances\n A class instance is created by calling a class object (see
above).\n A class instance has a namespace implemented as a dictionary
which\n is the first place in which attribute references are searched.\n
When an attribute is not found there, and the instance\'s class has\n
an attribute by that name, the search continues with the class\n
attributes. If a class attribute is found that is a user-defined\n
function object or an unbound user-defined method object whose\n
associated class is the class (call it ``C``) of the instance for\n which
the attribute reference was initiated or one of its bases, it\n is
transformed into a bound user-defined method object whose\n ``im_class``
attribute is ``C`` and whose ``im_self`` attribute is\n the instance.
Static method and class method objects are also\n transformed, as if they
had been retrieved from class ``C``; see\n above under
"Classes". See section *Implementing Descriptors* for\n another
way in which attributes of a class retrieved via its\n instances may
differ from the objects actually stored in the\n class\'s
``__dict__``. If no class attribute is found, and the\n object\'s
class has a ``__getattr__()`` method, that is called to\n satisfy the
lookup.\n\n Attribute assignments and deletions update the
instance\'s\n dictionary, never a class\'s dictionary. If the
class has a\n ``__setattr__()`` or ``__delattr__()`` method, this is
called\n instead of updating the instance dictionary directly.\n\n
Class instances can pretend to be numbers, sequences, or mappings\n if
they have methods with certain special names. See section\n *Special
method names*.\n\n Special attributes: ``__dict__`` is the attribute
dictionary;\n ``__class__`` is the instance\'s class.\n\nFiles\n A
file object represents an open file. File objects are created by\n the
``open()`` built-in function, and also by ``os.popen()``,\n
``os.fdopen()``, and the ``makefile()`` method of socket objects\n (and
perhaps by other functions or methods provided by extension\n modules).
The objects ``sys.stdin``, ``sys.stdout`` and\n ``sys.stderr`` are
initialized to file objects corresponding to the\n interpreter\'s
standard input, output and error streams. See *File\n Objects* for
complete documentation of file objects.\n\nInternal types\n A few types
used internally by the interpreter are exposed to the\n user. Their
definitions may change with future versions of the\n interpreter, but
they are mentioned here for completeness.\n\n Code objects\n Code
objects represent *byte-compiled* executable Python code,\n or
*bytecode*. The difference between a code object and a\n function
object is that the function object contains an explicit\n reference to
the function\'s globals (the module in which it was\n defined),
while a code object contains no context; also the\n default argument
values are stored in the function object, not\n in the code object
(because they represent values calculated at\n run-time). Unlike
function objects, code objects are immutable\n and contain no
references (directly or indirectly) to mutable\n objects.\n\n
Special read-only attributes: ``co_name`` gives the function\n name;
``co_argcount`` is the number of positional arguments\n (including
arguments with default values); ``co_nlocals`` is the\n number of
local variables used by the function (including\n arguments);
``co_varnames`` is a tuple containing the names of\n the local
variables (starting with the argument names);\n ``co_cellvars`` is a
tuple containing the names of local\n variables that are referenced by
nested functions;\n ``co_freevars`` is a tuple containing the names of
free\n variables; ``co_code`` is a string representing the sequence
of\n bytecode instructions; ``co_consts`` is a tuple containing the\n
literals used by the bytecode; ``co_names`` is a tuple\n
containing the names used by the bytecode; ``co_filename`` is\n the
filename from which the code was compiled;\n ``co_firstlineno`` is the
first line number of the function;\n ``co_lnotab`` is a string
encoding the mapping from bytecode\n offsets to line numbers (for
details see the source code of the\n interpreter); ``co_stacksize`` is
the required stack size\n (including local variables); ``co_flags`` is
an integer encoding\n a number of flags for the interpreter.\n\n
The following flag bits are defined for ``co_flags``: bit\n ``0x04``
is set if the function uses the ``*arguments`` syntax\n to accept an
arbitrary number of positional arguments; bit\n ``0x08`` is set if the
function uses the ``**keywords`` syntax\n to accept arbitrary keyword
arguments; bit ``0x20`` is set if\n the function is a generator.\n\n
Future feature declarations (``from __future__ import\n division``)
also use bits in ``co_flags`` to indicate whether a\n code object was
compiled with a particular feature enabled: bit\n ``0x2000`` is set if
the function was compiled with future\n division enabled; bits
``0x10`` and ``0x1000`` were used in\n earlier versions of Python.\n\n
Other bits in ``co_flags`` are reserved for internal use.\n\n If
a code object represents a function, the first item in\n ``co_consts``
is the documentation string of the function, or\n ``None`` if
undefined.\n\n Frame objects\n Frame objects represent execution
frames. They may occur in\n traceback objects (see below).\n\n
Special read-only attributes: ``f_back`` is to the previous\n stack
frame (towards the caller), or ``None`` if this is the\n bottom stack
frame; ``f_code`` is the code object being executed\n in this frame;
``f_locals`` is the dictionary used to look up\n local variables;
``f_globals`` is used for global variables;\n ``f_builtins`` is used
for built-in (intrinsic) names;\n ``f_restricted`` is a flag
indicating whether the function is\n executing in restricted execution
mode; ``f_lasti`` gives the\n precise instruction (this is an index
into the bytecode string\n of the code object).\n\n Special
writable attributes: ``f_trace``, if not ``None``, is a\n function
called at the start of each source code line (this is\n used by the
debugger); ``f_exc_type``, ``f_exc_value``,\n ``f_exc_traceback``
represent the last exception raised in the\n parent frame provided
another exception was ever raised in the\n current frame (in all other
cases they are None); ``f_lineno``\n is the current line number of the
frame --- writing to this from\n within a trace function jumps to the
given line (only for the\n bottom-most frame). A debugger can
implement a Jump command\n (aka Set Next Statement) by writing to
f_lineno.\n\n Traceback objects\n Traceback objects represent a
stack trace of an exception. A\n traceback object is created when an
exception occurs. When the\n search for an exception handler unwinds
the execution stack, at\n each unwound level a traceback object is
inserted in front of\n the current traceback. When an exception
handler is entered,\n the stack trace is made available to the
program. (See section\n *The try statement*.) It is accessible as
``sys.exc_traceback``,\n and also as the third item of the tuple
returned by\n ``sys.exc_info()``. The latter is the preferred
interface,\n since it works correctly when the program is using
multiple\n threads. When the program contains no suitable handler,
the\n stack trace is written (nicely formatted) to the standard
error\n stream; if the interpreter is interactive, it is also made\n
available to the user as ``sys.last_traceback``.\n\n Special
read-only attributes: ``tb_next`` is the next level in\n the stack
trace (towards the frame where the exception\n occurred), or ``None``
if there is no next level; ``tb_frame``\n points to the execution
frame of the current level;\n ``tb_lineno`` gives the line number
where the exception\n occurred; ``tb_lasti`` indicates the precise
instruction. The\n line number and last instruction in the traceback
may differ\n from the line number of its frame object if the
exception\n occurred in a ``try`` statement with no matching except
clause\n or with a finally clause.\n\n Slice objects\n Slice
objects are used to represent slices when *extended slice\n syntax* is
used. This is a slice using two colons, or multiple\n slices or
ellipses separated by commas, e.g., ``a[i:j:step]``,\n ``a[i:j,
k:l]``, or ``a[..., i:j]``. They are also created by\n the built-in
``slice()`` function.\n\n Special read-only attributes: ``start`` is
the lower bound;\n ``stop`` is the upper bound; ``step`` is the step
value; each is\n ``None`` if omitted. These attributes can have any
type.\n\n Slice objects support one method:\n\n
slice.indices(self, length)\n\n This method takes a single integer
argument *length* and\n computes information about the extended
slice that the slice\n object would describe if applied to a
sequence of *length*\n items. It returns a tuple of three
integers; respectively\n these are the *start* and *stop* indices
and the *step* or\n stride length of the slice. Missing or
out-of-bounds indices\n are handled in a manner consistent with
regular slices.\n\n New in version 2.3.\n\n Static method
objects\n Static method objects provide a way of defeating the\n
transformation of function objects to method objects described\n
above. A static method object is a wrapper around any other\n object,
usually a user-defined method object. When a static\n method object is
retrieved from a class or a class instance, the\n object actually
returned is the wrapped object, which is not\n subject to any further
transformation. Static method objects are\n not themselves callable,
although the objects they wrap usually\n are. Static method objects
are created by the built-in\n ``staticmethod()`` constructor.\n\n
Class method objects\n A class method object, like a static method
object, is a wrapper\n around another object that alters the way in
which that object\n is retrieved from classes and class instances. The
behaviour of\n class method objects upon such retrieval is described
above,\n under "User-defined methods". Class method objects
are created\n by the built-in ``classmethod()`` constructor.\n',
'typesfunctions': '\nFunctions\n*********\n\nFunction
objects are created by function definitions. The only\noperation on a
function object is to call it: ``func(argument-list)``.\n\nThere are really
two flavors of function objects: built-in functions\nand user-defined
functions. Both support the same operation (to call\nthe function), but
the implementation is different, hence the\ndifferent object types.\n\nSee
*Function definitions* for more information.\n',
'typesmapping': '\nMapping Types ---
``dict``\n**************************\n\nA *mapping* object maps *hashable*
values to arbitrary objects.\nMappings are mutable objects. There is
currently only one standard\nmapping type, the *dictionary*. (For other
containers see the built\nin ``list``, ``set``, and ``tuple`` classes, and
the ``collections``\nmodule.)\n\nA dictionary\'s keys are *almost*
arbitrary values. Values that are\nnot *hashable*, that is, values
containing lists, dictionaries or\nother mutable types (that are compared
by value rather than by object\nidentity) may not be used as keys. Numeric
types used for keys obey\nthe normal rules for numeric comparison: if two
numbers compare equal\n(such as ``1`` and ``1.0``) then they can be used
interchangeably to\nindex the same dictionary entry. (Note however, that
since computers\nstore floating-point numbers as approximations it is
usually unwise to\nuse them as dictionary keys.)\n\nDictionaries can be
created by placing a comma-separated list of\n``key: value`` pairs within
braces, for example: ``{\'jack\': 4098,\n\'sjoerd\':
4127}`` or ``{4098: \'jack\', 4127: \'sjoerd\'}``, or
by the\n``dict`` constructor.\n\nclass class dict(**kwarg)\nclass class
dict(mapping, **kwarg)\nclass class dict(iterable, **kwarg)\n\n Return a
new dictionary initialized from an optional positional\n argument and a
possibly empty set of keyword arguments.\n\n If no positional argument is
given, an empty dictionary is created.\n If a positional argument is
given and it is a mapping object, a\n dictionary is created with the same
key-value pairs as the mapping\n object. Otherwise, the positional
argument must be an *iterator*\n object. Each item in the iterable must
itself be an iterator with\n exactly two objects. The first object of
each item becomes a key\n in the new dictionary, and the second object
the corresponding\n value. If a key occurs more than once, the last
value for that key\n becomes the corresponding value in the new
dictionary.\n\n If keyword arguments are given, the keyword arguments and
their\n values are added to the dictionary created from the positional\n
argument. If a key being added is already present, the value from\n the
keyword argument replaces the value from the positional\n argument.\n\n
To illustrate, the following examples all return a dictionary equal\n to
``{"one": 1, "two": 2, "three": 3}``:\n\n
>>> a = dict(one=1, two=2, three=3)\n >>> b =
{\'one\': 1, \'two\': 2, \'three\': 3}\n
>>> c = dict(zip([\'one\', \'two\',
\'three\'], [1, 2, 3]))\n >>> d =
dict([(\'two\', 2), (\'one\', 1), (\'three\',
3)])\n >>> e = dict({\'three\': 3,
\'one\': 1, \'two\': 2})\n >>> a == b ==
c == d == e\n True\n\n Providing keyword arguments as in the first
example only works for\n keys that are valid Python identifiers.
Otherwise, any valid keys\n can be used.\n\n New in version 2.2.\n\n
Changed in version 2.3: Support for building a dictionary from\n keyword
arguments added.\n\n These are the operations that dictionaries support
(and therefore,\n custom mapping types should support too):\n\n
len(d)\n\n Return the number of items in the dictionary *d*.\n\n
d[key]\n\n Return the item of *d* with key *key*. Raises a
``KeyError`` if\n *key* is not in the map.\n\n New in version
2.5: If a subclass of dict defines a method\n ``__missing__()``, if
the key *key* is not present, the\n ``d[key]`` operation calls that
method with the key *key* as\n argument. The ``d[key]`` operation
then returns or raises\n whatever is returned or raised by the
``__missing__(key)`` call\n if the key is not present. No other
operations or methods invoke\n ``__missing__()``. If ``__missing__()``
is not defined,\n ``KeyError`` is raised. ``__missing__()`` must be a
method; it\n cannot be an instance variable. For an example, see\n
``collections.defaultdict``.\n\n d[key] = value\n\n Set ``d[key]``
to *value*.\n\n del d[key]\n\n Remove ``d[key]`` from *d*. Raises a
``KeyError`` if *key* is\n not in the map.\n\n key in d\n\n
Return ``True`` if *d* has a key *key*, else ``False``.\n\n New in
version 2.2.\n\n key not in d\n\n Equivalent to ``not key in
d``.\n\n New in version 2.2.\n\n iter(d)\n\n Return an iterator
over the keys of the dictionary. This is a\n shortcut for
``iterkeys()``.\n\n clear()\n\n Remove all items from the
dictionary.\n\n copy()\n\n Return a shallow copy of the
dictionary.\n\n fromkeys(seq[, value])\n\n Create a new dictionary
with keys from *seq* and values set to\n *value*.\n\n
``fromkeys()`` is a class method that returns a new dictionary.\n
*value* defaults to ``None``.\n\n New in version 2.3.\n\n get(key[,
default])\n\n Return the value for *key* if *key* is in the
dictionary, else\n *default*. If *default* is not given, it defaults
to ``None``,\n so that this method never raises a ``KeyError``.\n\n
has_key(key)\n\n Test for the presence of *key* in the dictionary.
``has_key()``\n is deprecated in favor of ``key in d``.\n\n
items()\n\n Return a copy of the dictionary\'s list of ``(key,
value)``\n pairs.\n\n **CPython implementation detail:** Keys and
values are listed in\n an arbitrary order which is non-random, varies
across Python\n implementations, and depends on the dictionary\'s
history of\n insertions and deletions.\n\n If ``items()``,
``keys()``, ``values()``, ``iteritems()``,\n ``iterkeys()``, and
``itervalues()`` are called with no\n intervening modifications to the
dictionary, the lists will\n directly correspond. This allows the
creation of ``(value,\n key)`` pairs using ``zip()``: ``pairs =
zip(d.values(),\n d.keys())``. The same relationship holds for the
``iterkeys()``\n and ``itervalues()`` methods: ``pairs =
zip(d.itervalues(),\n d.iterkeys())`` provides the same value for
``pairs``. Another\n way to create the same list is ``pairs = [(v, k)
for (k, v) in\n d.iteritems()]``.\n\n iteritems()\n\n Return an
iterator over the dictionary\'s ``(key, value)`` pairs.\n See the
note for ``dict.items()``.\n\n Using ``iteritems()`` while adding or
deleting entries in the\n dictionary may raise a ``RuntimeError`` or
fail to iterate over\n all entries.\n\n New in version 2.2.\n\n
iterkeys()\n\n Return an iterator over the dictionary\'s keys.
See the note for\n ``dict.items()``.\n\n Using ``iterkeys()``
while adding or deleting entries in the\n dictionary may raise a
``RuntimeError`` or fail to iterate over\n all entries.\n\n New
in version 2.2.\n\n itervalues()\n\n Return an iterator over the
dictionary\'s values. See the note\n for ``dict.items()``.\n\n
Using ``itervalues()`` while adding or deleting entries in the\n
dictionary may raise a ``RuntimeError`` or fail to iterate over\n all
entries.\n\n New in version 2.2.\n\n keys()\n\n Return a copy
of the dictionary\'s list of keys. See the note\n for
``dict.items()``.\n\n pop(key[, default])\n\n If *key* is in the
dictionary, remove it and return its value,\n else return *default*.
If *default* is not given and *key* is\n not in the dictionary, a
``KeyError`` is raised.\n\n New in version 2.3.\n\n popitem()\n\n
Remove and return an arbitrary ``(key, value)`` pair from the\n
dictionary.\n\n ``popitem()`` is useful to destructively iterate over
a\n dictionary, as often used in set algorithms. If the dictionary\n
is empty, calling ``popitem()`` raises a ``KeyError``.\n\n
setdefault(key[, default])\n\n If *key* is in the dictionary, return
its value. If not, insert\n *key* with a value of *default* and
return *default*. *default*\n defaults to ``None``.\n\n
update([other])\n\n Update the dictionary with the key/value pairs
from *other*,\n overwriting existing keys. Return ``None``.\n\n
``update()`` accepts either another dictionary object or an\n iterable
of key/value pairs (as tuples or other iterables of\n length two). If
keyword arguments are specified, the dictionary\n is then updated with
those key/value pairs: ``d.update(red=1,\n blue=2)``.\n\n Changed
in version 2.4: Allowed the argument to be an iterable\n of key/value
pairs and allowed keyword arguments.\n\n values()\n\n Return a copy
of the dictionary\'s list of values. See the note\n for
``dict.items()``.\n\n viewitems()\n\n Return a new view of the
dictionary\'s items (``(key, value)``\n pairs). See below for
documentation of view objects.\n\n New in version 2.7.\n\n
viewkeys()\n\n Return a new view of the dictionary\'s keys. See
below for\n documentation of view objects.\n\n New in version
2.7.\n\n viewvalues()\n\n Return a new view of the
dictionary\'s values. See below for\n documentation of view
objects.\n\n New in version 2.7.\n\n\nDictionary view
objects\n=======================\n\nThe objects returned by
``dict.viewkeys()``, ``dict.viewvalues()`` and\n``dict.viewitems()`` are
*view objects*. They provide a dynamic view\non the dictionary\'s
entries, which means that when the dictionary\nchanges, the view reflects
these changes.\n\nDictionary views can be iterated over to yield their
respective data,\nand support membership tests:\n\nlen(dictview)\n\n
Return the number of entries in the dictionary.\n\niter(dictview)\n\n
Return an iterator over the keys, values or items (represented as\n
tuples of ``(key, value)``) in the dictionary.\n\n Keys and values are
iterated over in an arbitrary order which is\n non-random, varies across
Python implementations, and depends on\n the dictionary\'s history
of insertions and deletions. If keys,\n values and items views are
iterated over with no intervening\n modifications to the dictionary, the
order of items will directly\n correspond. This allows the creation of
``(value, key)`` pairs\n using ``zip()``: ``pairs = zip(d.values(),
d.keys())``. Another\n way to create the same list is ``pairs = [(v, k)
for (k, v) in\n d.items()]``.\n\n Iterating views while adding or
deleting entries in the dictionary\n may raise a ``RuntimeError`` or fail
to iterate over all entries.\n\nx in dictview\n\n Return ``True`` if *x*
is in the underlying dictionary\'s keys,\n values or items (in the
latter case, *x* should be a ``(key,\n value)`` tuple).\n\nKeys views are
set-like since their entries are unique and hashable.\nIf all values are
hashable, so that (key, value) pairs are unique and\nhashable, then the
items view is also set-like. (Values views are not\ntreated as set-like
since the entries are generally not unique.) Then\nthese set operations
are available ("other" refers either to another\nview or a
set):\n\ndictview & other\n\n Return the intersection of the dictview
and the other object as a\n new set.\n\ndictview | other\n\n Return the
union of the dictview and the other object as a new set.\n\ndictview -
other\n\n Return the difference between the dictview and the other
object\n (all elements in *dictview* that aren\'t in *other*) as a
new set.\n\ndictview ^ other\n\n Return the symmetric difference (all
elements either in *dictview*\n or *other*, but not in both) of the
dictview and the other object\n as a new set.\n\nAn example of dictionary
view usage:\n\n >>> dishes = {\'eggs\': 2,
\'sausage\': 1, \'bacon\': 1, \'spam\':
500}\n >>> keys = dishes.viewkeys()\n >>> values =
dishes.viewvalues()\n\n >>> # iteration\n >>> n = 0\n
>>> for val in values:\n ... n += val\n >>>
print(n)\n 504\n\n >>> # keys and values are iterated over in
the same order\n >>> list(keys)\n [\'eggs\',
\'bacon\', \'sausage\', \'spam\']\n
>>> list(values)\n [2, 1, 1, 500]\n\n >>> # view
objects are dynamic and reflect dict changes\n >>> del
dishes[\'eggs\']\n >>> del
dishes[\'sausage\']\n >>> list(keys)\n
[\'spam\', \'bacon\']\n\n >>> # set
operations\n >>> keys & {\'eggs\',
\'bacon\', \'salad\'}\n
{\'bacon\'}\n',
'typesmethods': '\nMethods\n*******\n\nMethods are
functions that are called using the attribute notation.\nThere are two
flavors: built-in methods (such as ``append()`` on\nlists) and class
instance methods. Built-in methods are described\nwith the types that
support them.\n\nThe implementation adds two special read-only attributes
to class\ninstance methods: ``m.im_self`` is the object on which the
method\noperates, and ``m.im_func`` is the function implementing the
method.\nCalling ``m(arg-1, arg-2, ..., arg-n)`` is completely equivalent
to\ncalling ``m.im_func(m.im_self, arg-1, arg-2, ..., arg-n)``.\n\nClass
instance methods are either *bound* or *unbound*, referring to\nwhether the
method was accessed through an instance or a class,\nrespectively. When a
method is unbound, its ``im_self`` attribute\nwill be ``None`` and if
called, an explicit ``self`` object must be\npassed as the first argument.
In this case, ``self`` must be an\ninstance of the unbound method\'s
class (or a subclass of that class),\notherwise a ``TypeError`` is
raised.\n\nLike function objects, methods objects support getting
arbitrary\nattributes. However, since method attributes are actually stored
on\nthe underlying function object (``meth.im_func``), setting
method\nattributes on either bound or unbound methods is
disallowed.\nAttempting to set an attribute on a method results in
an\n``AttributeError`` being raised. In order to set a method
attribute,\nyou need to explicitly set it on the underlying function
object:\n\n >>> class C:\n ... def method(self):\n ...
pass\n ...\n >>> c = C()\n >>>
c.method.whoami = \'my name is method\' # can\'t set on the
method\n Traceback (most recent call last):\n File
"<stdin>", line 1, in <module>\n AttributeError:
\'instancemethod\' object has no attribute \'whoami\'\n
>>> c.method.im_func.whoami = \'my name is method\'\n
>>> c.method.whoami\n \'my name is method\'\n\nSee
*The standard type hierarchy* for more information.\n',
'typesmodules': "\nModules\n*******\n\nThe only special
operation on a module is attribute access:\n``m.name``, where *m* is a
module and *name* accesses a name defined\nin *m*'s symbol table.
Module attributes can be assigned to. (Note\nthat the ``import`` statement
is not, strictly speaking, an operation\non a module object; ``import foo``
does not require a module object\nnamed *foo* to exist, rather it requires
an (external) *definition*\nfor a module named *foo* somewhere.)\n\nA
special attribute of every module is ``__dict__``. This is the\ndictionary
containing the module's symbol table. Modifying this\ndictionary will
actually change the module's symbol table, but direct\nassignment to
the ``__dict__`` attribute is not possible (you can\nwrite
``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``,
but\nyou can't write ``m.__dict__ = {}``). Modifying ``__dict__``
directly\nis not recommended.\n\nModules built into the interpreter are
written like this: ``<module\n'sys' (built-in)>``. If
loaded from a file, they are written as\n``<module 'os' from
'/usr/local/lib/pythonX.Y/os.pyc'>``.\n",
'typesseq': '\nSequence Types --- ``str``, ``unicode``,
``list``, ``tuple``, ``bytearray``, ``buffer``,
``xrange``\n***************************************************************************************************\n\nThere
are seven sequence types: strings, Unicode strings, lists,\ntuples,
bytearrays, buffers, and xrange objects.\n\nFor other containers see the
built in ``dict`` and ``set`` classes,\nand the ``collections``
module.\n\nString literals are written in single or double quotes:
``\'xyzzy\'``,\n``"frobozz"``. See *String literals*
for more about string literals.\nUnicode strings are much like strings, but
are specified in the syntax\nusing a preceding ``\'u\'``
character: ``u\'abc\'``, ``u"def"``. In\naddition to
the functionality described here, there are also string-\nspecific methods
described in the *String Methods* section. Lists are\nconstructed with
square brackets, separating items with commas: ``[a,\nb, c]``. Tuples are
constructed by the comma operator (not within\nsquare brackets), with or
without enclosing parentheses, but an empty\ntuple must have the enclosing
parentheses, such as ``a, b, c`` or\n``()``. A single item tuple must have
a trailing comma, such as\n``(d,)``.\n\nBytearray objects are created with
the built-in function\n``bytearray()``.\n\nBuffer objects are not directly
supported by Python syntax, but can be\ncreated by calling the built-in
function ``buffer()``. They don\'t\nsupport concatenation or
repetition.\n\nObjects of type xrange are similar to buffers in that there
is no\nspecific syntax to create them, but they are created using
the\n``xrange()`` function. They don\'t support slicing,
concatenation or\nrepetition, and using ``in``, ``not in``, ``min()`` or
``max()`` on\nthem is inefficient.\n\nMost sequence types support the
following operations. The ``in`` and\n``not in`` operations have the same
priorities as the comparison\noperations. The ``+`` and ``*`` operations
have the same priority as\nthe corresponding numeric operations. [3]
Additional methods are\nprovided for *Mutable Sequence Types*.\n\nThis
table lists the sequence operations sorted in ascending
priority\n(operations in the same box have the same priority). In the
table,\n*s* and *t* are sequences of the same type; *n*, *i* and *j*
are\nintegers:\n\n+--------------------+----------------------------------+------------+\n|
Operation | Result | Notes
|\n+====================+==================================+============+\n|
``x in s`` | ``True`` if an item of *s* is | (1) |\n|
| equal to *x*, else ``False`` |
|\n+--------------------+----------------------------------+------------+\n|
``x not in s`` | ``False`` if an item of *s* is | (1) |\n|
| equal to *x*, else ``True`` |
|\n+--------------------+----------------------------------+------------+\n|
``s + t`` | the concatenation of *s* and *t* | (6)
|\n+--------------------+----------------------------------+------------+\n|
``s * n, n * s`` | *n* shallow copies of *s* | (2) |\n|
| concatenated |
|\n+--------------------+----------------------------------+------------+\n|
``s[i]`` | *i*th item of *s*, origin 0 | (3)
|\n+--------------------+----------------------------------+------------+\n|
``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4)
|\n+--------------------+----------------------------------+------------+\n|
``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |\n|
| with step *k* |
|\n+--------------------+----------------------------------+------------+\n|
``len(s)`` | length of *s* |
|\n+--------------------+----------------------------------+------------+\n|
``min(s)`` | smallest item of *s* |
|\n+--------------------+----------------------------------+------------+\n|
``max(s)`` | largest item of *s* |
|\n+--------------------+----------------------------------+------------+\n|
``s.index(i)`` | index of the first occurence of | |\n|
| *i* in *s* |
|\n+--------------------+----------------------------------+------------+\n|
``s.count(i)`` | total number of occurences of | |\n|
| *i* in *s* |
|\n+--------------------+----------------------------------+------------+\n\nSequence
types also support comparisons. In particular, tuples and\nlists are
compared lexicographically by comparing corresponding\nelements. This means
that to compare equal, every element must compare\nequal and the two
sequences must be of the same type and have the same\nlength. (For full
details see *Comparisons* in the language\nreference.)\n\nNotes:\n\n1. When
*s* is a string or Unicode string object the ``in`` and ``not\n in``
operations act like a substring test. In Python versions\n before 2.3,
*x* had to be a string of length 1. In Python 2.3 and\n beyond, *x* may
be a string of any length.\n\n2. Values of *n* less than ``0`` are treated
as ``0`` (which yields an\n empty sequence of the same type as *s*).
Note also that the copies\n are shallow; nested structures are not
copied. This often haunts\n new Python programmers; consider:\n\n
>>> lists = [[]] * 3\n >>> lists\n [[], [], []]\n
>>> lists[0].append(3)\n >>> lists\n [[3], [3],
[3]]\n\n What has happened is that ``[[]]`` is a one-element list
containing\n an empty list, so all three elements of ``[[]] * 3`` are
(pointers\n to) this single empty list. Modifying any of the elements
of\n ``lists`` modifies this single list. You can create a list of\n
different lists this way:\n\n >>> lists = [[] for i in
range(3)]\n >>> lists[0].append(3)\n >>>
lists[1].append(5)\n >>> lists[2].append(7)\n >>>
lists\n [[3], [5], [7]]\n\n3. If *i* or *j* is negative, the index is
relative to the end of the\n string: ``len(s) + i`` or ``len(s) + j`` is
substituted. But note\n that ``-0`` is still ``0``.\n\n4. The slice of
*s* from *i* to *j* is defined as the sequence of\n items with index *k*
such that ``i <= k < j``. If *i* or *j* is\n greater than
``len(s)``, use ``len(s)``. If *i* is omitted or\n ``None``, use ``0``.
If *j* is omitted or ``None``, use\n ``len(s)``. If *i* is greater than
or equal to *j*, the slice is\n empty.\n\n5. The slice of *s* from *i* to
*j* with step *k* is defined as the\n sequence of items with index ``x =
i + n*k`` such that ``0 <= n <\n (j-i)/k``. In other words, the
indices are ``i``, ``i+k``,\n ``i+2*k``, ``i+3*k`` and so on, stopping
when *j* is reached (but\n never including *j*). If *i* or *j* is
greater than ``len(s)``,\n use ``len(s)``. If *i* or *j* are omitted or
``None``, they become\n "end" values (which end depends on the
sign of *k*). Note, *k*\n cannot be zero. If *k* is ``None``, it is
treated like ``1``.\n\n6. **CPython implementation detail:** If *s* and *t*
are both strings,\n some Python implementations such as CPython can
usually perform an\n in-place optimization for assignments of the form
``s = s + t`` or\n ``s += t``. When applicable, this optimization makes
quadratic\n run-time much less likely. This optimization is both version
and\n implementation dependent. For performance sensitive code, it is\n
preferable to use the ``str.join()`` method which assures\n consistent
linear concatenation performance across versions and\n
implementations.\n\n Changed in version 2.4: Formerly, string
concatenation never\n occurred in-place.\n\n\nString
Methods\n==============\n\nBelow are listed the string methods which both
8-bit strings and\nUnicode objects support. Some of them are also
available on\n``bytearray`` objects.\n\nIn addition, Python\'s strings
support the sequence type methods\ndescribed in the *Sequence Types ---
str, unicode, list, tuple,\nbytearray, buffer, xrange* section. To output
formatted strings use\ntemplate strings or the ``%`` operator described in
the *String\nFormatting Operations* section. Also, see the ``re`` module
for string\nfunctions based on regular expressions.\n\nstr.capitalize()\n\n
Return a copy of the string with its first character capitalized\n and
the rest lowercased.\n\n For 8-bit strings, this method is
locale-dependent.\n\nstr.center(width[, fillchar])\n\n Return centered in
a string of length *width*. Padding is done\n using the specified
*fillchar* (default is a space).\n\n Changed in version 2.4: Support for
the *fillchar* argument.\n\nstr.count(sub[, start[, end]])\n\n Return the
number of non-overlapping occurrences of substring *sub*\n in the range
[*start*, *end*]. Optional arguments *start* and\n *end* are interpreted
as in slice notation.\n\nstr.decode([encoding[, errors]])\n\n Decodes the
string using the codec registered for *encoding*.\n *encoding* defaults
to the default string encoding. *errors* may\n be given to set a
different error handling scheme. The default is\n
``\'strict\'``, meaning that encoding errors raise
``UnicodeError``.\n Other possible values are ``\'ignore\'``,
``\'replace\'`` and any other\n name registered via
``codecs.register_error()``, see section *Codec\n Base Classes*.\n\n
New in version 2.2.\n\n Changed in version 2.3: Support for other error
handling schemes\n added.\n\n Changed in version 2.7: Support for
keyword arguments added.\n\nstr.encode([encoding[, errors]])\n\n Return
an encoded version of the string. Default encoding is the\n current
default string encoding. *errors* may be given to set a\n different
error handling scheme. The default for *errors* is\n
``\'strict\'``, meaning that encoding errors raise a\n
``UnicodeError``. Other possible values are ``\'ignore\'``,\n
``\'replace\'``, ``\'xmlcharrefreplace\'``,
``\'backslashreplace\'`` and\n any other name registered via
``codecs.register_error()``, see\n section *Codec Base Classes*. For a
list of possible encodings, see\n section *Standard Encodings*.\n\n New
in version 2.0.\n\n Changed in version 2.3: Support for
``\'xmlcharrefreplace\'`` and\n
``\'backslashreplace\'`` and other error handling schemes
added.\n\n Changed in version 2.7: Support for keyword arguments
added.\n\nstr.endswith(suffix[, start[, end]])\n\n Return ``True`` if the
string ends with the specified *suffix*,\n otherwise return ``False``.
*suffix* can also be a tuple of\n suffixes to look for. With optional
*start*, test beginning at\n that position. With optional *end*, stop
comparing at that\n position.\n\n Changed in version 2.5: Accept tuples
as *suffix*.\n\nstr.expandtabs([tabsize])\n\n Return a copy of the string
where all tab characters are replaced\n by one or more spaces, depending
on the current column and the\n given tab size. Tab positions occur
every *tabsize* characters\n (default is 8, giving tab positions at
columns 0, 8, 16 and so on).\n To expand the string, the current column
is set to zero and the\n string is examined character by character. If
the character is a\n tab (``\\t``), one or more space characters are
inserted in the\n result until the current column is equal to the next
tab position.\n (The tab character itself is not copied.) If the
character is a\n newline (``\\n``) or return (``\\r``), it is copied and
the current\n column is reset to zero. Any other character is copied
unchanged\n and the current column is incremented by one regardless of
how the\n character is represented when printed.\n\n >>>
\'01\\t012\\t0123\\t01234\'.expandtabs()\n \'01 012
0123 01234\'\n >>>
\'01\\t012\\t0123\\t01234\'.expandtabs(4)\n \'01 012 0123
01234\'\n\nstr.find(sub[, start[, end]])\n\n Return the lowest
index in the string where substring *sub* is\n found, such that *sub* is
contained in the slice ``s[start:end]``.\n Optional arguments *start* and
*end* are interpreted as in slice\n notation. Return ``-1`` if *sub* is
not found.\n\n Note: The ``find()`` method should be used only if you
need to know the\n position of *sub*. To check if *sub* is a substring
or not, use\n the ``in`` operator:\n\n >>>
\'Py\' in \'Python\'\n True\n\nstr.format(*args,
**kwargs)\n\n Perform a string formatting operation. The string on which
this\n method is called can contain literal text or replacement fields\n
delimited by braces ``{}``. Each replacement field contains either\n
the numeric index of a positional argument, or the name of a\n keyword
argument. Returns a copy of the string where each\n replacement field is
replaced with the string value of the\n corresponding argument.\n\n
>>> "The sum of 1 + 2 is {0}".format(1+2)\n \'The
sum of 1 + 2 is 3\'\n\n See *Format String Syntax* for a description
of the various\n formatting options that can be specified in format
strings.\n\n This method of string formatting is the new standard in
Python 3,\n and should be preferred to the ``%`` formatting described
in\n *String Formatting Operations* in new code.\n\n New in version
2.6.\n\nstr.index(sub[, start[, end]])\n\n Like ``find()``, but raise
``ValueError`` when the substring is not\n found.\n\nstr.isalnum()\n\n
Return true if all characters in the string are alphanumeric and\n there
is at least one character, false otherwise.\n\n For 8-bit strings, this
method is locale-dependent.\n\nstr.isalpha()\n\n Return true if all
characters in the string are alphabetic and\n there is at least one
character, false otherwise.\n\n For 8-bit strings, this method is
locale-dependent.\n\nstr.isdigit()\n\n Return true if all characters in
the string are digits and there is\n at least one character, false
otherwise.\n\n For 8-bit strings, this method is
locale-dependent.\n\nstr.islower()\n\n Return true if all cased
characters [4] in the string are lowercase\n and there is at least one
cased character, false otherwise.\n\n For 8-bit strings, this method is
locale-dependent.\n\nstr.isspace()\n\n Return true if there are only
whitespace characters in the string\n and there is at least one
character, false otherwise.\n\n For 8-bit strings, this method is
locale-dependent.\n\nstr.istitle()\n\n Return true if the string is a
titlecased string and there is at\n least one character, for example
uppercase characters may only\n follow uncased characters and lowercase
characters only cased ones.\n Return false otherwise.\n\n For 8-bit
strings, this method is locale-dependent.\n\nstr.isupper()\n\n Return
true if all cased characters [4] in the string are uppercase\n and there
is at least one cased character, false otherwise.\n\n For 8-bit strings,
this method is locale-dependent.\n\nstr.join(iterable)\n\n Return a
string which is the concatenation of the strings in the\n *iterable*
*iterable*. The separator between elements is the\n string providing
this method.\n\nstr.ljust(width[, fillchar])\n\n Return the string left
justified in a string of length *width*.\n Padding is done using the
specified *fillchar* (default is a\n space). The original string is
returned if *width* is less than or\n equal to ``len(s)``.\n\n Changed
in version 2.4: Support for the *fillchar* argument.\n\nstr.lower()\n\n
Return a copy of the string with all the cased characters [4]\n converted
to lowercase.\n\n For 8-bit strings, this method is
locale-dependent.\n\nstr.lstrip([chars])\n\n Return a copy of the string
with leading characters removed. The\n *chars* argument is a string
specifying the set of characters to be\n removed. If omitted or
``None``, the *chars* argument defaults to\n removing whitespace. The
*chars* argument is not a prefix; rather,\n all combinations of its
values are stripped:\n\n >>> \' spacious
\'.lstrip()\n \'spacious \'\n >>>
\'www.example.com\'.lstrip(\'cmowz.\')\n
\'example.com\'\n\n Changed in version 2.2.2: Support for the
*chars* argument.\n\nstr.partition(sep)\n\n Split the string at the first
occurrence of *sep*, and return a\n 3-tuple containing the part before
the separator, the separator\n itself, and the part after the separator.
If the separator is not\n found, return a 3-tuple containing the string
itself, followed by\n two empty strings.\n\n New in version
2.5.\n\nstr.replace(old, new[, count])\n\n Return a copy of the string
with all occurrences of substring *old*\n replaced by *new*. If the
optional argument *count* is given, only\n the first *count* occurrences
are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n Return the highest
index in the string where substring *sub* is\n found, such that *sub* is
contained within ``s[start:end]``.\n Optional arguments *start* and *end*
are interpreted as in slice\n notation. Return ``-1`` on
failure.\n\nstr.rindex(sub[, start[, end]])\n\n Like ``rfind()`` but
raises ``ValueError`` when the substring *sub*\n is not
found.\n\nstr.rjust(width[, fillchar])\n\n Return the string right
justified in a string of length *width*.\n Padding is done using the
specified *fillchar* (default is a\n space). The original string is
returned if *width* is less than or\n equal to ``len(s)``.\n\n Changed
in version 2.4: Support for the *fillchar*
argument.\n\nstr.rpartition(sep)\n\n Split the string at the last
occurrence of *sep*, and return a\n 3-tuple containing the part before
the separator, the separator\n itself, and the part after the separator.
If the separator is not\n found, return a 3-tuple containing two empty
strings, followed by\n the string itself.\n\n New in version
2.5.\n\nstr.rsplit([sep[, maxsplit]])\n\n Return a list of the words in
the string, using *sep* as the\n delimiter string. If *maxsplit* is
given, at most *maxsplit* splits\n are done, the *rightmost* ones. If
*sep* is not specified or\n ``None``, any whitespace string is a
separator. Except for\n splitting from the right, ``rsplit()`` behaves
like ``split()``\n which is described in detail below.\n\n New in
version 2.4.\n\nstr.rstrip([chars])\n\n Return a copy of the string with
trailing characters removed. The\n *chars* argument is a string
specifying the set of characters to be\n removed. If omitted or
``None``, the *chars* argument defaults to\n removing whitespace. The
*chars* argument is not a suffix; rather,\n all combinations of its
values are stripped:\n\n >>> \' spacious
\'.rstrip()\n \' spacious\'\n >>>
\'mississippi\'.rstrip(\'ipz\')\n
\'mississ\'\n\n Changed in version 2.2.2: Support for the
*chars* argument.\n\nstr.split([sep[, maxsplit]])\n\n Return a list of
the words in the string, using *sep* as the\n delimiter string. If
*maxsplit* is given, at most *maxsplit*\n splits are done (thus, the list
will have at most ``maxsplit+1``\n elements). If *maxsplit* is not
specified or ``-1``, then there is\n no limit on the number of splits
(all possible splits are made).\n\n If *sep* is given, consecutive
delimiters are not grouped together\n and are deemed to delimit empty
strings (for example,\n ``\'1,,2\'.split(\',\')``
returns ``[\'1\', \'\', \'2\']``). The
*sep*\n argument may consist of multiple characters (for example,\n
``\'1<>2<>3\'.split(\'<>\')`` returns
``[\'1\', \'2\', \'3\']``). Splitting\n an
empty string with a specified separator returns ``[\'\']``.\n\n
If *sep* is not specified or is ``None``, a different splitting\n
algorithm is applied: runs of consecutive whitespace are regarded\n as a
single separator, and the result will contain no empty strings\n at the
start or end if the string has leading or trailing\n whitespace.
Consequently, splitting an empty string or a string\n consisting of just
whitespace with a ``None`` separator returns\n ``[]``.\n\n For example,
``\' 1 2 3 \'.split()`` returns ``[\'1\',
\'2\', \'3\']``,\n and ``\' 1 2 3
\'.split(None, 1)`` returns ``[\'1\', \'2 3
\']``.\n\nstr.splitlines([keepends])\n\n Return a list of the lines
in the string, breaking at line\n boundaries. This method uses the
*universal newlines* approach to\n splitting lines. Line breaks are not
included in the resulting list\n unless *keepends* is given and true.\n\n
For example, ``\'ab c\\n\\nde fg\\rkl\\r\\n\'.splitlines()``
returns\n ``[\'ab c\', \'\', \'de fg\',
\'kl\']``, while the same call with\n ``splitlines(True)``
returns ``[\'ab c\\n\', \'\\n\', \'de
fg\\r\',\n \'kl\\r\\n\']``.\n\n Unlike ``split()`` when
a delimiter string *sep* is given, this\n method returns an empty list
for the empty string, and a terminal\n line break does not result in an
extra line.\n\nstr.startswith(prefix[, start[, end]])\n\n Return ``True``
if string starts with the *prefix*, otherwise\n return ``False``.
*prefix* can also be a tuple of prefixes to look\n for. With optional
*start*, test string beginning at that\n position. With optional *end*,
stop comparing string at that\n position.\n\n Changed in version 2.5:
Accept tuples as *prefix*.\n\nstr.strip([chars])\n\n Return a copy of the
string with the leading and trailing\n characters removed. The *chars*
argument is a string specifying the\n set of characters to be removed. If
omitted or ``None``, the\n *chars* argument defaults to removing
whitespace. The *chars*\n argument is not a prefix or suffix; rather, all
combinations of its\n values are stripped:\n\n >>> \'
spacious \'.strip()\n \'spacious\'\n >>>
\'www.example.com\'.strip(\'cmowz.\')\n
\'example\'\n\n Changed in version 2.2.2: Support for the
*chars* argument.\n\nstr.swapcase()\n\n Return a copy of the string with
uppercase characters converted to\n lowercase and vice versa.\n\n For
8-bit strings, this method is locale-dependent.\n\nstr.title()\n\n Return
a titlecased version of the string where words start with an\n uppercase
character and the remaining characters are lowercase.\n\n The algorithm
uses a simple language-independent definition of a\n word as groups of
consecutive letters. The definition works in\n many contexts but it
means that apostrophes in contractions and\n possessives form word
boundaries, which may not be the desired\n result:\n\n >>>
"they\'re bill\'s friends from the UK".title()\n
"They\'Re Bill\'S Friends From The Uk"\n\n A
workaround for apostrophes can be constructed using regular\n
expressions:\n\n >>> import re\n >>> def
titlecase(s):\n ... return
re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n ...
lambda mo: mo.group(0)[0].upper() +\n ...
mo.group(0)[1:].lower(),\n ... s)\n ...\n
>>> titlecase("they\'re bill\'s friends.")\n
"They\'re Bill\'s Friends."\n\n For 8-bit
strings, this method is locale-dependent.\n\nstr.translate(table[,
deletechars])\n\n Return a copy of the string where all characters
occurring in the\n optional argument *deletechars* are removed, and the
remaining\n characters have been mapped through the given translation
table,\n which must be a string of length 256.\n\n You can use the
``maketrans()`` helper function in the ``string``\n module to create a
translation table. For string objects, set the\n *table* argument to
``None`` for translations that only delete\n characters:\n\n
>>> \'read this short text\'.translate(None,
\'aeiou\')\n \'rd ths shrt txt\'\n\n New in version
2.6: Support for a ``None`` *table* argument.\n\n For Unicode objects,
the ``translate()`` method does not accept the\n optional *deletechars*
argument. Instead, it returns a copy of the\n *s* where all characters
have been mapped through the given\n translation table which must be a
mapping of Unicode ordinals to\n Unicode ordinals, Unicode strings or
``None``. Unmapped characters\n are left untouched. Characters mapped to
``None`` are deleted.\n Note, a more flexible approach is to create a
custom character\n mapping codec using the ``codecs`` module (see
``encodings.cp1251``\n for an example).\n\nstr.upper()\n\n Return a
copy of the string with all the cased characters [4]\n converted to
uppercase. Note that ``str.upper().isupper()`` might\n be ``False`` if
``s`` contains uncased characters or if the Unicode\n category of the
resulting character(s) is not "Lu" (Letter,\n uppercase), but
e.g. "Lt" (Letter, titlecase).\n\n For 8-bit strings, this
method is locale-dependent.\n\nstr.zfill(width)\n\n Return the numeric
string left filled with zeros in a string of\n length *width*. A sign
prefix is handled correctly. The original\n string is returned if
*width* is less than or equal to ``len(s)``.\n\n New in version
2.2.2.\n\nThe following methods are present only on unicode
objects:\n\nunicode.isnumeric()\n\n Return ``True`` if there are only
numeric characters in S,\n ``False`` otherwise. Numeric characters
include digit characters,\n and all characters that have the Unicode
numeric value property,\n e.g. U+2155, VULGAR FRACTION ONE
FIFTH.\n\nunicode.isdecimal()\n\n Return ``True`` if there are only
decimal characters in S,\n ``False`` otherwise. Decimal characters
include digit characters,\n and all characters that can be used to form
decimal-radix numbers,\n e.g. U+0660, ARABIC-INDIC DIGIT
ZERO.\n\n\nString Formatting
Operations\n============================\n\nString and Unicode objects have
one unique built-in operation: the\n``%`` operator (modulo). This is also
known as the string\n*formatting* or *interpolation* operator. Given
``format % values``\n(where *format* is a string or Unicode object), ``%``
conversion\nspecifications in *format* are replaced with zero or more
elements of\n*values*. The effect is similar to the using ``sprintf()`` in
the C\nlanguage. If *format* is a Unicode object, or if any of the
objects\nbeing converted using the ``%s`` conversion are Unicode objects,
the\nresult will also be a Unicode object.\n\nIf *format* requires a single
argument, *values* may be a single non-\ntuple object. [5] Otherwise,
*values* must be a tuple with exactly\nthe number of items specified by the
format string, or a single\nmapping object (for example, a
dictionary).\n\nA conversion specifier contains two or more characters and
has the\nfollowing components, which must occur in this order:\n\n1. The
``\'%\'`` character, which marks the start of the
specifier.\n\n2. Mapping key (optional), consisting of a parenthesised
sequence of\n characters (for example, ``(somename)``).\n\n3. Conversion
flags (optional), which affect the result of some\n conversion
types.\n\n4. Minimum field width (optional). If specified as an
``\'*\'``\n (asterisk), the actual width is read from the next
element of the\n tuple in *values*, and the object to convert comes after
the\n minimum field width and optional precision.\n\n5. Precision
(optional), given as a ``\'.\'`` (dot) followed by the\n
precision. If specified as ``\'*\'`` (an asterisk), the actual
width\n is read from the next element of the tuple in *values*, and the\n
value to convert comes after the precision.\n\n6. Length modifier
(optional).\n\n7. Conversion type.\n\nWhen the right argument is a
dictionary (or other mapping type), then\nthe formats in the string *must*
include a parenthesised mapping key\ninto that dictionary inserted
immediately after the ``\'%\'`` character.\nThe mapping key
selects the value to be formatted from the mapping.\nFor
example:\n\n>>> print \'%(language)s has %(number)03d quote
types.\' % \\\n... {"language": "Python",
"number": 2}\nPython has 002 quote types.\n\nIn this case no
``*`` specifiers may occur in a format (since they\nrequire a sequential
parameter list).\n\nThe conversion flag characters
are:\n\n+-----------+-----------------------------------------------------------------------+\n|
Flag | Meaning
|\n+===========+=======================================================================+\n|
``\'#\'`` | The value conversion will use the "alternate
form" (where defined |\n| | below).
|\n+-----------+-----------------------------------------------------------------------+\n|
``\'0\'`` | The conversion will be zero padded for numeric
values.
|\n+-----------+-----------------------------------------------------------------------+\n|
``\'-\'`` | The converted value is left adjusted (overrides the
``\'0\'`` |\n| | conversion if both are
given).
|\n+-----------+-----------------------------------------------------------------------+\n|
``\' \'`` | (a space) A blank should be left before a positive
number (or empty |\n| | string) produced by a signed
conversion.
|\n+-----------+-----------------------------------------------------------------------+\n|
``\'+\'`` | A sign character (``\'+\'`` or
``\'-\'``) will precede the conversion |\n| |
(overrides a "space" flag).
|\n+-----------+-----------------------------------------------------------------------+\n\nA
length modifier (``h``, ``l``, or ``L``) may be present, but is\nignored as
it is not necessary for Python -- so e.g. ``%ld`` is\nidentical to
``%d``.\n\nThe conversion types
are:\n\n+--------------+-------------------------------------------------------+---------+\n|
Conversion | Meaning |
Notes
|\n+==============+=======================================================+=========+\n|
``\'d\'`` | Signed integer decimal.
|
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'i\'`` | Signed integer decimal.
|
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'o\'`` | Signed octal value.
| (1)
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'u\'`` | Obsolete type -- it is identical to
``\'d\'``. | (7)
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'x\'`` | Signed hexadecimal (lowercase).
| (2)
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'X\'`` | Signed hexadecimal (uppercase).
| (2)
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'e\'`` | Floating point exponential format (lowercase).
| (3)
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'E\'`` | Floating point exponential format (uppercase).
| (3)
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'f\'`` | Floating point decimal format.
| (3)
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'F\'`` | Floating point decimal format.
| (3)
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'g\'`` | Floating point format. Uses lowercase
exponential | (4) |\n| | format if exponent is less
than -4 or not less than | |\n| | precision, decimal
format otherwise. |
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'G\'`` | Floating point format. Uses uppercase
exponential | (4) |\n| | format if exponent is less
than -4 or not less than | |\n| | precision, decimal
format otherwise. |
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'c\'`` | Single character (accepts integer or single
character | |\n| | string).
|
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'r\'`` | String (converts any Python object using
*repr()*). | (5)
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'s\'`` | String (converts any Python object using
``str()``). | (6)
|\n+--------------+-------------------------------------------------------+---------+\n|
``\'%\'`` | No argument is converted, results in a
``\'%\'`` | |\n| | character in the
result. |
|\n+--------------+-------------------------------------------------------+---------+\n\nNotes:\n\n1.
The alternate form causes a leading zero (``\'0\'``) to be
inserted\n between left-hand padding and the formatting of the number if
the\n leading character of the result is not already a zero.\n\n2. The
alternate form causes a leading ``\'0x\'`` or
``\'0X\'`` (depending\n on whether the ``\'x\'`` or
``\'X\'`` format was used) to be inserted\n between left-hand
padding and the formatting of the number if the\n leading character of
the result is not already a zero.\n\n3. The alternate form causes the
result to always contain a decimal\n point, even if no digits follow
it.\n\n The precision determines the number of digits after the decimal\n
point and defaults to 6.\n\n4. The alternate form causes the result to
always contain a decimal\n point, and trailing zeroes are not removed as
they would otherwise\n be.\n\n The precision determines the number of
significant digits before\n and after the decimal point and defaults to
6.\n\n5. The ``%r`` conversion was added in Python 2.0.\n\n The precision
determines the maximal number of characters used.\n\n6. If the object or
format provided is a ``unicode`` string, the\n resulting string will also
be ``unicode``.\n\n The precision determines the maximal number of
characters used.\n\n7. See **PEP 237**.\n\nSince Python strings have an
explicit length, ``%s`` conversions do\nnot assume that
``\'\\0\'`` is the end of the string.\n\nChanged in version 2.7:
``%f`` conversions for numbers whose absolute\nvalue is over 1e50 are no
longer replaced by ``%g`` conversions.\n\nAdditional string operations are
defined in standard modules\n``string`` and ``re``.\n\n\nXRange
Type\n===========\n\nThe ``xrange`` type is an immutable sequence which is
commonly used\nfor looping. The advantage of the ``xrange`` type is that
an\n``xrange`` object will always take the same amount of memory,
no\nmatter the size of the range it represents. There are no
consistent\nperformance advantages.\n\nXRange objects have very little
behavior: they only support indexing,\niteration, and the ``len()``
function.\n\n\nMutable Sequence Types\n======================\n\nList and
``bytearray`` objects support additional operations that\nallow in-place
modification of the object. Other mutable sequence\ntypes (when added to
the language) should also support these\noperations. Strings and tuples are
immutable sequence types: such\nobjects cannot be modified once created.
The following operations are\ndefined on mutable sequence types (where *x*
is an arbitrary
object):\n\n+--------------------------------+----------------------------------+-----------------------+\n|
Operation | Result | Notes
|\n+================================+==================================+=======================+\n|
``s[i] = x`` | item *i* of *s* is replaced by |
|\n| | *x*
|
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s[i:j] = t`` | slice of *s* from *i* to *j* is |
|\n| | replaced by the
contents of the | |\n|
| iterable *t* |
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``del s[i:j]`` | same as ``s[i:j] = []`` |
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` are | (1)
|\n| | replaced by those of
*t* |
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``del s[i:j:k]`` | removes the elements of |
|\n| | ``s[i:j:k]`` from the
list |
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.append(x)`` | same as ``s[len(s):len(s)] = | (2)
|\n| | [x]``
|
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.extend(x)`` | same as ``s[len(s):len(s)] = x`` | (3)
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.count(x)`` | return number of *i*\'s for which |
|\n| | ``s[i] == x``
|
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.index(x[, i[, j]])`` | return smallest *k* such that | (4)
|\n| | ``s[k] == x`` and ``i
<= k < j`` |
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | (5)
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.pop([i])`` | same as ``x = s[i]; del s[i]; | (6)
|\n| | return x``
|
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.remove(x)`` | same as ``del s[s.index(x)]`` | (4)
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.reverse()`` | reverses the items of *s* in | (7)
|\n| | place
|
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.sort([cmp[, key[, | sort the items of *s* in place |
(7)(8)(9)(10) |\n| reverse]]])`` |
|
|\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1.
*t* must have the same length as the slice it is replacing.\n\n2. The C
implementation of Python has historically accepted multiple\n parameters
and implicitly joined them into a tuple; this no longer\n works in Python
2.0. Use of this misfeature has been deprecated\n since Python
1.4.\n\n3. *x* can be any iterable object.\n\n4. Raises ``ValueError`` when
*x* is not found in *s*. When a negative\n index is passed as the second
or third parameter to the ``index()``\n method, the list length is added,
as for slice indices. If it is\n still negative, it is truncated to
zero, as for slice indices.\n\n Changed in version 2.3: Previously,
``index()`` didn\'t have\n arguments for specifying start and stop
positions.\n\n5. When a negative index is passed as the first parameter to
the\n ``insert()`` method, the list length is added, as for slice\n
indices. If it is still negative, it is truncated to zero, as for\n
slice indices.\n\n Changed in version 2.3: Previously, all negative
indices were\n truncated to zero.\n\n6. The ``pop()`` method is only
supported by the list and array types.\n The optional argument *i*
defaults to ``-1``, so that by default\n the last item is removed and
returned.\n\n7. The ``sort()`` and ``reverse()`` methods modify the list in
place\n for economy of space when sorting or reversing a large list.
To\n remind you that they operate by side effect, they don\'t return
the\n sorted or reversed list.\n\n8. The ``sort()`` method takes optional
arguments for controlling the\n comparisons.\n\n *cmp* specifies a
custom comparison function of two arguments (list\n items) which should
return a negative, zero or positive number\n depending on whether the
first argument is considered smaller than,\n equal to, or larger than the
second argument: ``cmp=lambda x,y:\n cmp(x.lower(), y.lower())``. The
default value is ``None``.\n\n *key* specifies a function of one argument
that is used to extract\n a comparison key from each list element:
``key=str.lower``. The\n default value is ``None``.\n\n *reverse* is a
boolean value. If set to ``True``, then the list\n elements are sorted
as if each comparison were reversed.\n\n In general, the *key* and
*reverse* conversion processes are much\n faster than specifying an
equivalent *cmp* function. This is\n because *cmp* is called multiple
times for each list element while\n *key* and *reverse* touch each
element only once. Use\n ``functools.cmp_to_key()`` to convert an
old-style *cmp* function\n to a *key* function.\n\n Changed in version
2.3: Support for ``None`` as an equivalent to\n omitting *cmp* was
added.\n\n Changed in version 2.4: Support for *key* and *reverse* was
added.\n\n9. Starting with Python 2.3, the ``sort()`` method is guaranteed
to be\n stable. A sort is stable if it guarantees not to change the\n
relative order of elements that compare equal --- this is helpful\n for
sorting in multiple passes (for example, sort by department,\n then by
salary grade).\n\n10. **CPython implementation detail:** While a list is
being sorted,\n the effect of attempting to mutate, or even inspect, the
list is\n undefined. The C implementation of Python 2.3 and newer makes
the\n list appear empty for the duration, and raises ``ValueError`` if\n
it can detect that the list has been mutated during a sort.\n',
'typesseq-mutable': "\nMutable Sequence
Types\n**********************\n\nList and ``bytearray`` objects support
additional operations that\nallow in-place modification of the object.
Other mutable sequence\ntypes (when added to the language) should also
support these\noperations. Strings and tuples are immutable sequence types:
such\nobjects cannot be modified once created. The following operations
are\ndefined on mutable sequence types (where *x* is an arbitrary
object):\n\n+--------------------------------+----------------------------------+-----------------------+\n|
Operation | Result | Notes
|\n+================================+==================================+=======================+\n|
``s[i] = x`` | item *i* of *s* is replaced by |
|\n| | *x*
|
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s[i:j] = t`` | slice of *s* from *i* to *j* is |
|\n| | replaced by the
contents of the | |\n|
| iterable *t* |
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``del s[i:j]`` | same as ``s[i:j] = []`` |
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` are | (1)
|\n| | replaced by those of
*t* |
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``del s[i:j:k]`` | removes the elements of |
|\n| | ``s[i:j:k]`` from the
list |
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.append(x)`` | same as ``s[len(s):len(s)] = | (2)
|\n| | [x]``
|
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.extend(x)`` | same as ``s[len(s):len(s)] = x`` | (3)
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.count(x)`` | return number of *i*'s for which |
|\n| | ``s[i] == x``
|
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.index(x[, i[, j]])`` | return smallest *k* such that | (4)
|\n| | ``s[k] == x`` and ``i
<= k < j`` |
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | (5)
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.pop([i])`` | same as ``x = s[i]; del s[i]; | (6)
|\n| | return x``
|
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.remove(x)`` | same as ``del s[s.index(x)]`` | (4)
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.reverse()`` | reverses the items of *s* in | (7)
|\n| | place
|
|\n+--------------------------------+----------------------------------+-----------------------+\n|
``s.sort([cmp[, key[, | sort the items of *s* in place |
(7)(8)(9)(10) |\n| reverse]]])`` |
|
|\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1.
*t* must have the same length as the slice it is replacing.\n\n2. The C
implementation of Python has historically accepted multiple\n parameters
and implicitly joined them into a tuple; this no longer\n works in Python
2.0. Use of this misfeature has been deprecated\n since Python
1.4.\n\n3. *x* can be any iterable object.\n\n4. Raises ``ValueError`` when
*x* is not found in *s*. When a negative\n index is passed as the second
or third parameter to the ``index()``\n method, the list length is added,
as for slice indices. If it is\n still negative, it is truncated to
zero, as for slice indices.\n\n Changed in version 2.3: Previously,
``index()`` didn't have\n arguments for specifying start and stop
positions.\n\n5. When a negative index is passed as the first parameter to
the\n ``insert()`` method, the list length is added, as for slice\n
indices. If it is still negative, it is truncated to zero, as for\n
slice indices.\n\n Changed in version 2.3: Previously, all negative
indices were\n truncated to zero.\n\n6. The ``pop()`` method is only
supported by the list and array types.\n The optional argument *i*
defaults to ``-1``, so that by default\n the last item is removed and
returned.\n\n7. The ``sort()`` and ``reverse()`` methods modify the list in
place\n for economy of space when sorting or reversing a large list.
To\n remind you that they operate by side effect, they don't return
the\n sorted or reversed list.\n\n8. The ``sort()`` method takes optional
arguments for controlling the\n comparisons.\n\n *cmp* specifies a
custom comparison function of two arguments (list\n items) which should
return a negative, zero or positive number\n depending on whether the
first argument is considered smaller than,\n equal to, or larger than the
second argument: ``cmp=lambda x,y:\n cmp(x.lower(), y.lower())``. The
default value is ``None``.\n\n *key* specifies a function of one argument
that is used to extract\n a comparison key from each list element:
``key=str.lower``. The\n default value is ``None``.\n\n *reverse* is a
boolean value. If set to ``True``, then the list\n elements are sorted
as if each comparison were reversed.\n\n In general, the *key* and
*reverse* conversion processes are much\n faster than specifying an
equivalent *cmp* function. This is\n because *cmp* is called multiple
times for each list element while\n *key* and *reverse* touch each
element only once. Use\n ``functools.cmp_to_key()`` to convert an
old-style *cmp* function\n to a *key* function.\n\n Changed in version
2.3: Support for ``None`` as an equivalent to\n omitting *cmp* was
added.\n\n Changed in version 2.4: Support for *key* and *reverse* was
added.\n\n9. Starting with Python 2.3, the ``sort()`` method is guaranteed
to be\n stable. A sort is stable if it guarantees not to change the\n
relative order of elements that compare equal --- this is helpful\n for
sorting in multiple passes (for example, sort by department,\n then by
salary grade).\n\n10. **CPython implementation detail:** While a list is
being sorted,\n the effect of attempting to mutate, or even inspect, the
list is\n undefined. The C implementation of Python 2.3 and newer makes
the\n list appear empty for the duration, and raises ``ValueError`` if\n
it can detect that the list has been mutated during a sort.\n",
'unary': '\nUnary arithmetic and bitwise
operations\n***************************************\n\nAll unary arithmetic
and bitwise operations have the same priority:\n\n u_expr ::= power |
"-" u_expr | "+" u_expr | "~" u_expr\n\nThe
unary ``-`` (minus) operator yields the negation of its
numeric\nargument.\n\nThe unary ``+`` (plus) operator yields its numeric
argument unchanged.\n\nThe unary ``~`` (invert) operator yields the bitwise
inversion of its\nplain or long integer argument. The bitwise inversion of
``x`` is\ndefined as ``-(x+1)``. It only applies to integral
numbers.\n\nIn all three cases, if the argument does not have the proper
type, a\n``TypeError`` exception is raised.\n',
'while': '\nThe ``while``
statement\n***********************\n\nThe ``while`` statement is used for
repeated execution as long as an\nexpression is true:\n\n while_stmt ::=
"while" expression ":" suite\n
["else" ":" suite]\n\nThis repeatedly tests the
expression and, if it is true, executes the\nfirst suite; if the expression
is false (which may be the first time\nit is tested) the suite of the
``else`` clause, if present, is\nexecuted and the loop terminates.\n\nA
``break`` statement executed in the first suite terminates the
loop\nwithout executing the ``else`` clause\'s suite. A
``continue``\nstatement executed in the first suite skips the rest of the
suite and\ngoes back to testing the expression.\n',
'with': '\nThe ``with``
statement\n**********************\n\nNew in version 2.5.\n\nThe ``with``
statement is used to wrap the execution of a block with\nmethods defined by
a context manager (see section *With Statement\nContext Managers*). This
allows common\n``try``...``except``...``finally`` usage patterns to be
encapsulated\nfor convenient reuse.\n\n with_stmt ::= "with"
with_item ("," with_item)* ":" suite\n with_item ::=
expression ["as" target]\n\nThe execution of the ``with``
statement with one "item" proceeds as\nfollows:\n\n1. The context
expression (the expression given in the ``with_item``)\n is evaluated to
obtain a context manager.\n\n2. The context manager\'s ``__exit__()``
is loaded for later use.\n\n3. The context manager\'s ``__enter__()``
method is invoked.\n\n4. If a target was included in the ``with``
statement, the return\n value from ``__enter__()`` is assigned to it.\n\n
Note: The ``with`` statement guarantees that if the ``__enter__()``\n
method returns without an error, then ``__exit__()`` will always\n be
called. Thus, if an error occurs during the assignment to the\n target
list, it will be treated the same as an error occurring\n within the
suite would be. See step 6 below.\n\n5. The suite is executed.\n\n6. The
context manager\'s ``__exit__()`` method is invoked. If an\n
exception caused the suite to be exited, its type, value, and\n traceback
are passed as arguments to ``__exit__()``. Otherwise,\n three ``None``
arguments are supplied.\n\n If the suite was exited due to an exception,
and the return value\n from the ``__exit__()`` method was false, the
exception is\n reraised. If the return value was true, the exception is\n
suppressed, and execution continues with the statement following\n the
``with`` statement.\n\n If the suite was exited for any reason other than
an exception, the\n return value from ``__exit__()`` is ignored, and
execution proceeds\n at the normal location for the kind of exit that was
taken.\n\nWith more than one item, the context managers are processed as
if\nmultiple ``with`` statements were nested:\n\n with A() as a, B() as
b:\n suite\n\nis equivalent to\n\n with A() as a:\n with B()
as b:\n suite\n\nNote: In Python 2.5, the ``with`` statement is
only allowed when the\n ``with_statement`` feature has been enabled. It
is always enabled\n in Python 2.6.\n\nChanged in version 2.7: Support for
multiple context expressions.\n\nSee also:\n\n **PEP 0343** - The
"with" statement\n The specification, background, and
examples for the Python\n ``with`` statement.\n',
'yield': '\nThe ``yield``
statement\n***********************\n\n yield_stmt ::=
yield_expression\n\nThe ``yield`` statement is only used when defining a
generator\nfunction, and is only used in the body of the generator
function.\nUsing a ``yield`` statement in a function definition is
sufficient to\ncause that definition to create a generator function instead
of a\nnormal function.\n\nWhen a generator function is called, it returns
an iterator known as a\ngenerator iterator, or more commonly, a generator.
The body of the\ngenerator function is executed by calling the
generator\'s ``next()``\nmethod repeatedly until it raises an
exception.\n\nWhen a ``yield`` statement is executed, the state of the
generator is\nfrozen and the value of ``expression_list`` is returned
to\n``next()``\'s caller. By "frozen" we mean that all
local state is\nretained, including the current bindings of local
variables, the\ninstruction pointer, and the internal evaluation stack:
enough\ninformation is saved so that the next time ``next()`` is invoked,
the\nfunction can proceed exactly as if the ``yield`` statement were
just\nanother external call.\n\nAs of Python version 2.5, the ``yield``
statement is now allowed in\nthe ``try`` clause of a ``try`` ...
``finally`` construct. If the\ngenerator is not resumed before it is
finalized (by reaching a zero\nreference count or by being garbage
collected), the generator-\niterator\'s ``close()`` method will be
called, allowing any pending\n``finally`` clauses to execute.\n\nFor full
details of ``yield`` semantics, refer to the *Yield\nexpressions*
section.\n\nNote: In Python 2.2, the ``yield`` statement was only allowed
when the\n ``generators`` feature has been enabled. This ``__future__``
import\n statement was used to enable the feature:\n\n from __future__
import generators\n\nSee also:\n\n **PEP 0255** - Simple Generators\n
The proposal for adding generators and the ``yield`` statement\n to
Python.\n\n **PEP 0342** - Coroutines via Enhanced Generators\n The
proposal that, among other generator enhancements, proposed\n allowing
``yield`` to appear inside a ``try`` ... ``finally``\n block.\n'}