Table of Contents
Previous Chapter
Simple statements are comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons. The syntax for simple statements is:
simple_stmt: expression_stmt | assignment_stmt | pass_stmt | del_stmt | print_stmt | return_stmt | raise_stmt | break_stmt | continue_stmt | import_stmt | global_stmt | exec_stmt
Expression statements are used (mostly interactively) to compute and write a value, or (usually) to call a procedure (a function that returns no meaningful result; in Python, procedures return the value None
). Other uses of expression statements are allowed and occasionally useful. The syntax for an expression statement is:
expression_stmt: expression_list
An expression statement evaluates the expression list (which may be a single expression). In interactive mode, if the value is not None
, it is converted to a string using the built-in repr() function and the resulting string is written to standard output (see "The print statement" on page41) on a line by itself. (Expression statements yielding None are not written, so that procedure calls do not cause any output.)
Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects:
assignment_stmt: (target_list "=")+ expression_list target_list: target ("," target)* [","] target: identifier | "(" target_list ")" | "[" target_list "]" | attributeref | subscription | slicing
(See "Primaries" on page29 for the syntax definitions for the last three symbols.)
An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.
Assignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is unacceptable. The rules observed by various types and the exceptions raised are given with the definition of the object types (See "The standard type hierarchy" on page12.)
Assignment of an object to a target list is recursively defined as follows.
Assignment of an object to a single target is recursively defined as follows.
global
statement in the current code block: the name is bound to the object in the current local name space.TypeError
is raised. That object is then asked to assign the assigned object to the given attribute; if it cannot perform the assignment, it raises an exception (usually but not necessarily AttributeError
).
IndexError
is raised (assignment to a subscripted sequence cannot add new items to a list).
(In the current implementation, the syntax for targets is taken to be the same as for expressions, and invalid syntax is rejected during the code generation phase, causing less detailed error messages.)
WARNING: Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are `safe' (e.g. ``a,
b
=
b,
a
'' swaps two variables), overlaps within the collection of assigned-to variables are not safe! For instance, the following program prints ``[0,2]'':
x = [0, 1] i = 0 i, x[i] = 1, 2 print x
pass
statementpass_stmt: "pass"
pass is a null operation when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:
def f(arg): pass # a function that does nothing (yet) class C: pass # a class with no methods (yet)
del
statementdel_stmt: "del" target_list
Deletion is recursively defined very similar to the way assignment is defined. Rather that spelling it out in full details, here are some hints.
Deletion of a target list recursively deletes each target, from left to right.
Deletion of a name removes the binding of that name (which must exist) from the local or global name space, depending on whether the name occurs in a global
statement in the same code block.
Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object).
print
statementprint_stmt: "print" [ expression ("," expression)* [","] ]
print evaluates each expression in turn and writes the resulting object to standard output (see below). If an object is not a string, it is first converted to a string using the rules for string conversions. The (resulting or original) string is then written. A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line. This is the case: (1) when no characters have yet been written to standard output; or (2) when the last character written to standard output is \n
; or (3) when the last write operation on standard output was not a print
statement. (In some cases it may be functional to write an empty string to standard output for this reason.)
A "\n"
character is written at the end, unless the print
statement ends with a comma. This is the only action if the statement contains just the keyword print
. Standard output is defined as the file object named stdout
in the built-in module sys
. If no such object exists, or if it is not a writable file, a RuntimeError
exception is raised. (The original implementation attempts to write to the system's original standard output instead, but this is not safe, and should be fixed.)
return
statementreturn_stmt: "return" [expression_list]
return may only occur syntactically nested in a function definition, not within a nested class definition.
If an expression list is present, it is evaluated, else None
is substituted.
return
leaves the current function call with the expression list (or None
) as return value.
When return
passes control out of a try
statement with a finally
clause, that finally clause is executed before really leaving the function.
raise
statementraise_stmt: "raise" expression ["," expression ["," expression]]
raise evaluates its first expression, which must yield a string, class, or instance object. If there is a second expression, this is evaluated, else None
is substituted. If the first expression is a class object, then the second expression must be an instance of that class or one of its derivatives. If the first expression is an instance object, the second expression must be None
.
If the first object is a class or string, it then raises the exception identified by the first object, with the second one (or None
) as its parameter. If the first object is an instance, it raises the exception identified by the class of the object, with the instance as its parameter (and there should be no second object, or the second object should be None
).
If a third object is present, and it is not None
, it should be a traceback object (see page17 traceback objects), and it is substituted instead of the current location as the place where the exception occurred. This is useful to re-raise an exception transparently in an except clause.
break
statementbreak_stmt: "break"
break may only occur syntactically nested in a for
or while
loop, but not nested in a function or class definition within that loop.
It terminates the nearest enclosing loop, skipping the optional else
clause if the loop has one.
If a for
loop is terminated by break
, the loop control target keeps its current value.
When break
passes control out of a try
statement with a finally
clause, that finally clause is executed before really leaving the loop.
continue
statementcontinue_stmt: "continue"
continue may only occur syntactically nested in a for
or while
loop, but not nested in a function or class definition or try
statement within that loop.(1) It continues with the next cycle of the nearest enclosing loop.
import
statementimport_stmt: "import" identifier ("," identifier)* | "from" identifier "import" identifier ("," identifier)* | "from" identifier "import" "*"
Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local name space (of the scope where the import
statement occurs). The first form (without from
) repeats these steps for each identifier in the list, the from
form performs them once, with the first identifier specifying the module name.
The system maintains a table of modules that have been initialized, indexed by module name. (The current implementation makes this table accessible as sys.modules
.) When a module name is found in this table, step (1) is finished. If not, a search for a module definition is started. This first looks for a built-in module definition, and if no built-in module if the given name is found, it searches a user-specified list of directories for a file whose name is the module name with extension ".py"
. (The current implementation uses the list of strings sys.path
as the search path; it is initialized from the shell environment variable $PYTHONPATH
, with an installation-dependent default.)
If a built-in module is found, its built-in initialization code is executed and step (1) is finished. If no matching file is found, ImportError
is raised. If a file is found, it is parsed, yielding an executable code block. If a syntax error occurs, SyntaxError
is raised. Otherwise, an empty module of the given name is created and inserted in the module table, and then the code block is executed in the context of this module. Exceptions during this execution terminate step (1).
When step (1) finishes without raising an exception, step (2) can begin.
The first form of import
statement binds the module name in the local name space to the module object, and then goes on to import the next identifier, if any. The from
form does not bind the module name: it goes through the list of identifiers, looks each one of them up in the module found in step (1), and binds the name in the local name space to the object thus found. If a name is not found, ImportError
is raised. If the list of identifiers is replaced by a star (*
), all names defined in the module are bound, except those beginning with an underscore(_
).
Names bound by import statements may not occur in global
statements in the same scope.
The from
form with *
may only occur in a module scope.
(The current implementation does not enforce the latter two restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.)
global
statementglobal_stmt: "global" identifier ("," identifier)*
The global
statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. While using global names is automatic if they are not defined in the local scope, assigning to global names would be impossible without global
.
Names listed in a global
statement must not be used in the same code block before that global
statement is executed.
Names listed in a global
statement must not be defined as formal parameters or in a for
loop control target, class
definition, function definition, or import
statement.
(The current implementation does not enforce the latter two restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.)
Note: the global
is a directive to the parser. Therefore, it applies only to code parsed at the same time as the global
statement. In particular, a global
statement contained in an exec
statement does not affect the code block containing the exec
statement, and code contained in an exec
statement is unaffected by global
statements in the code containing the exec
statement. The same applies to the eval()
, execfile()
and compile()
functions.
exec
statementexec_stmt: "exec" expression ["in" expression ["," expression]]
This statement supports dynamic execution of Python code. The first expression should evaluate to either a string, an open file object, or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). If it is an open file, the file is parsed until EOF and executed. If it is a code object, it is simply executed.
In all cases, if the optional parts are omitted, the code is executed in the current scope. If only the first expression after in
is specified, it should be a dictionary, which will be used for both the global and the local variables. If two expressions are given, both must be dictionaries and they are used for the global and local variables, respectively.
Hints: dynamic evaluation of expressions is supported by the built-in function eval()
. The built-in functions globals()
and locals()
return the current global and local dictionary, respectively, which may be useful to pass around for use by exec
.