7.Compound statements¶
Compound statements contain (groups of) other statements; they affect or controlthe execution of those other statements in some way. In general, compoundstatements span multiple lines, although in simple incarnations a whole compoundstatement may be contained in one line.
Theif,while andfor statements implementtraditional control flow constructs.try specifies exceptionhandlers and/or cleanup code for a group of statements. Function and classdefinitions are also syntactically compound statements.
Compound statements consist of one or more ‘clauses.’ A clause consists of aheader and a ‘suite.’ The clause headers of a particular compound statement areall at the same indentation level. Each clause header begins with a uniquelyidentifying keyword and ends with a colon. A suite is a group of statementscontrolled by a clause. A suite can be one or more semicolon-separated simplestatements on the same line as the header, following the header’s colon, or itcan be one or more indented statements on subsequent lines. Only the latterform of suite can contain nested compound statements; the following is illegal,mostly because it wouldn’t be clear to whichif clause a followingelse clause would belong:
iftest1:iftest2:printx
Also note that the semicolon binds tighter than the colon in this context, sothat in the following example, either all or none of theprintstatements are executed:
ifx<y<z:printx;printy;printz
Summarizing:
compound_stmt ::=if_stmt|while_stmt|for_stmt|try_stmt|with_stmt|funcdef|classdef|decoratedsuite ::=stmt_listNEWLINE | NEWLINE INDENTstatement+ DEDENTstatement ::=stmt_listNEWLINE |compound_stmtstmt_list ::=simple_stmt(";"simple_stmt)* [";"]
Note that statements always end in aNEWLINE possibly followed by aDEDENT. Also note that optional continuation clauses always begin with akeyword that cannot start a statement, thus there are no ambiguities (the‘danglingelse’ problem is solved in Python by requiring nestedif statements to be indented).
The formatting of the grammar rules in the following sections places each clauseon a separate line for clarity.
7.1.Theif statement¶
Theif statement is used for conditional execution:
if_stmt ::= "if"expression":"suite( "elif"expression":"suite)* ["else" ":"suite]
It selects exactly one of the suites by evaluating the expressions one by oneuntil one is found to be true (see sectionBoolean operations for the definition oftrue and false); then that suite is executed (and no other part of theif statement is executed or evaluated). If all expressions arefalse, the suite of theelse clause, if present, is executed.
7.2.Thewhile statement¶
Thewhile statement is used for repeated execution as long as anexpression is true:
while_stmt ::= "while"expression":"suite["else" ":"suite]
This repeatedly tests the expression and, if it is true, executes the firstsuite; if the expression is false (which may be the first time it is tested) thesuite of theelse clause, if present, is executed and the loopterminates.
Abreak statement executed in the first suite terminates the loopwithout executing theelse clause’s suite. Acontinuestatement executed in the first suite skips the rest of the suite and goes backto testing the expression.
7.3.Thefor statement¶
Thefor statement is used to iterate over the elements of a sequence(such as a string, tuple or list) or other iterable object:
for_stmt ::= "for"target_list"in"expression_list":"suite["else" ":"suite]
The expression list is evaluated once; it should yield an iterable object. Aniterator is created for the result of theexpression_list. The suite isthen executed once for each item provided by the iterator, in the order ofascending indices. Each item in turn is assigned to the target list using thestandard rules for assignments, and then the suite is executed. When the itemsare exhausted (which is immediately when the sequence is empty), the suite intheelse clause, if present, is executed, and the loop terminates.
Abreak statement executed in the first suite terminates the loopwithout executing theelse clause’s suite. Acontinuestatement executed in the first suite skips the rest of the suite and continueswith the next item, or with theelse clause if there was no nextitem.
The suite may assign to the variable(s) in the target list; this does not affectthe next item assigned to it.
The target list is not deleted when the loop is finished, but if the sequence isempty, it will not have been assigned to at all by the loop. Hint: the built-infunctionrange() returns a sequence of integers suitable to emulate theeffect of Pascal’sfori:=atobdo; e.g.,range(3) returns the list[0,1,2].
Note
There is a subtlety when the sequence is being modified by the loop (this canonly occur for mutable sequences, e.g. lists). An internal counter is used tokeep track of which item is used next, and this is incremented on eachiteration. When this counter has reached the length of the sequence the loopterminates. This means that if the suite deletes the current (or a previous)item from the sequence, the next item will be skipped (since it gets the indexof the current item which has already been treated). Likewise, if the suiteinserts an item in the sequence before the current item, the current item willbe treated again the next time through the loop. This can lead to nasty bugsthat can be avoided by making a temporary copy using a slice of the wholesequence, e.g.,
forxina[:]:ifx<0:a.remove(x)
7.4.Thetry statement¶
Thetry statement specifies exception handlers and/or cleanup codefor a group of statements:
try_stmt ::= try1_stmt | try2_stmttry1_stmt ::= "try" ":"suite("except" [expression[("as" | ",")identifier]] ":"suite)+ ["else" ":"suite] ["finally" ":"suite]try2_stmt ::= "try" ":"suite"finally" ":"suite
Changed in version 2.5:In previous versions of Python,try…except…finally did not work.try…except had to benested intry…finally.
Theexcept clause(s) specify one or more exception handlers. When noexception occurs in thetry clause, no exception handler is executed.When an exception occurs in thetry suite, a search for an exceptionhandler is started. This search inspects the except clauses in turn until oneis found that matches the exception. An expression-less except clause, ifpresent, must be last; it matches any exception. For an except clause with anexpression, that expression is evaluated, and the clause matches the exceptionif the resulting object is “compatible” with the exception. An object iscompatible with an exception if it is the class or a base class of the exceptionobject, or a tuple containing an item compatible with the exception.
If no except clause matches the exception, the search for an exception handlercontinues in the surrounding code and on the invocation stack.1
If the evaluation of an expression in the header of an except clause raises anexception, the original search for a handler is canceled and a search starts forthe new exception in the surrounding code and on the call stack (it is treatedas if the entiretry statement raised the exception).
When a matching except clause is found, the exception is assigned to the targetspecified in that except clause, if present, and the except clause’s suite isexecuted. All except clauses must have an executable block. When the end ofthis block is reached, execution continues normally after the entire trystatement. (This means that if two nested handlers exist for the sameexception, and the exception occurs in the try clause of the inner handler, theouter handler will not handle the exception.)
Before an except clause’s suite is executed, details about the exception areassigned to three variables in thesys module:sys.exc_type receivesthe object identifying the exception;sys.exc_value receives the exception’sparameter;sys.exc_traceback receives a traceback object (see sectionThe standard type hierarchy) identifying the point in the program where the exceptionoccurred. These details are also available through thesys.exc_info()function, which returns a tuple(exc_type,exc_value,exc_traceback). Useof the corresponding variables is deprecated in favor of this function, sincetheir use is unsafe in a threaded program. As of Python 1.5, the variables arerestored to their previous values (before the call) when returning from afunction that handled an exception.
The optionalelse clause is executed if the control flow leaves thetry suite, no exception was raised, and noreturn,continue, orbreak statement was executed. Exceptions intheelse clause are not handled by the precedingexceptclauses.
Iffinally is present, it specifies a ‘cleanup’ handler. Thetry clause is executed, including anyexcept andelse clauses. If an exception occurs in any of the clauses and isnot handled, the exception is temporarily saved. Thefinally clauseis executed. If there is a saved exception, it is re-raised at the end of thefinally clause. If thefinally clause raises anotherexception or executes areturn orbreak statement, thesaved exception is discarded:
>>>deff():...try:...1/0...finally:...return42...>>>f()42
The exception information is not available to the program during execution ofthefinally clause.
When areturn,break orcontinue statement isexecuted in thetry suite of atry…finallystatement, thefinally clause is also executed ‘on the way out.’ Acontinue statement is illegal in thefinally clause. (Thereason is a problem with the current implementation — this restriction may belifted in the future).
The return value of a function is determined by the lastreturnstatement executed. Since thefinally clause always executes, areturn statement executed in thefinally clause willalways be the last one executed:
>>>deffoo():...try:...return'try'...finally:...return'finally'...>>>foo()'finally'
Additional information on exceptions can be found in sectionExceptions,and information on using theraise statement to generate exceptionsmay be found in sectionThe raise statement.
7.5.Thewith statement¶
New in version 2.5.
Thewith statement is used to wrap the execution of a block withmethods defined by a context manager (see sectionWith Statement Context Managers). Thisallows commontry…except…finally usagepatterns to be encapsulated for convenient reuse.
with_stmt ::= "with" with_item ("," with_item)* ":"suitewith_item ::=expression ["as"target]The execution of thewith statement with one “item” proceeds as follows:
The context expression (the expression given in the
with_item) isevaluated to obtain a context manager.The context manager’s
__exit__()is loaded for later use.The context manager’s
__enter__()method is invoked.If a target was included in the
withstatement, the return valuefrom__enter__()is assigned to it.Note
The
withstatement guarantees that if the__enter__()methodreturns without an error, then__exit__()will always be called. Thus, ifan error occurs during the assignment to the target list, it will be treated thesame as an error occurring within the suite would be. See step 6 below.The suite is executed.
The context manager’s
__exit__()method is invoked. If an exceptioncaused the suite to be exited, its type, value, and traceback are passed asarguments to__exit__(). Otherwise, threeNonearguments aresupplied.If the suite was exited due to an exception, and the return value from the
__exit__()method was false, the exception is reraised. If the returnvalue was true, the exception is suppressed, and execution continues with thestatement following thewithstatement.If the suite was exited for any reason other than an exception, the return valuefrom
__exit__()is ignored, and execution proceeds at the normal locationfor the kind of exit that was taken.
With more than one item, the context managers are processed as if multiplewith statements were nested:
withA()asa,B()asb:suite
is equivalent to
withA()asa:withB()asb:suite
Note
In Python 2.5, thewith statement is only allowed when thewith_statement feature has been enabled. It is always enabled inPython 2.6.
Changed in version 2.7:Support for multiple context expressions.
7.6.Function definitions¶
A function definition defines a user-defined function object (see sectionThe standard type hierarchy):
decorated ::= decorators (classdef | funcdef)decorators ::=decorator+decorator ::= "@"dotted_name["(" [argument_list[","]] ")"] NEWLINEfuncdef ::= "def"funcname"(" [parameter_list] ")" ":"suitedotted_name ::=identifier("."identifier)*parameter_list ::= (defparameter",")* ( "*"identifier["," "**"identifier] | "**"identifier|defparameter[","] )defparameter ::=parameter["="expression]sublist ::=parameter(","parameter)* [","]parameter ::=identifier| "("sublist")"funcname ::=identifier
A function definition is an executable statement. Its execution binds thefunction name in the current local namespace to a function object (a wrapperaround the executable code for the function). This function object contains areference to the current global namespace as the global namespace to be usedwhen the function is called.
The function definition does not execute the function body; this gets executedonly when the function is called.2
A function definition may be wrapped by one or moredecorator expressions.Decorator expressions are evaluated when the function is defined, in the scopethat contains the function definition. The result must be a callable, which isinvoked with the function object as the only argument. The returned value isbound to the function name instead of the function object. Multiple decoratorsare applied in nested fashion. For example, the following code:
@f1(arg)@f2deffunc():pass
is equivalent to:
deffunc():passfunc=f1(arg)(f2(func))
When one or more top-levelparameters have the formparameter=expression, the function is said to have “default parametervalues.” For a parameter with a default value, the correspondingargument may be omitted from a call, in whichcase the parameter’s default value is substituted. If aparameter has a default value, all following parameters must also have a defaultvalue — this is a syntactic restriction that is not expressed by the grammar.
Default parameter values are evaluated when the function definition isexecuted. This means that the expression is evaluated once, when the functionis defined, and that the same “pre-computed” value is used for each call. Thisis especially important to understand when a default parameter is a mutableobject, such as a list or a dictionary: if the function modifies the object(e.g. by appending an item to a list), the default value is in effect modified.This is generally not what was intended. A way around this is to useNoneas the default, and explicitly test for it in the body of the function, e.g.:
defwhats_on_the_telly(penguin=None):ifpenguinisNone:penguin=[]penguin.append("property of the zoo")returnpenguin
Function call semantics are described in more detail in sectionCalls. Afunction call always assigns values to all parameters mentioned in the parameterlist, either from position arguments, from keyword arguments, or from defaultvalues. If the form “*identifier” is present, it is initialized to a tuplereceiving any excess positional parameters, defaulting to the empty tuple. Ifthe form “**identifier” is present, it is initialized to a new dictionaryreceiving any excess keyword arguments, defaulting to a new empty dictionary.
It is also possible to create anonymous functions (functions not bound to aname), for immediate use in expressions. This uses lambda expressions, described insectionLambdas. Note that the lambda expression is merely a shorthand for asimplified function definition; a function defined in a “def”statement can be passed around or assigned to another name just like a functiondefined by a lambda expression. The “def” form is actually more powerfulsince it allows the execution of multiple statements.
Programmer’s note: Functions are first-class objects. A “def” formexecuted inside a function definition defines a local function that can bereturned or passed around. Free variables used in the nested function canaccess the local variables of the function containing the def. See sectionNaming and binding for details.
7.7.Class definitions¶
A class definition defines a class object (see sectionThe standard type hierarchy):
classdef ::= "class"classname[inheritance] ":"suiteinheritance ::= "(" [expression_list] ")"classname ::=identifier
A class definition is an executable statement. It first evaluates theinheritance list, if present. Each item in the inheritance list should evaluateto a class object or class type which allows subclassing. The class’s suite isthen executed in a new execution frame (see sectionNaming and binding), using anewly created local namespace and the original global namespace. (Usually, thesuite contains only function definitions.) When the class’s suite finishesexecution, its execution frame is discarded but its local namespace issaved.3 A class object is then created using the inheritance list for thebase classes and the saved local namespace for the attribute dictionary. Theclass name is bound to this class object in the original local namespace.
Programmer’s note: Variables defined in the class definition are classvariables; they are shared by all instances. To create instance variables, theycan be set in a method withself.name=value. Both class and instancevariables are accessible through the notation “self.name”, and an instancevariable hides a class variable with the same name when accessed in this way.Class variables can be used as defaults for instance variables, but usingmutable values there can lead to unexpected results. Fornew-styleclasses, descriptors can be used to create instance variables with differentimplementation details.
Class definitions, like function definitions, may be wrapped by one or moredecorator expressions. The evaluation rules for the decoratorexpressions are the same as for functions. The result must be a class object,which is then bound to the class name.
Footnotes
- 1
The exception is propagated to the invocation stack unlessthere is a
finallyclause which happens to raise anotherexception. That new exception causes the old one to be lost.- 2
A string literal appearing as the first statement in the function body istransformed into the function’s
__doc__attribute and therefore thefunction’sdocstring.- 3
A string literal appearing as the first statement in the class body istransformed into the namespace’s
__doc__item and therefore the class’sdocstring.
