Movatterモバイル変換


[0]ホーム

URL:


Navigation

8. 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, while thewith statement allows the execution of initialization andfinalization code around a block of code. Function and class definitions arealso 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:print(x)

Also note that the semicolon binds tighter than the colon in this context, sothat in the following example, either all or none of theprint() calls areexecuted:

ifx<y<z:print(x);print(y);print(z)

Summarizing:

compound_stmt ::=if_stmt                   |while_stmt                   |for_stmt                   |try_stmt                   |with_stmt                   |funcdef                   |classdefsuite ::=stmt_list NEWLINE | NEWLINE INDENTstatement+ DEDENTstatement ::=stmt_list NEWLINE |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.

8.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.

8.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.

8.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 (seeAssignment statements), and then the suite isexecuted. When the items are exhausted (which is immediately when the sequenceis empty or an iterator raises aStopIteration exception), 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.

Names in the target list are not deleted when the loop is finished, but if thesequence is empty, it will not have been assigned to at all by the loop. Hint:the built-in functionrange() returns an iterator of integers suitable toemulate the effect of Pascal’sfori:=atobdo; e.g.,list(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, i.e. lists). An internal counter is usedto keep 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 theindex of the current item which has already been treated). Likewise, if thesuite inserts an item in the sequence before the current item, the currentitem will be treated again the next time through the loop. This can lead tonasty bugs that can be avoided by making a temporary copy using a slice ofthe whole sequence, e.g.,

forxina[:]:ifx<0:a.remove(x)

8.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"target]] ":"suite)+               ["else" ":"suite]               ["finally" ":"suite]try2_stmt ::=  "try" ":"suite               "finally" ":"suite

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 after theas keyword in that except clause, if present, andthe except clause’s suite is executed. All except clauses must have anexecutable block. When the end of this block is reached, execution continuesnormally after the entire try statement. (This means that if two nestedhandlers exist for the same exception, and the exception occurs in the tryclause of the inner handler, the outer handler will not handle the exception.)

When an exception has been assigned usingastarget, it is cleared at theend of the except clause. This is as if

exceptEasN:foo

was translated to

exceptEasN:try:foofinally:delN

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

Before an except clause’s suite is executed, details about the exception arestored in thesys module and can be access viasys.exc_info().sys.exc_info() returns a 3-tuple consisting of the exception class, theexception instance and a traceback object (see sectionThe standard type hierarchy) identifyingthe point in the program where the exception occurred.sys.exc_info()values are restored to their previous values (before the call) when returningfrom a function that handled an exception.

The optionalelse clause is executed if and when control flows offthe end of thetry clause.[2] Exceptions in theelseclause are not handled by the precedingexcept clauses.

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, the saved exception is set as the context of the new exception.If thefinally clause executes areturn orbreakstatement, the saved exception is discarded:

deff():try:1/0finally: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).

Additional information on exceptions can be found in sectionExceptions,and information on using theraise statement to generate exceptionsmay be found in sectionThe raise statement.

8.5. Thewith statement

Thewith statement is used to wrap the execution of a block withmethods defined by a context manager (see sectionWith Statement Context Managers).This allows commontry...except...finallyusage patterns 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:

  1. The context expression (the expression given in thewith_item) isevaluated to obtain a context manager.

  2. The context manager’s__exit__() is loaded for later use.

  3. The context manager’s__enter__() method is invoked.

  4. If a target was included in thewith statement, the return valuefrom__enter__() is assigned to it.

    Note

    Thewith statement guarantees that if the__enter__()method returns without an error, then__exit__() will always becalled. Thus, if an error occurs during the assignment to the target list,it will be treated the same as an error occurring within the suite wouldbe. See step 6 below.

  5. The suite is executed.

  6. 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, threeNone arguments 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 thewith statement.

    If the suite was exited for any reason other than an exception, the returnvalue from__exit__() is ignored, and execution proceeds at the normallocation for 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

Changed in version 3.1:Support for multiple context expressions.

See also

PEP 0343 - The “with” statement
The specification, background, and examples for the Pythonwithstatement.

8.6. Function definitions

A function definition defines a user-defined function object (see sectionThe standard type hierarchy):

funcdef ::=  [decorators] "def"funcname "(" [parameter_list] ")" ["->"expression] ":"suitedecorators ::=decorator+decorator ::=  "@"dotted_name ["(" [parameter_list [","]] ")"] NEWLINEdotted_name ::=identifier ("."identifier)*parameter_list ::=  (defparameter ",")*                    ( "*" [parameter] (","defparameter)* ["," "**"parameter]                    | "**"parameter                    |defparameter [","] )parameter ::=identifier [":"expression]defparameter ::=parameter ["="expression]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.[3]

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 moreparameters have the formparameter=expression, the function is said to have “default parameter values.” For aparameter with a default value, the correspondingargument may beomitted from a call, in whichcase the parameter’s default value is substituted. If a parameter has a defaultvalue, all following parameters up until the “*” 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.Parameters after “*” or “*identifier” are keyword-only parameters andmay only be passed used keyword arguments.

Parameters may have annotations of the form “:expression” following theparameter name. Any parameter may have an annotation even those of the form*identifier or**identifier. Functions may have “return” annotation ofthe form “->expression” after the parameter list. These annotations can beany valid Python expression and are evaluated when the function definition isexecuted. Annotations may be evaluated in a different order than they appear inthe source code. The presence of annotations does not change the semantics of afunction. The annotation values are available as values of a dictionary keyedby the parameters’ names in the__annotations__ attribute of thefunction object.

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 and annotations.

Programmer’s note: Functions are first-class objects. A “def” statementexecuted 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.

See also

PEP 3107 - Function Annotations
The original specification for function annotations.

8.7. Class definitions

A class definition defines a class object (see sectionThe standard type hierarchy):

classdef ::=  [decorators] "class"classname [inheritance] ":"suiteinheritance ::=  "(" [parameter_list] ")"classname ::=identifier

A class definition is an executable statement. The inheritance list usuallygives a list of base classes (seeCustomizing class creation for more advanced uses), soeach item in the list should evaluate to a class object which allowssubclassing. Classes without an inheritance list inherit, by default, from thebase classobject; hence,

classFoo:pass

is equivalent to

classFoo(object):pass

The class’s suite is then executed in a new execution frame (seeNaming and binding),using a newly created local namespace and the original global namespace.(Usually, the suite contains mostly function definitions.) When the class’ssuite finishes execution, its execution frame is discarded but its localnamespace is saved.[4] A class object is then created using the inheritancelist for the base classes and the saved local namespace for the attributedictionary. The class name is bound to this class object in the original localnamespace.

Class creation can be customized heavily usingmetaclasses.

Classes can also be decorated: just like when decorating functions,

@f1(arg)@f2classFoo:pass

is equivalent to

classFoo:passFoo=f1(arg)(f2(Foo))

The evaluation rules for the decorator expressions are the same as for functiondecorators. The result must be a class object, which is then bound to the classname.

Programmer’s note: Variables defined in the class definition are classattributes; they are shared by instances. Instance attributes can be set in amethod withself.name=value. Both class and instance attributes areaccessible through the notation “self.name”, and an instance attribute hidesa class attribute with the same name when accessed in this way. Classattributes can be used as defaults for instance attributes, but using mutablevalues there can lead to unexpected results.Descriptorscan be used to create instance variables with different implementation details.

See also

PEP 3115 - Metaclasses in Python 3PEP 3129 - Class Decorators

Footnotes

[1]The exception is propagated to the invocation stack unlessthere is afinally clause which happens to raise anotherexception. That new exception causes the old one to be lost.
[2]Currently, control “flows off the end” except in the case of an exceptionor the execution of areturn,continue, orbreak statement.
[3]A string literal appearing as the first statement in the function body istransformed into the function’s__doc__ attribute and therefore thefunction’sdocstring.
[4]A string literal appearing as the first statement in the class body istransformed into the namespace’s__doc__ item and therefore the class’sdocstring.

Table Of Contents

Previous topic

7. Simple statements

Next topic

9. Top-level components

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2017, Python Software Foundation.
The Python Software Foundation is a non-profit corporation.Please donate.
Last updated on Sep 19, 2017.Found a bug?
Created usingSphinx 1.2.

[8]ページ先頭

©2009-2025 Movatter.jp