7. 복합문(Compound statements)

복합문은 다른 문장들(의 그룹들)을 포함한다; 어떤 방법으로 그 다른 문장들의 실행에 영향을 주거나 제어한다. 간단하게 표현할 때, 전체 복합문을 한 줄로 쓸 수 있기는 하지만, 일반적으로 복합문은 여러 줄에 걸친다.

The if, while and for statements implement traditional control flow constructs. try specifies exception handlers and/or cleanup code for a group of statements. Function and class definitions are also syntactically compound statements.

Compound statements consist of one or more 〈clauses.〉 A clause consists of a header and a 〈suite.〉 The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines. Only the latter form of suite can contain nested compound statements; the following is illegal, mostly because it wouldn’t be clear to which if clause a following else clause would belong:

if test1: if test2: print x

Also note that the semicolon binds tighter than the colon in this context, so that in the following example, either all or none of the print statements are executed:

if x < y < z: print x; print y; print z

요약하면:

compound_stmt ::=  if_stmt
                   | while_stmt
                   | for_stmt
                   | try_stmt
                   | with_stmt
                   | funcdef
                   | classdef
                   | decorated
suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement     ::=  stmt_list NEWLINE | compound_stmt
stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]

Note that statements always end in a NEWLINE possibly followed by a DEDENT. Also note that optional continuation clauses always begin with a keyword that cannot start a statement, thus there are no ambiguities (the 〈dangling else〉 problem is solved in Python by requiring nested if statements to be indented).

명확함을 위해 다음에 오는 절들에서 나오는 문법 규칙들은 각 절을 별도의 줄에 놓도록 포매팅한다.

7.1. if

if 문은 조건부 실행에 사용된다:

if_stmt ::=  "if" expression ":" suite
             ( "elif" expression ":" suite )*
             ["else" ":" suite]

참이 되는 것을 발견할 때까지 표현식들의 값을 하나씩 차례대로 구해서 정확히 하나의 스위트를 선택한다 (참과 거짓의 정의는 논리 연산(Boolean operations) 섹션을 보라); 그런 다음 그 스위트를 실행한다 (그리고는 if 문의 다른 어떤 부분도 실행되거나 값이 구해지지 않는다). 모든 표현식들이 거짓이면 else 절의 스위트가 (있다면) 실행된다.

7.2. while

while 문은 표현식이 참인 동안 실행을 반복하는 데 사용된다:

while_stmt ::=  "while" expression ":" suite
                ["else" ":" suite]

이것은 표현식을 반복적으로 검사하고, 참이면, 첫 번째 스위트를 실행한다; 표현식이 거짓이면 (처음부터 거짓일 수도 있다) else 절의 스위트가 (있다면) 실행되고 루프를 종료한다.

첫 번째 스위트에서 실행되는 break 문은 else 절을 실행하지 않고 루프를 종료한다. 첫 번째 스위트에서 실행되는 continue 문은 스위트의 나머지 부분을 건너뛰고 표현식의 검사로 돌아간다.

7.3. for

for 문은 (문자열, 튜플, 리스트 같은) 시퀀스 나 다른 이터러블 객체의 요소들을 이터레이트하는데 사용된다:

for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order of ascending indices. Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed. When the items are exhausted (which is immediately when the sequence is empty), the suite in the else clause, if present, is executed, and the loop terminates.

A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.

The suite may assign to the variable(s) in the target list; this does not affect the next item assigned to it.

The target list is not deleted when the loop is finished, but if the sequence is empty, it will not have been assigned to at all by the loop. Hint: the built-in function range() returns a sequence of integers suitable to emulate the effect of Pascal’s for i := a to b do; e.g., range(3) returns the list [0, 1, 2].

참고

There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, e.g. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. 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 index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.,

for x in a[:]:
    if x < 0: a.remove(x)

7.4. try

try 문은 문장 그룹에 대한 예외 처리기나 정리(cleanup) 코드 또는 그 둘 모두를 지정하는 데 사용된다.

try_stmt  ::=  try1_stmt | try2_stmt
try1_stmt ::=  "try" ":" suite
               ("except" [expression [("as" | ",") identifier]] ":" suite)+
               ["else" ":" suite]
               ["finally" ":" suite]
try2_stmt ::=  "try" ":" suite
               "finally" ":" suite

버전 2.5에서 변경: In previous versions of Python, tryexceptfinally did not work. tryexcept had to be nested in tryfinally.

The except clause(s) specify one or more exception handlers. When no exception occurs in the try clause, no exception handler is executed. When an exception occurs in the try suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception. An expression-less except clause, if present, must be last; it matches any exception. For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is 《compatible》 with the exception. An object is compatible with an exception if it is the class or a base class of the exception object, or a tuple containing an item compatible with the exception.

except 절 중 어느 것도 예외와 매치되지 않으면, 예외 처리기 검색은 둘러싼 코드와 호출 스택에서 계속된다. 1

만약 except 절의 헤더에 있는 표현식의 값을 구할 때 예외가 발생하면, 원래의 처리기 검색은 취소되고 둘러싼 코드와 호출 스택에서 새 예외에 대해 검사가 시작된다 (try 문 전체가 예외를 일으킨 것으로 취급된다).

When a matching except clause is found, the exception is assigned to the target specified in that except clause, if present, and the except clause’s suite is executed. All except clauses must have an executable block. When the end of this block is reached, execution continues normally after the entire try statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the try clause of the inner handler, the outer handler will not handle the exception.)

Before an except clause’s suite is executed, details about the exception are assigned to three variables in the sys module: sys.exc_type receives the object identifying the exception; sys.exc_value receives the exception’s parameter; sys.exc_traceback receives a traceback object (see section 표준형 계층) identifying the point in the program where the exception occurred. These details are also available through the sys.exc_info() function, which returns a tuple (exc_type, exc_value, exc_traceback). Use of the corresponding variables is deprecated in favor of this function, since their use is unsafe in a threaded program. As of Python 1.5, the variables are restored to their previous values (before the call) when returning from a function that handled an exception.

The optional else clause is executed if the control flow leaves the try suite, no exception was raised, and no return, continue, or break statement was executed. Exceptions in the else clause are not handled by the preceding except clauses.

If finally is present, it specifies a 〈cleanup〉 handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. If the finally clause raises another exception or executes a return or break statement, the saved exception is discarded:

>>> def f():
...     try:
...         1/0
...     finally:
...         return 42
...
>>> f()
42

finally 절을 실행하는 동안 예외 정보는 프로그램에 제공되지 않는다.

tryfinally 문의 try 스위트에서 return, break, continue 문이 실행될 때, finally 절도 〈나가는 길에〉 실행된다. finally 절에서는 continue 문을 사용할 수 없다. (그 이유는 현재 구현에 있는 문제 때문이다 — 이 제약은 미래에 제거될 수 있다).

함수의 반환 값은 마지막에 실행된 return 문으로 결정된다. finally 절이 항상 실행되기 때문에, finally 절에서 실행되는 return 문이 항상 마지막에 실행되는 것이 된다:

>>> def foo():
...     try:
...         return 'try'
...     finally:
...         return 'finally'
...
>>> foo()
'finally'

예외에 관한 추가의 정보는 예외 섹션에서 찾을 수 있고, 예외를 일으키기 위해 raise 문을 사용하는 것에 관한 정보는 raise 문 섹션에서 찾을 수 있다.

7.5. with

버전 2.5에 추가.

with 문은 블록의 실행을 컨텍스트 관리자 (with 문 컨텍스트 관리자 섹션을 보라) 가 정의한 메서드들로 감싸는 데 사용된다. 이것은 흔한 tryexceptfinally 사용 패턴을 편리하게 재사용할 수 있도록 캡슐화할 수 있도록 한다.

with_stmt ::=  "with" with_item ("," with_item)* ":" suite
with_item ::=  expression ["as" target]

하나의 《item》 을 사용하는 with 문의 실행은 다음과 같이 진행된다:

  1. 컨텍스트 관리자를 얻기 위해 컨텍스트 표현식 (with_item 에 주어진 expression) 의 값을 구한다.

  2. 나중에 사용하기 위해 컨텍스트 관리자의 __exit__() 가 로드된다.

  3. 컨텍스트 관리자의 __enter__() 메서드를 호출한다.

  4. with 문에 타깃이 포함되었으면, 그것에 __enter__() 의 반환 값을 대입한다.

    참고

    with 문은 __enter__() 메서드가 에러 없이 돌아왔을 때, __exit__() 가 항상 호출됨을 보장한다. 그래서, 타깃에 대입하는 동안 에러가 발생하면, 스위트 안에서 에러가 발생한 것과 같이 취급된다. 아래의 6단계를 보라.

  5. 스위트가 실행된다.

  6. The context manager’s __exit__() method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to __exit__(). Otherwise, three None arguments are supplied.

    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 return value was true, the exception is suppressed, and execution continues with the statement following the with statement.

    스위트가 예외 이외의 이유로 종료되면, __exit__() 의 반환 값은 무시되고, 해당 종료의 종류에 맞는 위치에서 실행을 계속한다.

하나 보다 많은 항목을 주면, 컨텍스트 관리자는 with 문이 중첩된 것처럼 진행한다:

with A() as a, B() as b:
    suite

는 다음과 동등하다

with A() as a:
    with B() as b:
        suite

참고

In Python 2.5, the with statement is only allowed when the with_statement feature has been enabled. It is always enabled in Python 2.6.

버전 2.7에서 변경: 다중 컨텍스트 표현식의 지원

더 보기

PEP 343 - 《with》 문

파이썬 with 문의 규격, 배경, 예.

7.6. 함수 정의

함수 정의는 사용자 정의 함수 객체 (표준형 계층 섹션을 보라) 를 정의한다:

decorated      ::=  decorators (classdef | funcdef)
decorators     ::=  decorator+
decorator      ::=  "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
funcdef        ::=  "def" funcname "(" [parameter_list] ")" ":" suite
dotted_name    ::=  identifier ("." identifier)*
parameter_list ::=  (defparameter ",")*
                    (  "*" identifier ["," "**" identifier]
                    | "**" identifier
                    | defparameter [","] )
defparameter   ::=  parameter ["=" expression]
sublist        ::=  parameter ("," parameter)* [","]
parameter      ::=  identifier | "(" sublist ")"
funcname       ::=  identifier

함수 정의는 실행할 수 있는 문장이다. 실행하면 현재 지역 이름 공간의 함수 이름을 함수 객체 (함수의 실행 가능한 코드를 둘러싼 래퍼(wrapper)). 이 함수 객체는 현재의 이름 공간에 대한 참조를 포함하는데, 함수가 호출될 때 전역 이름 공간으로 사용된다.

함수 정의는 함수의 바디를 실행하지 않는다. 함수가 호출될 때 실행된다. 2

A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion. For example, the following code:

@f1(arg)
@f2
def func(): pass

is equivalent to:

def func(): pass
func = f1(arg)(f2(func))

When one or more top-level parameters have the form parameter = expression, the function is said to have 《default parameter values.》 For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter’s default value is substituted. If a parameter has a default value, all following parameters must also have a default value — this is a syntactic restriction that is not expressed by the grammar.

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same 《pre-computed》 value is used for each call. This is especially important to understand when a default parameter is a mutable object, 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 use None as the default, and explicitly test for it in the body of the function, e.g.:

def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append("property of the zoo")
    return penguin

Function call semantics are described in more detail in section 호출. A function call always assigns values to all parameters mentioned in the parameter list, either from position arguments, from keyword arguments, or from default values. If the form 《*identifier》 is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form 《**identifier》 is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.

It is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda expressions, described in section 람다(Lambdas). Note that the lambda expression is merely a shorthand for a simplified function definition; a function defined in a 《def》 statement can be passed around or assigned to another name just like a function defined by a lambda expression. The 《def》 form is actually more powerful since it allows the execution of multiple statements.

Programmer’s note: Functions are first-class objects. A 《def》 form executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. See section 이름과 연결(binding) for details.

7.7. 클래스 정의

클래스 정의는 클래스 객체(표준형 계층 섹션을 보라)를 정의한다:

classdef    ::=  "class" classname [inheritance] ":" suite
inheritance ::=  "(" [expression_list] ")"
classname   ::=  identifier

A class definition is an executable statement. It first evaluates the inheritance list, if present. Each item in the inheritance list should evaluate to a class object or class type which allows subclassing. The class’s suite is then executed in a new execution frame (see section 이름과 연결(binding)), using a newly created local namespace and the original global namespace. (Usually, the suite contains only function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. 3 A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary. The class name is bound to this class object in the original local namespace.

Programmer’s note: Variables defined in the class definition are class variables; they are shared by all instances. To create instance variables, they can be set in a method with self.name = value. Both class and instance variables are accessible through the notation 《self.name》, and an instance variable hides a class variable with the same name when accessed in this way. Class variables can be used as defaults for instance variables, but using mutable values there can lead to unexpected results. For new-style classes, descriptors can be used to create instance variables with different implementation details.

Class definitions, like function definitions, may be wrapped by one or more decorator expressions. The evaluation rules for the decorator expressions are the same as for functions. The result must be a class object, which is then bound to the class name.

각주

1

다른 예외를 일으키는 finally 절이 있지 않은 한 예외는 호출 스택으로 퍼진다. 그 새 예외는 예전의 것을 잃어버리게 만든다.

2

함수 바디의 첫 번째 문장으로 등장하는 문자열 리터럴은 함수의 __doc__ 어트리뷰트로 변환되어 함수의 독스트링 이 된다.

3

클래스 바디의 첫 번째 문장으로 등장하는 문자열 리터럴은 그 이름 공간의 __doc__ 항목으로 변환되어 클래스의 독스트링 이 된다.