This is /home/pdm/install/Python-2.1/Doc/ref/python-ref.info, produced
by makeinfo version 4.0 from ref.texi.

   April 15, 2001		2.1


File: python-ref.info,  Node: Emulating numeric types,  Prev: Additional methods for emulation of sequence types,  Up: Special method names

Emulating numeric types
-----------------------

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

`__add__(self, other)'

`__sub__(self, other)'

`__mul__(self, other)'

`__div__(self, other)'

`__mod__(self, other)'

`__divmod__(self, other)'

`__pow__(self, other[, modulo])'

`__lshift__(self, other)'

`__rshift__(self, other)'

`__and__(self, other)'

`__xor__(self, other)'

`__or__(self, other)'
     These functions are called to implement the binary arithmetic
     operations (`+', `-', `*', `/', `%', `divmod()', `pow()', `**',
     `<'`<', `>'`>', `&', `^', `|').  For instance, to evaluate the
     expression X`+'Y, where X is an instance of a class that has an
     `__add__()' method, `X.__add__(Y)' is called.  Note that
     `__pow__()' should be defined to accept an optional third argument
     if the ternary version of the built-in `pow()' function is to be
     supported.

`__radd__(self, other)'

`__rsub__(self, other)'

`__rmul__(self, other)'

`__rdiv__(self, other)'

`__rmod__(self, other)'

`__rdivmod__(self, other)'

`__rpow__(self, other)'

`__rlshift__(self, other)'

`__rrshift__(self, other)'

`__rand__(self, other)'

`__rxor__(self, other)'

`__ror__(self, other)'
     These functions are called to implement the binary arithmetic
     operations (`+', `-', `*', `/', `%', `divmod()', `pow()', `**',
     `<'`<', `>'`>', `&', `^', `|') with reflected (swapped) operands.
     These functions are only called if the left operand does not
     support the corresponding operation.  For instance, to evaluate
     the expression X`-'Y, where Y is an instance of a class that has
     an `__rsub__()' method, `Y.__rsub__(X)' is called.  Note that
     ternary `pow()' will not try calling `__rpow__()' (the coercion
     rules would become too complicated).

`__iadd__(self, other)'

`__isub__(self, other)'

`__imul__(self, other)'

`__idiv__(self, other)'

`__imod__(self, other)'

`__ipow__(self, other[, modulo])'

`__ilshift__(self, other)'

`__irshift__(self, other)'

`__iand__(self, other)'

`__ixor__(self, other)'

`__ior__(self, other)'
     These methods are called to implement the augmented arithmetic
     operations (`+=', `-=', `*=', `/=', `%=', `**=', `<'`<=', `>'`>=',
     `&=', `^=', `|=').  These methods should attempt to do the
     operation in-place (modifying SELF) and return the result (which
     could be, but does not have to be, SELF).  If a specific method is
     not defined, the augmented operation falls back to the normal
     methods.  For instance, to evaluate the expression X`+='Y, where X
     is an instance of a class that has an `__iadd__()' method,
     `X.__iadd__(Y)' is called.  If X is an instance of a class that
     does not define a `__iadd()' method, `X.__add__(Y)' and
     `Y.__radd__(X)' are considered, as with the evaluation of X`+'Y.

`__neg__(self)'

`__pos__(self)'

`__abs__(self)'

`__invert__(self)'
     Called to implement the unary arithmetic operations (`-', `+',
     `abs()' and `~{}').

`__complex__(self)'

`__int__(self)'

`__long__(self)'

`__float__(self)'
     Called to implement the built-in functions `complex()', `int()',
     `long()', and `float()'.  Should return a value of the appropriate
     type.

`__oct__(self)'

`__hex__(self)'
     Called to implement the built-in functions `oct()' and `hex()'.
     Should return a string value.

`__coerce__(self, other)'
     Called to implement "mixed-mode" numeric arithmetic.  Should either
     return a 2-tuple containing SELF and OTHER converted to a common
     numeric type, or `None' if conversion is impossible.  When the
     common type would be the type of `other', it is sufficient to
     return `None', since the interpreter will also ask the other
     object to attempt a coercion (but sometimes, if the implementation
     of the other type cannot be changed, it is useful to do the
     conversion to the other type here).

   *Coercion rules*: to evaluate X OP Y, the following steps are taken
(where `__OP__()' and `__rOP__()' are the method names corresponding to
OP, e.g., if OP is ``+'', `__add__()' and `__radd__()' are used).  If
an exception occurs at any point, the evaluation is abandoned and
exception handling takes over.

   * 0.  If X is a string object and OP is the modulo operator (%), the
     string formatting operation is invoked and the remaining steps are
     skipped.

   * 1.  If X is a class instance:

        * 1a.  If X has a `__coerce__()' method: replace X and Y with
          the 2-tuple returned by `X.__coerce__(Y)'; skip to step 2 if
          the coercion returns `None'.

        * 1b.  If neither X nor Y is a class instance after coercion,
          go to step 3.

        * 1c.  If X has a method `__OP__()', return `X.__OP__(Y)';
          otherwise, restore X and Y to their value before step 1a.


   * 2.  If Y is a class instance:

        * 2a.  If Y has a `__coerce__()' method: replace Y and X with
          the 2-tuple returned by `Y.__coerce__(X)'; skip to step 3 if
          the coercion returns `None'.

        * 2b.  If neither X nor Y is a class instance after coercion,
          go to step 3.

        * 2b.  If Y has a method `__rOP__()', return `Y.__rOP__(X)';
          otherwise, restore X and Y to their value before step 2a.


   * 3.  We only get here if neither X nor Y is a class instance.

        * 3a.  If OP is ``+'' and X is a sequence, sequence
          concatenation is invoked.

        * 3b.  If OP is ``*'' and one operand is a sequence and the
          other an integer, sequence repetition is invoked.

        * 3c.  Otherwise, both operands must be numbers; they are
          coerced to a common type if possible, and the numeric
          operation is invoked for that type.




File: python-ref.info,  Node: Execution model,  Next: Expressions,  Prev: Data model,  Up: Top

Execution model
***************

* Menu:

* Code blocks::
* Exceptions::


File: python-ref.info,  Node: Code blocks,  Next: Exceptions,  Prev: Execution model,  Up: Execution model

Code blocks, execution frames, and namespaces
=============================================

   A "code block" is a piece of Python program text that can be
executed as a unit, such as a module, a class definition or a function
body.  Some code blocks (like modules) are normally executed only once,
others (like function bodies) may be executed many times.  Code blocks
may textually contain other code blocks.  Code blocks may invoke other
code blocks (that may or may not be textually contained in them) as
part of their execution, e.g., by invoking (calling) a function.

   The following are code blocks: A module is a code block.  A function
body is a code block.  A class definition is a code block.  Each
command typed interactively is a separate code block; a script file (a
file given as standard input to the interpreter or specified on the
interpreter command line the first argument) is a code block; a script
command (a command specified on the interpreter command line with the
`*-c*' option) is a code block.  The file read by the built-in function
`execfile()' is a code block.  The string argument passed to the
built-in function `eval()' and to the `exec' statement is a code block.
And finally, the expression read and evaluated by the built-in
function `input()' is a code block.

   A code block is executed in an execution frame.  An "execution
frame" contains some administrative information (used for debugging),
determines where and how execution continues after the code block's
execution has completed, and (perhaps most importantly) defines two
namespaces, the local and the global namespace, that affect execution
of the code block.

   A "namespace" is a mapping from names (identifiers) to objects.  A
particular namespace may be referenced by more than one execution
frame, and from other places as well.  Adding a name to a namespace is
called "binding" a name (to an object); changing the mapping of a name
is called "rebinding"; removing a name is "unbinding".  Namespaces are
functionally equivalent to dictionaries (and often implemented as
dictionaries).

   The "local namespace" of an execution frame determines the default
place where names are defined and searched.  The "global namespace"
determines the place where names listed in `global' statements are
defined and searched, and where names that are not bound anywhere in
the current code block are searched.

   Whether a name is local or global in a code block is determined by
static inspection of the source text for the code block: in the absence
of `global' statements, a name that is bound anywhere in the code block
is local in the entire code block; all other names are considered
global.  The `global' statement forces global interpretation of
selected names throughout the code block.  The following constructs
bind names: formal parameters to functions, `import' statements, class
and function definitions (these bind the class or function name in the
defining block), and targets that are identifiers if occurring in an
assignment, `for' loop header, or in the second position of an `except'
clause header.  Local names are searched only on the local namespace;
global names are searched only in the global and built-in namespace.(1)

   A target occurring in a `del' statement is also considered bound for
this purpose (though the actual semantics are to "unbind" the name).

   When a global name is not found in the global namespace, it is
searched in the built-in namespace (which is actually the global
namespace of the module `__builtin__').  The built-in namespace
associated with the execution of a code block is actually found by
looking up the name `__builtins__' is its global namespace; this should
be a dictionary or a module (in the latter case its dictionary is
used).  Normally, the `__builtins__' namespace is the dictionary of the
built-in module `__builtin__' (note: no `s'); if it isn't, restricted
execution mode is in effect.  When a name is not found at all, a
`NameError' exception is raised.

   The following table lists the meaning of the local and global
namespace for various types of code blocks.  The namespace for a
particular module is automatically created when the module is first
imported (i.e., when it is loaded).  Note that in almost all cases, the
global namespace is the namespace of the containing module -- scopes in
Python do not nest!

Code block type    Global namespace   Local namespace    Notes
------             ------             ------             ------
Module             n.s. for this      same as global     
                   module                                
Script (file or    n.s. for           same as global     (1)
command)           `__main__'                            
Interactive        n.s. for           same as global     
command            `__main__'                            
Class definition   global n.s. of     new n.s.           
                   containing block                      
Function body      global n.s. of     new n.s.           (2)
                   containing block                      
String passed to   global n.s. of     local n.s. of      (2), (3)
`exec' statement   containing block   containing block   
String passed to   global n.s. of     local n.s. of      (2), (3)
`eval()'           caller             caller             
File read by       global n.s. of     local n.s. of      (2), (3)
`execfile()'       caller             caller             
Expression read    global n.s. of     local n.s. of      
by `input()'       caller             caller             

   Notes:

`n.s.'
     means _namespace_

`(1)'
     The main module for a script is always called `__main__'; "the
     filename don't enter into it."

`(2)'
     The global and local namespace for these can be overridden with
     optional extra arguments.

`(3)'
     The `exec' statement and the `eval()' and `execfile()' functions
     have optional arguments to override the global and local
     namespace.  If only one namespace is specified, it is used for
     both.

   The built-in functions `globals()' and `locals()' returns a
dictionary representing the current global and local namespace,
respectively.  The effect of modifications to this dictionary on the
namespace are undefined.(2)

   ---------- Footnotes ----------

   (1)  If the code block contains `exec' statements or the construct
"`from ...import *'", the semantics of local names change: local name
lookup first searches the local namespace, then the global namespace
and the built-in namespace.

   (2)  The current implementations return the dictionary actually used
to implement the namespace, _except_ for functions, where the optimizer
may cause the local namespace to be implemented differently, and
`locals()' returns a read-only dictionary.


File: python-ref.info,  Node: Exceptions,  Prev: Code blocks,  Up: Execution model

Exceptions
==========

   Exceptions are a means of breaking out of the normal flow of control
of a code block in order to handle errors or other exceptional
conditions.  An exception is _raised_ at the point where the error is
detected; it may be _handled_ by the surrounding code block or by any
code block that directly or indirectly invoked the code block where the
error occurred.

   The Python interpreter raises an exception when it detects a run-time
error (such as division by zero).  A Python program can also explicitly
raise an exception with the `raise' statement.  Exception handlers are
specified with the `try' ... `except' statement.  The `try' ...
`finally' statement specifies cleanup code which does not handle the
exception, but is executed whether an exception occurred or not in the
preceding code.

   Python uses the "termination" model of error handling: an exception
handler can find out what happened and continue execution at an outer
level, but it cannot repair the cause of the error and retry the
failing operation (except by re-entering the offending piece of code
from the top).

   When an exception is not handled at all, the interpreter terminates
execution of the program, or returns to its interactive main loop.  In
either case, it prints a stack backtrace, except when the exception is
`SystemExit'.

   Exceptions are identified by string objects or class instances.
Selection of a matching except clause is based on object identity
(i.e., two different string objects with the same value represent
different exceptions!)  For string exceptions, the `except' clause must
reference the same string object.  For class exceptions, the `except'
clause must reference the same class or a base class of it.

   When an exception is raised, an object (maybe `None') is passed as
the exception's "parameter" or "value"; this object does not affect the
selection of an exception handler, but is passed to the selected
exception handler as additional information.  For class exceptions,
this object must be an instance of the exception class being raised.

   See also the description of the `try' statement in section *Note try
statement:: and `raise' statement in section *Note raise statement::.


File: python-ref.info,  Node: Expressions,  Next: Simple statements,  Prev: Execution model,  Up: Top

Expressions
***********

   This chapter explains the meaning of the elements of expressions in
Python.

   *Syntax Notes:* In this and the following chapters, extended BNF
notation will be used to describe syntax, not lexical analysis.  When
(one alternative of) a syntax rule has the form

     name:           othername

   and no semantics are given, the semantics of this form of `name' are
the same as for `othername'.

* Menu:

* Arithmetic conversions::
* Atoms::
* Primaries::
* power operator::
* Unary arithmetic operations::
* Binary arithmetic operations::
* Shifting operations::
* Binary bit-wise operations::
* Comparisons::
* Boolean operations::
* Expression lists::
* Summary::


File: python-ref.info,  Node: Arithmetic conversions,  Next: Atoms,  Prev: Expressions,  Up: Expressions

Arithmetic conversions
======================

   When a description of an arithmetic operator below uses the phrase
"the numeric arguments are converted to a common type," the arguments
are coerced using the coercion rules listed at the end of chapter 3.
If both arguments are standard numeric types, the following coercions
are applied:

   * If either argument is a complex number, the other is converted to
     complex;

   * otherwise, if either argument is a floating point number, the
     other is converted to floating point;

   * otherwise, if either argument is a long integer, the other is
     converted to long integer;

   * otherwise, both must be plain integers and no conversion is
     necessary.

   Some additional rules apply for certain operators (e.g., a string
left argument to the `%' operator). Extensions can define their own
coercions.


File: python-ref.info,  Node: Atoms,  Next: Primaries,  Prev: Arithmetic conversions,  Up: Expressions

Atoms
=====

   Atoms are the most basic elements of expressions.  The simplest atoms
are identifiers or literals.  Forms enclosed in reverse quotes or in
parentheses, brackets or braces are also categorized syntactically as
atoms.  The syntax for atoms is:

     atom:      identifier | literal | enclosure
     enclosure: parenth_form|list_display|dict_display|string_conversion

* Menu:

* Identifiers Names::
* Literals 2::
* Parenthesized forms::
* List displays::
* Dictionary displays::
* String conversions::


File: python-ref.info,  Node: Identifiers Names,  Next: Literals 2,  Prev: Atoms,  Up: Atoms

Identifiers (Names)
-------------------

   An identifier occurring as an atom is a reference to a local, global
or built-in name binding.  If a name is assigned to anywhere in a code
block (even in unreachable code), and is not mentioned in a `global'
statement in that code block, then it refers to a local name throughout
that code block.  When it is not assigned to anywhere in the block, or
when it is assigned to but also explicitly listed in a `global'
statement, it refers to a global name if one exists, else to a built-in
name (and this binding may dynamically change).(1)

   When the name is bound to an object, evaluation of the atom yields
that object.  When a name is not bound, an attempt to evaluate it
raises a `NameError' exception.

   *Private name mangling:*when an identifier that textually occurs in
a class definition begins with two or more underscore characters and
does not end in two or more underscores, it is considered a "private
name" of that class.  Private names are transformed to a longer form
before code is generated for them.  The transformation inserts the
class name in front of the name, with leading underscores removed, and
a single underscore inserted in front of the class name.  For example,
the identifier `__spam' occurring in a class named `Ham' will be
transformed to `_Ham__spam'.  This transformation is independent of the
syntactical context in which the identifier is used.  If the
transformed name is extremely long (longer than 255 characters),
implementation defined truncation may happen.  If the class name
consists only of underscores, no transformation is done.

   ---------- Footnotes ----------

   (1) The Python interpreter provides a useful set of predefined
built-in functions.  It is not recommended to reuse (hide) these names
with self defined objects.  See the  for the descriptions of built-in
functions and methods.


File: python-ref.info,  Node: Literals 2,  Next: Parenthesized forms,  Prev: Identifiers Names,  Up: Atoms

Literals
--------

   Python supports string literals and various numeric literals:

     literal: stringliteral | integer | longinteger | floatnumber | imagnumber

   Evaluation of a literal yields an object of the given type (string,
integer, long integer, floating point number, complex number) with the
given value.  The value may be approximated in the case of floating
point and imaginary (complex) literals.  See section *Note Literals::
for details.

   All literals correspond to immutable data types, and hence the
object's identity is less important than its value.  Multiple
evaluations of literals with the same value (either the same occurrence
in the program text or a different occurrence) may obtain the same
object or a different object with the same value.


File: python-ref.info,  Node: Parenthesized forms,  Next: List displays,  Prev: Literals 2,  Up: Atoms

Parenthesized forms
-------------------

   A parenthesized form is an optional expression list enclosed in
parentheses:

     parenth_form:      "(" [expression_list] ")"

   A parenthesized expression list yields whatever that expression list
yields: if the list contains at least one comma, it yields a tuple;
otherwise, it yields the single expression that makes up the expression
list.

   An empty pair of parentheses yields an empty tuple object.  Since
tuples are immutable, the rules for literals apply (i.e., two
occurrences of the empty tuple may or may not yield the same object).

   Note that tuples are not formed by the parentheses, but rather by use
of the comma operator.  The exception is the empty tuple, for which
parentheses _are_ required -- allowing unparenthesized "nothing" in
expressions would cause ambiguities and allow common typos to pass
uncaught.


File: python-ref.info,  Node: List displays,  Next: Dictionary displays,  Prev: Parenthesized forms,  Up: Atoms

List displays
-------------

   A list display is a possibly empty series of expressions enclosed in
square brackets:

     list_display:   "[" [listmaker] "]"
     listmaker:   expression ( list_for | ( "," expression)* [","] )
     list_iter:   list_for | list_if
     list_for:    "for" expression_list "in" testlist [list_iter]
     list_if:     "if" test [list_iter]

   A list display yields a new list object.  Its contents are specified
by providing either a list of expressions or a list comprehension.
When a comma-separated list of expressions is supplied, its elements are
evaluated from left to right and placed into the list object in that
order.  When a list comprehension is supplied, it consists of a single
expression followed by at least one `for' clause and zero or more `for'
or `if' clauses.  In this case, the elements of the new list are those
that would be produced by considering each of the `for' or `if' clauses
a block, nesting from left to right, and evaluating the expression to
produce a list element each time the innermost block is reached.


File: python-ref.info,  Node: Dictionary displays,  Next: String conversions,  Prev: List displays,  Up: Atoms

Dictionary displays
-------------------

   A dictionary display is a possibly empty series of key/datum pairs
enclosed in curly braces:

     dict_display:   "{" [key_datum_list] "}"
     key_datum_list: key_datum ("," key_datum)* [","]
     key_datum:      expression ":" expression

   A dictionary display yields a new dictionary object.

   The key/datum pairs are evaluated from left to right to define the
entries of the dictionary: each key object is used as a key into the
dictionary to store the corresponding datum.

   Restrictions on the types of the key values are listed earlier in
section *Note standard type hierarchy::.  (To summarize,the key type
should be hashable, which excludes all mutable objects.)  Clashes
between duplicate keys are not detected; the last datum (textually
rightmost in the display) stored for a given key value prevails.


File: python-ref.info,  Node: String conversions,  Prev: Dictionary displays,  Up: Atoms

String conversions
------------------

   A string conversion is an expression list enclosed in reverse (a.k.a.
backward) quotes:

     string_conversion: "`" expression_list "`"

   A string conversion evaluates the contained expression list and
converts the resulting object into a string according to rules specific
to its type.

   If the object is a string, a number, `None', or a tuple, list or
dictionary containing only objects whose type is one of these, the
resulting string is a valid Python expression which can be passed to
the built-in function `eval()' to yield an expression with the same
value (or an approximation, if floating point numbers are involved).

   (In particular, converting a string adds quotes around it and
converts "funny" characters to escape sequences that are safe to print.)

   It is illegal to attempt to convert recursive objects (e.g., lists or
dictionaries that contain a reference to themselves, directly or
indirectly.)

   The built-in function `repr()' performs exactly the same conversion
in its argument as enclosing it in parentheses and reverse quotes does.
The built-in function `str()' performs a similar but more
user-friendly conversion.


File: python-ref.info,  Node: Primaries,  Next: power operator,  Prev: Atoms,  Up: Expressions

Primaries
=========

   Primaries represent the most tightly bound operations of the
language.  Their syntax is:

     primary:        atom | attributeref | subscription | slicing | call

* Menu:

* Attribute references::
* Subscriptions::
* Slicings::
* Calls::


File: python-ref.info,  Node: Attribute references,  Next: Subscriptions,  Prev: Primaries,  Up: Primaries

Attribute references
--------------------

   An attribute reference is a primary followed by a period and a name:

     attributeref:   primary "." identifier

   The primary must evaluate to an object of a type that supports
attribute references, e.g., a module, list, or an instance.  This
object is then asked to produce the attribute whose name is the
identifier.  If this attribute is not available, the exception
`AttributeError' is raised.  Otherwise, the type and value of the
object produced is determined by the object.  Multiple evaluations of
the same attribute reference may yield different objects.


File: python-ref.info,  Node: Subscriptions,  Next: Slicings,  Prev: Attribute references,  Up: Primaries

Subscriptions
-------------

   A subscription selects an item of a sequence (string, tuple or list)
or mapping (dictionary) object:

     subscription:   primary "[" expression_list "]"

   The primary must evaluate to an object of a sequence or mapping type.

   If the primary is a mapping, the expression list must evaluate to an
object whose value is one of the keys of the mapping, and the
subscription selects the value in the mapping that corresponds to that
key.  (The expression list is a tuple except if it has exactly one
item.)

   If the primary is a sequence, the expression (list) must evaluate to
a plain integer.  If this value is negative, the length of the sequence
is added to it (so that, e.g., `x[-1]' selects the last item of `x'.)
The resulting value must be a nonnegative integer less than the number
of items in the sequence, and the subscription selects the item whose
index is that value (counting from zero).

   A string's items are characters.  A character is not a separate data
type but a string of exactly one character.


File: python-ref.info,  Node: Slicings,  Next: Calls,  Prev: Subscriptions,  Up: Primaries

Slicings
--------

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

     slicing:          simple_slicing | extended_slicing
     simple_slicing:   primary "[" short_slice "]"
     extended_slicing: primary "[" slice_list "]"
     slice_list:       slice_item ("," slice_item)* [","]
     slice_item:       expression | proper_slice | ellipsis
     proper_slice:     short_slice | long_slice
     short_slice:      [lower_bound] ":" [upper_bound]
     long_slice:       short_slice ":" [stride]
     lower_bound:      expression
     upper_bound:      expression
     stride:           expression
     ellipsis:         "..."

   There is ambiguity in the formal syntax here: anything that looks
like an expression list also looks like a slice list, so any
subscription can be interpreted as a slicing.  Rather than further
complicating the syntax, this is disambiguated by defining that in this
case the interpretation as a subscription takes priority over the
interpretation as a slicing (this is the case if the slice list
contains no proper slice nor ellipses).  Similarly, when the slice list
has exactly one short slice and no trailing comma, the interpretation
as a simple slicing takes priority over that as an extended slicing.

   The semantics for a simple slicing are as follows.  The primary must
evaluate to a sequence object.  The lower and upper bound expressions,
if present, must evaluate to plain integers; defaults are zero and the
`sys.maxint', respectively.  If either bound is negative, the
sequence's length is added to it.  The slicing now selects all items
with index K such that `I <= K < J' where I and J are the specified
lower and upper bounds.  This may be an empty sequence.  It is not an
error if I or J lie outside the range of valid indexes (such items
don't exist so they aren't selected).

   The semantics for an extended slicing are as follows.  The primary
must evaluate to a mapping object, and it is indexed with a key that is
constructed from the slice list, as follows.  If the slice list
contains at least one comma, the key is a tuple containing the
conversion of the slice items; otherwise, the conversion of the lone
slice item is the key.  The conversion of a slice item that is an
expression is that expression.  The conversion of an ellipsis slice
item is the built-in `Ellipsis' object.  The conversion of a proper
slice is a slice object (see section *Note standard type hierarchy::)
whose `start', `stop' and `step' attributes are the values of the
expressions given as lower bound, upper bound and stride, respectively,
substituting `None' for missing expressions.


File: python-ref.info,  Node: Calls,  Prev: Slicings,  Up: Primaries

Calls
-----

   A call calls a callable object (e.g., a function) with a possibly
empty series of arguments:

     call:                   primary "(" [argument_list [","]] ")"
     argument_list:          positional_arguments ["," keyword_arguments]
                           | keyword_arguments
     positional_arguments:   expression ("," expression)*
     keyword_arguments:      keyword_item ("," keyword_item)*
     keyword_item:           identifier "=" expression

   A trailing comma may be present after an argument list but does not
affect the semantics.

   The primary must evaluate to a callable object (user-defined
functions, built-in functions, methods of built-in objects, class
objects, methods of class instances, and certain class instances
themselves are callable; extensions may define additional callable
object types).  All argument expressions are evaluated before the call
is attempted.  Please refer to section *Note Function definitions:: for
the syntax of formal parameter lists.

   If keyword arguments are present, they are first converted to
positional arguments, as follows.  First, a list of unfilled slots is
created for the formal parameters.  If there are N positional
arguments, they are placed in the first N slots.  Next, for each
keyword argument, the identifier is used to determine the corresponding
slot (if the identifier is the same as the first formal parameter name,
the first slot is used, and so on).  If the slot is already filled, a
`TypeError' exception is raised.  Otherwise, the value of the argument
is placed in the slot, filling it (even if the expression is `None', it
fills the slot).  When all arguments have been processed, the slots
that are still unfilled are filled with the corresponding default value
from the function definition.  (Default values are calculated, once,
when the function is defined; thus, a mutable object such as a list or
dictionary used as default value will be shared by all calls that don't
specify an argument value for the corresponding slot; this should
usually be avoided.)  If there are any unfilled slots for which no
default value is specified, a `TypeError' exception is raised.
Otherwise, the list of filled slots is used as the argument list for
the call.

   If there are more positional arguments than there are formal
parameter slots, a `TypeError' exception is raised, unless a formal
parameter using the syntax `*identifier' is present; in this case, that
formal parameter receives a tuple containing the excess positional
arguments (or an empty tuple if there were no excess positional
arguments).

   If any keyword argument does not correspond to a formal parameter
name, a `TypeError' exception is raised, unless a formal parameter
using the syntax `**identifier' is present; in this case, that formal
parameter receives a dictionary containing the excess keyword arguments
(using the keywords as keys and the argument values as corresponding
values), or a (new) empty dictionary if there were no excess keyword
arguments.

   Formal parameters using the syntax `*identifier' or `**identifier'
cannot be used as positional argument slots or as keyword argument
names.  Formal parameters using the syntax `(sublist)' cannot be used
as keyword argument names; the outermost sublist corresponds to a
single unnamed argument slot, and the argument value is assigned to the
sublist using the usual tuple assignment rules after all other
parameter processing is done.

   A call always returns some value, possibly `None', unless it raises
an exception.  How this value is computed depends on the type of the
callable object.

   If it is--

`a user-defined function:'
     The code block for the function is executed, passing it the
     argument list.  The first thing the code block will do is bind the
     formal parameters to the arguments; this is described in section
     *Note Function definitions::.  When the code block executes a
     `return' statement, this specifies the return value of the
     function call.

`a built-in function or method:'
     The result is up to the interpreter; see the  for the descriptions
     of built-in functions and methods.

`a class object:'
     A new instance of that class is returned.

`a class instance method:'
     The corresponding user-defined function is called, with an
     argument list that is one longer than the argument list of the
     call: the instance becomes the first argument.

`a class instance:'
     The class must define a `__call__()' method; the effect is then
     the same as if that method was called.


File: python-ref.info,  Node: power operator,  Next: Unary arithmetic operations,  Prev: Primaries,  Up: Expressions

The power operator
==================

   The power operator binds more tightly than unary operators on its
left; it binds less tightly than unary operators on its right.  The
syntax is:

     power:         primary ["**" u_expr]

   Thus, in an unparenthesized sequence of power and unary operators,
the operators are evaluated from right to left (this does not constrain
the evaluation order for the operands).

   The power operator has the same semantics as the built-in `pow()'
function, when called with two arguments: it yields its left argument
raised to the power of its right argument.  The numeric arguments are
first converted to a common type.  The result type is that of the
arguments after coercion; if the result is not expressible in that type
(as in raising an integer to a negative power, or a negative floating
point number to a broken power), a `TypeError' exception is raised.


File: python-ref.info,  Node: Unary arithmetic operations,  Next: Binary arithmetic operations,  Prev: power operator,  Up: Expressions

Unary arithmetic operations
===========================

   All unary arithmetic (and bit-wise) operations have the same
priority:

     u_expr:         power | "-" u_expr | "+" u_expr | "~" u_expr

   The unary `-' (minus) operator yields the negation of its numeric
argument.

   The unary `+' (plus) operator yields its numeric argument unchanged.

   The unary `~' (invert) operator yields the bit-wise inversion of its
plain or long integer argument.  The bit-wise inversion of `x' is
defined as `-(x+1)'.  It only applies to integral numbers.

   In all three cases, if the argument does not have the proper type, a
`TypeError' exception is raised.


File: python-ref.info,  Node: Binary arithmetic operations,  Next: Shifting operations,  Prev: Unary arithmetic operations,  Up: Expressions

Binary arithmetic operations
============================

   The binary arithmetic operations have the conventional priority
levels.  Note that some of these operations also apply to certain
non-numeric types.  Apart from the power operator, there are only two
levels, one for multiplicative operators and one for additive operators:

     m_expr:         u_expr | m_expr "*" u_expr
                   | m_expr "/" u_expr | m_expr "%" u_expr
     a_expr:         m_expr | aexpr "+" m_expr | aexpr "-" m_expr

   The `*' (multiplication) operator yields the product of its
arguments.  The arguments must either both be numbers, or one argument
must be an integer (plain or long) and the other must be a sequence.
In the former case, the numbers are converted to a common type and then
multiplied together.  In the latter case, sequence repetition is
performed; a negative repetition factor yields an empty sequence.

   The `/' (division) operator yields the quotient of its arguments.
The numeric arguments are first converted to a common type.  Plain or
long integer division yields an integer of the same type; the result is
that of mathematical division with the `floor' function applied to the
result.  Division by zero raises the `ZeroDivisionError' exception.

   The `%' (modulo) operator yields the remainder from the division of
the first argument by the second.  The numeric arguments are first
converted to a common type.  A zero right argument raises the
`ZeroDivisionError' exception.  The arguments may be floating point
numbers, e.g., `3.14%0.7' equals `0.34' (since `3.14' equals `4*0.7 +
0.34'.)  The modulo operator always yields a result with the same sign
as its second operand (or zero); the absolute value of the result is
strictly smaller than the second operand.

   The integer division and modulo operators are connected by the
following identity: `x == (x/y)*y + (x%y)'.  Integer division and
modulo are also connected with the built-in function `divmod()':
`divmod(x, y) == (x/y, x%y)'.  These identities don't hold for floating
point and complex numbers; there similar identities hold approximately
where `x/y' is replaced by `floor(x/y)') or `floor(x/y) - 1' (for
floats),(1) or `floor((x/y).real)' (for complex).

   The `+' (addition) operator yields the sum of its arguments.  The
arguments must either both be numbers or both sequences of the same
type.  In the former case, the numbers are converted to a common type
and then added together.  In the latter case, the sequences are
concatenated.

   The `-' (subtraction) operator yields the difference of its
arguments.  The numeric arguments are first converted to a common type.

   ---------- Footnotes ----------

   (1)  If x is very close to an exact integer multiple of y, it's
possible for `floor(x/y)' to be one larger than `(x-x%y)/y' due to
rounding.  In such cases, Python returns the latter result, in order to
preserve that `divmod(x,y)[0] * y + x %{} y' be very close to `x'.


File: python-ref.info,  Node: Shifting operations,  Next: Binary bit-wise operations,  Prev: Binary arithmetic operations,  Up: Expressions

Shifting operations
===================

   The shifting operations have lower priority than the arithmetic
operations:

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

   These operators accept plain or long integers as arguments.  The
arguments are converted to a common type.  They shift the first
argument to the left or right by the number of bits given by the second
argument.

   A right shift by N bits is defined as division by `pow(2,N)'.  A
left shift by N bits is defined as multiplication with `pow(2,N)'; for
plain integers there is no overflow check so in that case the operation
drops bits and flips the sign if the result is not less than
`pow(2,31)' in absolute value.  Negative shift counts raise a
`ValueError' exception.


File: python-ref.info,  Node: Binary bit-wise operations,  Next: Comparisons,  Prev: Shifting operations,  Up: Expressions

Binary bit-wise operations
==========================

   Each of the three bitwise operations has a different priority level:

     and_expr:       shift_expr | and_expr "&" shift_expr
     xor_expr:       and_expr | xor_expr "^" and_expr
     or_expr:       xor_expr | or_expr "|" xor_expr

   The `&' operator yields the bitwise AND of its arguments, which must
be plain or long integers.  The arguments are converted to a common
type.

   The `^' operator yields the bitwise XOR (exclusive OR) of its
arguments, which must be plain or long integers.  The arguments are
converted to a common type.

   The `|' operator yields the bitwise (inclusive) OR of its arguments,
which must be plain or long integers.  The arguments are converted to a
common type.


File: python-ref.info,  Node: Comparisons,  Next: Boolean operations,  Prev: Binary bit-wise operations,  Up: Expressions

Comparisons
===========

   Unlike C, all comparison operations in Python have the same priority,
which is lower than that of any arithmetic, shifting or bitwise
operation.  Also unlike C, expressions like `a < b < c' have the
interpretation that is conventional in mathematics:

     comparison:     or_expr (comp_operator or_expr)*
     comp_operator:  "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"

   Comparisons yield integer values: `1' for true, `0' for false.

   Comparisons can be chained arbitrarily, e.g., `x < y <= z' is
equivalent to `x < y and y <= z', except that `y' is evaluated only
once (but in both cases `z' is not evaluated at all when `x < y' is
found to be false).

   Formally, if A, B, C, ..., Y, Z are expressions and OPA, OPB, ...,
OPY are comparison operators, then A OPA B OPB C ...Y OPY Z is
equivalent to A OPA B `and' B OPB C `and' ...  Y OPY Z, except that
each expression is evaluated at most once.

   Note that A OPA B OPB C doesn't imply any kind of comparison between
A and C, so that, e.g., `x < y > z' is perfectly legal (though perhaps
not pretty).

   The forms `<>' and `!=' are equivalent; for consistency with C, `!='
is preferred; where `!=' is mentioned below `<>' is also accepted.  The
`<>' spelling is considered obsolescent.

   The operators `<', `>', `==', `>=', `<=', and `!=' compare the
values of two objects.  The objects need not have the same type.  If
both are numbers, they are coverted to a common type.  Otherwise,
objects of different types _always_ compare unequal, and are ordered
consistently but arbitrarily.

   (This unusual definition of comparison was used to simplify the
definition of operations like sorting and the `in' and `not in'
operators.  In the future, the comparison rules for objects of
different types are likely to change.)

   Comparison of objects of the same type depends on the type:

   * Numbers are compared arithmetically.

   * Strings are compared lexicographically using the numeric
     equivalents (the result of the built-in function `ord()') of their
     characters.  Unicode and 8-bit strings are fully interoperable in
     this behavior.

   * Tuples and lists are compared lexicographically using comparison of
     corresponding items.

   * Mappings (dictionaries) are compared through lexicographic
     comparison of their sorted (key, value) lists.(1)

   * Most other types compare unequal unless they are the same object;
     the choice whether one object is considered smaller or larger than
     another one is made arbitrarily but consistently within one
     execution of a program.


   The operators `in' and `not in' test for set membership.  `X in S'
evaluates to true if X is a member of the set S, and false otherwise.
`X not in S' returns the negation of `X in S'.  The set membership test
has traditionally been bound to sequences; an object is a member of a
set if the set is a sequence and contains an element equal to that
object.  However, it is possible for an object to support membership
tests without being a sequence.

   For the list and tuple types, `X in Y' is true if and only if there
exists an index I such that `X == Y[I]' is true.

   For the Unicode and string types, `X in Y' is true if and only if
there exists an index I such that `X == Y[I]' is true. If `X' is not a
string or Unicode object of length `1', a `TypeError' exception is
raised.

   For user-defined classes which define the `__contains__()' method,
`X in Y' is true if and only if `Y.__contains__(X)' is true.

   For user-defined classes which do not define `__contains__()' and do
define `__getitem__()', `X in Y' is true if and only if there is a
non-negative integer index I such that `X == Y[I]', and all lower
integer indices do not raise `IndexError' exception. (If any other
exception is raised, it is as if `in' raised that exception).

   The operator `not in' is defined to have the inverse true value of
`in'.

   The operators `is' and `is not' test for object identity: `X is Y'
is true if and only if X and Y are the same object.  `X is not Y'
yields the inverse truth value.

   ---------- Footnotes ----------

   (1)  This is expensive since it requires sorting the keys first, but
it is about the only sensible definition.  An earlier version of Python
compared dictionaries by identity only, but this caused surprises
because people expected to be able to test a dictionary for emptiness
by comparing it to `{}'.


File: python-ref.info,  Node: Boolean operations,  Next: Expression lists,  Prev: Comparisons,  Up: Expressions

Boolean operations
==================

   Boolean operations have the lowest priority of all Python operations:

     expression:     or_test | lambda_form
     or_test:        and_test | or_test "or" and_test
     and_test:       not_test | and_test "and" not_test
     not_test:       comparison | "not" not_test
     lambda_form:	"lambda" [parameter_list]: expression

   In the context of Boolean operations, and also when expressions are
used by control flow statements, the following values are interpreted
as false: `None', numeric zero of all types, empty sequences (strings,
tuples and lists), and empty mappings (dictionaries).  All other values
are interpreted as true.

   The operator `not' yields `1' if its argument is false, `0'
otherwise.

   The expression `X and Y' first evaluates X; if X is false, its value
is returned; otherwise, Y is evaluated and the resulting value is
returned.

   The expression `X or Y' first evaluates X; if X is true, its value
is returned; otherwise, Y is evaluated and the resulting value is
returned.

   (Note that neither `and' nor `or' restrict the value and type they
return to `0' and `1', but rather return the last evaluated argument.
This is sometimes useful, e.g., if `s' is a string that should be
replaced by a default value if it is empty, the expression `s or 'foo''
yields the desired value.  Because `not' has to invent a value anyway,
it does not bother to return a value of the same type as its argument,
so e.g., `not 'foo'' yields `0', not `'''.)

   Lambda forms (lambda expressions) have the same syntactic position as
expressions.  They are a shorthand to create anonymous functions; the
expression `lambda ARGUMENTS: EXPRESSION' yields a function object that
behaves virtually identical to one defined with

     def name(arguments):
         return expression

   See section *Note Function definitions:: for the syntax of parameter
lists.  Note that functions created with lambda forms cannot contain
statements.

   *Programmer's note:* a lambda form defined inside a function has no
access to names defined in the function's namespace.  This is because
Python has only two scopes: local and global.  A common work-around is
to use default argument values to pass selected variables into the
lambda's namespace, e.g.:

     def make_incrementor(increment):
         return lambda x, n=increment: x+n


File: python-ref.info,  Node: Expression lists,  Next: Summary,  Prev: Boolean operations,  Up: Expressions

Expression lists
================

     expression_list:      expression ("," expression)* [","]

   An expression list containing at least one comma yields a tuple.
The length of the tuple is the number of expressions in the list.  The
expressions are evaluated from left to right.

   The trailing comma is required only to create a single tuple (a.k.a.
a _singleton_); it is optional in all other cases.  A single expression
without a trailing comma doesn't create a tuple, but rather yields the
value of that expression.  (To create an empty tuple, use an empty pair
of parentheses: `()'.)

