8. 複合文 (compound statement)¶
複合文には、他の文 (のグループ) が入ります; 複合文は、中に入っている他の文の実行の制御に何らかのやり方で影響を及ぼします。一般的には、複合文は複数行にまたがって書かれますが、全部の文を一行に連ねた単純な書き方もあります。
if
、 while
、および for
文は、伝統的な制御フロー構成を実現します。 try
は例外処理および/または一連の文に対するクリーンアップコードを指定します。それに対して、 with
文はコードのかたまりの前後でコードの初期化と終了処理を実行できるようにします。関数とクラス定義もまた、構文的には複合文です。
複合文は、一つ以上の '節 (clause)' からなります。節は、ヘッダと 'スイート (suite)' からなります。一つの複合文を成す各節のヘッダは、全て同じインデントレベルに置かれます。各節のヘッダは一意に識別するキーワードで始まり、コロンで終わります。スイートは、節によって制御される文の集まりです。スイートは、ヘッダがある行のコロンの後にセミコロンで区切って置かれた一つ以上の単純文、または、ヘッダに続く行で一つ多くインデントされた文の集まりです。後者の形式のスイートに限り、さらに複合文をネストできます; 以下の文は、 else
節がどちらの if
節に属するかがはっきりしないなどの理由から不正になります:
if test1: if test2: print(x)
また、このコンテキスト中では、セミコロンによる結合はコロンより強いです。従って、以下の例では、 print()
の呼び出しはは全て実行されるか、全く実行されないかのどちらかです:
if x < y < z: print(x); print(y); print(z)
まとめると、以下のようになります:
compound_stmt ::=if_stmt
|while_stmt
|for_stmt
|try_stmt
|with_stmt
|match_stmt
|funcdef
|classdef
|async_with_stmt
|async_for_stmt
|async_funcdef
suite ::=stmt_list
NEWLINE | NEWLINE INDENTstatement
+ DEDENT statement ::=stmt_list
NEWLINE |compound_stmt
stmt_list ::=simple_stmt
(";"simple_stmt
)* [";"]
なお、文は常に NEWLINE
か、その後に DEDENT
が続いたもので終了します。また、オプションの継続節は必ず、文を開始できない予約語で始まるので、曖昧さは存在しません。 (Python では、 'ぶら下がり (dangling) else
' 問題は、ネストされた if
文をインデントさせることで解決されます)。
以下の節における文法規則の記述方式は、明確さのために、各節を別々の行に書くようにしています。
8.1. if
文¶
if
文は、条件分岐を実行するために使われます:
if_stmt ::= "if"assignment_expression
":"suite
("elif"assignment_expression
":"suite
)* ["else" ":"suite
]
if
文は、式を一つ一つ評価してゆき、真になるまで続けて、真になった節のスイートだけを選択します (真: true と偽: false の定義については、 ブール演算 (boolean operation) 節を参照してください); 次に、選択したスイートを実行します (そして、 if
文の他の部分は、実行や評価をされません)。全ての式が偽になった場合、 else
節があれば、そのスイートが実行されます。
8.2. while
文¶
while
文は、式の値が真である間、実行を繰り返すために使われます:
while_stmt ::= "while"assignment_expression
":"suite
["else" ":"suite
]
while
文は式を繰り返し真偽評価し、真であれば最初のスイートを実行します。式が偽であれば (最初から偽になっていることもありえます)、 else
節がある場合にはそれを実行し、ループを終了します。
最初のスイート内で break
文が実行されると、 else
節のスイートを実行することなくループを終了します。 continue
文が最初のスイート内で実行されると、スイート内にある残りの文の実行をスキップして、式の真偽評価に戻ります。
8.3. for
文¶
for
文は、シーケンス (文字列、タプルまたはリスト) や、その他の反復可能なオブジェクト (iterable object) 内の要素に渡って反復処理を行うために使われます:
for_stmt ::= "for"target_list
"in"starred_list
":"suite
["else" ":"suite
]
The starred_list
expression is evaluated once; it should yield an
iterable object. An iterator is created for that iterable.
The first item provided
by the iterator is then assigned to the target list using the standard
rules for assignments (see 代入文 (assignment statement)), and the suite is executed. This
repeats for each item provided by the iterator. When the iterator is exhausted,
the suite in the else
clause,
if present, is executed, and the loop terminates.
最初のスイートの中で break
文が実行されると、 else
節のスイートを実行することなくループを終了します。
continue
文が最初のスイート内で実行されると、スイート内にある残りの文の実行をスキップして、次の要素の処理に移るか、これ以上次の要素が無い場合は else
節の処理に移ります。
for ループはターゲットリスト内の変数への代入を行います。 これにより、for ループ内も含めて、それ以前の全ての代入は上書きされます:
for i in range(10):
print(i)
i = 5 # this will not affect the for-loop
# because i will be overwritten with the next
# index in the range
Names in the target list are not deleted when the loop is finished, but if the
sequence is empty, they will not have been assigned to at all by the loop. Hint:
the built-in type range()
represents immutable arithmetic sequences of integers.
For instance, iterating range(3)
successively yields 0, 1, and then 2.
バージョン 3.11 で変更: Starred elements are now allowed in the expression list.
8.4. try
文¶
The try
statement specifies exception handlers and/or cleanup code
for a group of statements:
try_stmt ::=try1_stmt
|try2_stmt
|try3_stmt
try1_stmt ::= "try" ":"suite
("except" [expression
["as"identifier
]] ":"suite
)+ ["else" ":"suite
] ["finally" ":"suite
] try2_stmt ::= "try" ":"suite
("except" "*"expression
["as"identifier
] ":"suite
)+ ["else" ":"suite
] ["finally" ":"suite
] try3_stmt ::= "try" ":"suite
"finally" ":"suite
例外に関するその他の情報は 例外 節にあります。また、 raise
文の使用による例外の生成に関する情報は、 raise 文 節にあります。
8.4.1. except
clause¶
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 the object is the class or a
non-virtual base class of the exception object,
or a tuple containing an item that is the class or a non-virtual base class
of the exception object.
If no except
clause matches the exception,
the search for an exception handler
continues in the surrounding code and on the invocation stack. 1
If the evaluation of an expression
in the header of an except
clause raises an exception,
the original search for a handler is canceled and a search starts for
the new exception in the surrounding code and on the call stack (it is treated
as if the entire try
statement raised the exception).
When a matching except
clause is found,
the exception is assigned to the target
specified after the as
keyword 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.)
When an exception has been assigned using as target
, it is cleared at the
end of the except
clause. This is as if
except E as N:
foo
が、以下のコードに翻訳されたかのようなものです:
except E as N:
try:
foo
finally:
del N
This means the exception must be assigned to a different name to be able to
refer to it after the except
clause.
Exceptions are cleared because with the
traceback 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 are
stored in the sys
module and can be accessed via sys.exc_info()
.
sys.exc_info()
returns a 3-tuple consisting of the exception class, the
exception instance and a traceback object (see section 標準型の階層) identifying
the point in the program where the exception occurred. The details about the
exception accessed via sys.exc_info()
are restored to their previous values
when leaving an exception handler:
>>> print(sys.exc_info())
(None, None, None)
>>> try:
... raise TypeError
... except:
... print(sys.exc_info())
... try:
... raise ValueError
... except:
... print(sys.exc_info())
... print(sys.exc_info())
...
(<class 'TypeError'>, TypeError(), <traceback object at 0x10efad080>)
(<class 'ValueError'>, ValueError(), <traceback object at 0x10efad040>)
(<class 'TypeError'>, TypeError(), <traceback object at 0x10efad080>)
>>> print(sys.exc_info())
(None, None, None)
8.4.2. except*
clause¶
The except*
clause(s) are used for handling
ExceptionGroup
s. The exception type for matching is interpreted as in
the case of except
, but in the case of exception groups we can have
partial matches when the type matches some of the exceptions in the group.
This means that multiple except*
clauses can execute,
each handling part of the exception group.
Each clause executes at most once and handles an exception group
of all matching exceptions. Each exception in the group is handled by at most
one except*
clause, the first that matches it.
>>> try:
... raise ExceptionGroup("eg",
... [ValueError(1), TypeError(2), OSError(3), OSError(4)])
... except* TypeError as e:
... print(f'caught {type(e)} with nested {e.exceptions}')
... except* OSError as e:
... print(f'caught {type(e)} with nested {e.exceptions}')
...
caught <class 'ExceptionGroup'> with nested (TypeError(2),)
caught <class 'ExceptionGroup'> with nested (OSError(3), OSError(4))
+ Exception Group Traceback (most recent call last):
| File "<stdin>", line 2, in <module>
| ExceptionGroup: eg
+-+---------------- 1 ----------------
| ValueError: 1
+------------------------------------
Any remaining exceptions that were not handled by any except*
clause are re-raised at the end, combined into an exception group along with
all exceptions that were raised from within except*
clauses.
If the raised exception is not an exception group and its type matches
one of the except*
clauses, it is caught and wrapped by an
exception group with an empty message string.
>>> try:
... raise BlockingIOError
... except* BlockingIOError as e:
... print(repr(e))
...
ExceptionGroup('', (BlockingIOError()))
An except*
clause must have a matching type,
and this type cannot be a subclass of BaseExceptionGroup
.
It is not possible to mix except
and except*
in the same try
.
break
, continue
and return
cannot appear in an except*
clause.
8.4.3. else
clause¶
オプションの else
節は、コントロールフローが try
スイートを抜け、例外が送出されず、 return
文、 continue
文、 break
文のいずれもが実行されなかった場合に実行されます。
else
節で起きた例外は、手前にある except
節では処理されません。
8.4.4. finally
clause¶
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, the saved exception is set as the context of the new exception.
If the finally
clause executes a return
, break
or continue
statement, the saved exception is discarded:
>>> def f():
... try:
... 1/0
... finally:
... return 42
...
>>> f()
42
The exception information is not available to the program during execution of
the finally
clause.
When a return
, break
or continue
statement is
executed in the try
suite of a try
...finally
statement, the finally
clause is also executed 'on the way out.'
The return value of a function is determined by the last return
statement executed. Since the finally
clause always executes, a
return
statement executed in the finally
clause will
always be the last one executed:
>>> def foo():
... try:
... return 'try'
... finally:
... return 'finally'
...
>>> foo()
'finally'
バージョン 3.8 で変更: Prior to Python 3.8, a continue
statement was illegal in the
finally
clause due to a problem with the implementation.
8.5. with
文¶
with
文は、ブロックの実行を、コンテキストマネージャによって定義されたメソッドでラップするために使われます (with文とコンテキストマネージャ セクションを参照してください)。これにより、よくある try
...except
...finally
利用パターンをカプセル化して便利に再利用することができます。
with_stmt ::= "with" ( "("with_stmt_contents
","? ")" |with_stmt_contents
) ":"suite
with_stmt_contents ::=with_item
(","with_item
)* with_item ::=expression
["as"target
]
一つの "要素" を持つ with
文の実行は以下のように進行します:
The context expression (the expression given in the
with_item
) is evaluated to obtain a context manager.コンテキストマネージャの
__enter__()
メソッドが、後で使うためにロードされます。コンテキストマネージャの
__exit__()
メソッドが、後で使うためにロードされます。コンテキストマネージャの
__enter__()
メソッドが呼ばれます。with
文にターゲットが含まれていたら、それに__enter__()
からの戻り値が代入されます。注釈
The
with
statement guarantees that if the__enter__()
method returns without an error, then__exit__()
will always be called. 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 would be. See step 7 below.スイートが実行されます。
コンテキストマネージャの
__exit__()
メソッドが呼ばれます。スイートが例外によって終了されたのなら、その例外の型、値、トレースバックが__exit__()
に引数として渡されます。そうでなければ、 3 つのNone
引数が与えられます。スイートが例外により終了され、
__exit__()
メソッドからの戻り値が偽(false)ならば、例外が再送出されます。この戻り値が真(true)ならば例外は抑制され、実行はwith
文の次の文から続きます。もしそのスイートが例外でない何らかの理由で終了した場合、その
__exit__()
からの戻り値は無視されて、実行は発生した終了の種類に応じた通常の位置から継続します。
以下のコード:
with EXPRESSION as TARGET:
SUITE
これは次と等価です:
manager = (EXPRESSION)
enter = type(manager).__enter__
exit = type(manager).__exit__
value = enter(manager)
hit_except = False
try:
TARGET = value
SUITE
except:
hit_except = True
if not exit(manager, *sys.exc_info()):
raise
finally:
if not hit_except:
exit(manager, None, None, None)
複数の要素があるとき、コンテキストマネージャは複数の with
文がネストされたかのように進行します:
with A() as a, B() as b:
SUITE
これは次と等価です:
with A() as a:
with B() as b:
SUITE
You can also write multi-item context managers in multiple lines if the items are surrounded by parentheses. For example:
with (
A() as a,
B() as b,
):
SUITE
バージョン 3.1 で変更: 複数のコンテキスト式をサポートしました。
バージョン 3.10 で変更: Support for using grouping parentheses to break the statement in multiple lines.
8.6. The match
statement¶
バージョン 3.10 で追加.
The match statement is used for pattern matching. Syntax:
match_stmt ::= 'match'subject_expr
":" NEWLINE INDENTcase_block
+ DEDENT subject_expr ::=star_named_expression
","star_named_expressions
? |named_expression
case_block ::= 'case'patterns
[guard
] ":"block
注釈
This section uses single quotes to denote soft keywords.
Pattern matching takes a pattern as input (following case
) and a subject
value (following match
). The pattern (which may contain subpatterns) is
matched against the subject value. The outcomes are:
A match success or failure (also termed a pattern success or failure).
Possible binding of matched values to a name. The prerequisites for this are further discussed below.
The match
and case
keywords are soft keywords.
参考
8.6.1. 概要¶
Here's an overview of the logical flow of a match statement:
The subject expression
subject_expr
is evaluated and a resulting subject value obtained. If the subject expression contains a comma, a tuple is constructed using the standard rules.Each pattern in a
case_block
is attempted to match with the subject value. The specific rules for success or failure are described below. The match attempt can also bind some or all of the standalone names within the pattern. The precise pattern binding rules vary per pattern type and are specified below. Name bindings made during a successful pattern match outlive the executed block and can be used after the match statement.注釈
During failed pattern matches, some subpatterns may succeed. Do not rely on bindings being made for a failed match. Conversely, do not rely on variables remaining unchanged after a failed match. The exact behavior is dependent on implementation and may vary. This is an intentional decision made to allow different implementations to add optimizations.
If the pattern succeeds, the corresponding guard (if present) is evaluated. In this case all name bindings are guaranteed to have happened.
If the guard evaluates as true or is missing, the
block
insidecase_block
is executed.Otherwise, the next
case_block
is attempted as described above.If there are no further case blocks, the match statement is completed.
注釈
Users should generally never rely on a pattern being evaluated. Depending on implementation, the interpreter may cache values or use other optimizations which skip repeated evaluations.
A sample match statement:
>>> flag = False
>>> match (100, 200):
... case (100, 300): # Mismatch: 200 != 300
... print('Case 1')
... case (100, 200) if flag: # Successful match, but guard fails
... print('Case 2')
... case (100, y): # Matches and binds y to 200
... print(f'Case 3, y: {y}')
... case _: # Pattern not attempted
... print('Case 4, I match anything!')
...
Case 3, y: 200
In this case, if flag
is a guard. Read more about that in the next section.
8.6.2. Guards¶
guard ::= "if" named_expression
A guard
(which is part of the case
) must succeed for code inside
the case
block to execute. It takes the form: if
followed by an
expression.
The logical flow of a case
block with a guard
follows:
Check that the pattern in the
case
block succeeded. If the pattern failed, theguard
is not evaluated and the nextcase
block is checked.If the pattern succeeded, evaluate the
guard
.If the
guard
condition evaluates as true, the case block is selected.If the
guard
condition evaluates as false, the case block is not selected.If the
guard
raises an exception during evaluation, the exception bubbles up.
Guards are allowed to have side effects as they are expressions. Guard evaluation must proceed from the first to the last case block, one at a time, skipping case blocks whose pattern(s) don't all succeed. (I.e., guard evaluation must happen in order.) Guard evaluation must stop once a case block is selected.
8.6.3. Irrefutable Case Blocks¶
An irrefutable case block is a match-all case block. A match statement may have at most one irrefutable case block, and it must be last.
A case block is considered irrefutable if it has no guard and its pattern is irrefutable. A pattern is considered irrefutable if we can prove from its syntax alone that it will always succeed. Only the following patterns are irrefutable:
AS Patterns whose left-hand side is irrefutable
OR Patterns containing at least one irrefutable pattern
parenthesized irrefutable patterns
8.6.4. Patterns¶
注釈
This section uses grammar notations beyond standard EBNF:
the notation
SEP.RULE+
is shorthand forRULE (SEP RULE)*
the notation
!RULE
is shorthand for a negative lookahead assertion
The top-level syntax for patterns
is:
patterns ::=open_sequence_pattern
|pattern
pattern ::=as_pattern
|or_pattern
closed_pattern ::= |literal_pattern
|capture_pattern
|wildcard_pattern
|value_pattern
|group_pattern
|sequence_pattern
|mapping_pattern
|class_pattern
The descriptions below will include a description "in simple terms" of what a pattern does for illustration purposes (credits to Raymond Hettinger for a document that inspired most of the descriptions). Note that these descriptions are purely for illustration purposes and may not reflect the underlying implementation. Furthermore, they do not cover all valid forms.
8.6.4.1. OR Patterns¶
An OR pattern is two or more patterns separated by vertical
bars |
. Syntax:
or_pattern ::= "|".closed_pattern
+
Only the final subpattern may be irrefutable, and each subpattern must bind the same set of names to avoid ambiguity.
An OR pattern matches each of its subpatterns in turn to the subject value, until one succeeds. The OR pattern is then considered successful. Otherwise, if none of the subpatterns succeed, the OR pattern fails.
In simple terms, P1 | P2 | ...
will try to match P1
, if it fails it will try to
match P2
, succeeding immediately if any succeeds, failing otherwise.
8.6.4.2. AS Patterns¶
An AS pattern matches an OR pattern on the left of the as
keyword against a subject. Syntax:
as_pattern ::=or_pattern
"as"capture_pattern
If the OR pattern fails, the AS pattern fails. Otherwise, the AS pattern binds
the subject to the name on the right of the as keyword and succeeds.
capture_pattern
cannot be a a _
.
In simple terms P as NAME
will match with P
, and on success it will
set NAME = <subject>
.
8.6.4.3. Literal Patterns¶
A literal pattern corresponds to most literals in Python. Syntax:
literal_pattern ::=signed_number
|signed_number
"+" NUMBER |signed_number
"-" NUMBER |strings
| "None" | "True" | "False" |signed_number
: NUMBER | "-" NUMBER
The rule strings
and the token NUMBER
are defined in the
standard Python grammar. Triple-quoted strings are
supported. Raw strings and byte strings are supported. フォーマット済み文字列リテラル are
not supported.
The forms signed_number '+' NUMBER
and signed_number '-' NUMBER
are
for expressing complex numbers; they require a real number
on the left and an imaginary number on the right. E.g. 3 + 4j
.
In simple terms, LITERAL
will succeed only if <subject> == LITERAL
. For
the singletons None
, True
and False
, the is
operator is used.
8.6.4.4. Capture Patterns¶
A capture pattern binds the subject value to a name. Syntax:
capture_pattern ::= !'_' NAME
A single underscore _
is not a capture pattern (this is what !'_'
expresses). It is instead treated as a
wildcard_pattern
.
In a given pattern, a given name can only be bound once. E.g.
case x, x: ...
is invalid while case [x] | x: ...
is allowed.
Capture patterns always succeed. The binding follows scoping rules
established by the assignment expression operator in PEP 572; the
name becomes a local variable in the closest containing function scope unless
there's an applicable global
or nonlocal
statement.
In simple terms NAME
will always succeed and it will set NAME = <subject>
.
8.6.4.5. Wildcard Patterns¶
A wildcard pattern always succeeds (matches anything) and binds no name. Syntax:
wildcard_pattern ::= '_'
_
is a soft keyword within any pattern,
but only within patterns. It is an identifier, as usual, even within
match
subject expressions, guard
s, and case
blocks.
In simple terms, _
will always succeed.
8.6.4.6. Value Patterns¶
A value pattern represents a named value in Python. Syntax:
value_pattern ::=attr
attr ::=name_or_attr
"." NAME name_or_attr ::=attr
| NAME
The dotted name in the pattern is looked up using standard Python
name resolution rules. The pattern succeeds if the
value found compares equal to the subject value (using the ==
equality
operator).
In simple terms NAME1.NAME2
will succeed only if <subject> == NAME1.NAME2
注釈
If the same value occurs multiple times in the same match statement, the interpreter may cache the first value found and reuse it rather than repeat the same lookup. This cache is strictly tied to a given execution of a given match statement.
8.6.4.7. Group Patterns¶
A group pattern allows users to add parentheses around patterns to emphasize the intended grouping. Otherwise, it has no additional syntax. Syntax:
group_pattern ::= "(" pattern
")"
In simple terms (P)
has the same effect as P
.
8.6.4.8. Sequence Patterns¶
A sequence pattern contains several subpatterns to be matched against sequence elements. The syntax is similar to the unpacking of a list or tuple.
sequence_pattern ::= "[" [maybe_sequence_pattern
] "]" | "(" [open_sequence_pattern
] ")" open_sequence_pattern ::=maybe_star_pattern
"," [maybe_sequence_pattern
] maybe_sequence_pattern ::= ",".maybe_star_pattern
+ ","? maybe_star_pattern ::=star_pattern
|pattern
star_pattern ::= "*" (capture_pattern
|wildcard_pattern
)
There is no difference if parentheses or square brackets
are used for sequence patterns (i.e. (...)
vs [...]
).
注釈
A single pattern enclosed in parentheses without a trailing comma
(e.g. (3 | 4)
) is a group pattern.
While a single pattern enclosed in square brackets (e.g. [3 | 4]
) is
still a sequence pattern.
At most one star subpattern may be in a sequence pattern. The star subpattern may occur in any position. If no star subpattern is present, the sequence pattern is a fixed-length sequence pattern; otherwise it is a variable-length sequence pattern.
The following is the logical flow for matching a sequence pattern against a subject value:
If the subject value is not a sequence 2, the sequence pattern fails.
If the subject value is an instance of
str
,bytes
orbytearray
the sequence pattern fails.The subsequent steps depend on whether the sequence pattern is fixed or variable-length.
If the sequence pattern is fixed-length:
If the length of the subject sequence is not equal to the number of subpatterns, the sequence pattern fails
Subpatterns in the sequence pattern are matched to their corresponding items in the subject sequence from left to right. Matching stops as soon as a subpattern fails. If all subpatterns succeed in matching their corresponding item, the sequence pattern succeeds.
Otherwise, if the sequence pattern is variable-length:
If the length of the subject sequence is less than the number of non-star subpatterns, the sequence pattern fails.
The leading non-star subpatterns are matched to their corresponding items as for fixed-length sequences.
If the previous step succeeds, the star subpattern matches a list formed of the remaining subject items, excluding the remaining items corresponding to non-star subpatterns following the star subpattern.
Remaining non-star subpatterns are matched to their corresponding subject items, as for a fixed-length sequence.
注釈
The length of the subject sequence is obtained via
len()
(i.e. via the__len__()
protocol). This length may be cached by the interpreter in a similar manner as value patterns.
In simple terms [P1, P2, P3,
... , P<N>]
matches only if all the following
happens:
check
<subject>
is a sequencelen(subject) == <N>
P1
matches<subject>[0]
(note that this match can also bind names)P2
matches<subject>[1]
(note that this match can also bind names)... and so on for the corresponding pattern/element.
8.6.4.9. Mapping Patterns¶
A mapping pattern contains one or more key-value patterns. The syntax is similar to the construction of a dictionary. Syntax:
mapping_pattern ::= "{" [items_pattern
] "}" items_pattern ::= ",".key_value_pattern
+ ","? key_value_pattern ::= (literal_pattern
|value_pattern
) ":"pattern
|double_star_pattern
double_star_pattern ::= "**"capture_pattern
At most one double star pattern may be in a mapping pattern. The double star pattern must be the last subpattern in the mapping pattern.
Duplicate keys in mapping patterns are disallowed. Duplicate literal keys will
raise a SyntaxError
. Two keys that otherwise have the same value will
raise a ValueError
at runtime.
The following is the logical flow for matching a mapping pattern against a subject value:
If the subject value is not a mapping 3,the mapping pattern fails.
If every key given in the mapping pattern is present in the subject mapping, and the pattern for each key matches the corresponding item of the subject mapping, the mapping pattern succeeds.
If duplicate keys are detected in the mapping pattern, the pattern is considered invalid. A
SyntaxError
is raised for duplicate literal values; or aValueError
for named keys of the same value.
注釈
Key-value pairs are matched using the two-argument form of the mapping
subject's get()
method. Matched key-value pairs must already be present
in the mapping, and not created on-the-fly via __missing__()
or
__getitem__()
.
In simple terms {KEY1: P1, KEY2: P2, ... }
matches only if all the following
happens:
check
<subject>
is a mappingKEY1 in <subject>
P1
matches<subject>[KEY1]
... and so on for the corresponding KEY/pattern pair.
8.6.4.10. Class Patterns¶
A class pattern represents a class and its positional and keyword arguments (if any). Syntax:
class_pattern ::=name_or_attr
"(" [pattern_arguments
","?] ")" pattern_arguments ::=positional_patterns
[","keyword_patterns
] |keyword_patterns
positional_patterns ::= ",".pattern
+ keyword_patterns ::= ",".keyword_pattern
+ keyword_pattern ::= NAME "="pattern
The same keyword should not be repeated in class patterns.
The following is the logical flow for matching a class pattern against a subject value:
If
name_or_attr
is not an instance of the builtintype
, raiseTypeError
.If the subject value is not an instance of
name_or_attr
(tested viaisinstance()
), the class pattern fails.If no pattern arguments are present, the pattern succeeds. Otherwise, the subsequent steps depend on whether keyword or positional argument patterns are present.
For a number of built-in types (specified below), a single positional subpattern is accepted which will match the entire subject; for these types keyword patterns also work as for other types.
If only keyword patterns are present, they are processed as follows, one by one:
I. The keyword is looked up as an attribute on the subject.
If this raises an exception other than
AttributeError
, the exception bubbles up.If this raises
AttributeError
, the class pattern has failed.Else, the subpattern associated with the keyword pattern is matched against the subject's attribute value. If this fails, the class pattern fails; if this succeeds, the match proceeds to the next keyword.
II. If all keyword patterns succeed, the class pattern succeeds.
If any positional patterns are present, they are converted to keyword patterns using the
__match_args__
attribute on the classname_or_attr
before matching:I. The equivalent of
getattr(cls, "__match_args__", ())
is called.If this raises an exception, the exception bubbles up.
If the returned value is not a tuple, the conversion fails and
TypeError
is raised.If there are more positional patterns than
len(cls.__match_args__)
,TypeError
is raised.Otherwise, positional pattern
i
is converted to a keyword pattern using__match_args__[i]
as the keyword.__match_args__[i]
must be a string; if notTypeError
is raised.If there are duplicate keywords,
TypeError
is raised.
- II. Once all positional patterns have been converted to keyword patterns,
the match proceeds as if there were only keyword patterns.
For the following built-in types the handling of positional subpatterns is different:
These classes accept a single positional argument, and the pattern there is matched against the whole object rather than an attribute. For example
int(0|1)
matches the value0
, but not the value0.0
.
In simple terms CLS(P1, attr=P2)
matches only if the following happens:
isinstance(<subject>, CLS)
convert
P1
to a keyword pattern usingCLS.__match_args__
- For each keyword argument
attr=P2
: hasattr(<subject>, "attr")
P2
matches<subject>.attr
- For each keyword argument
... and so on for the corresponding keyword argument/pattern pair.
8.7. 関数定義¶
関数定義は、ユーザ定義関数オブジェクトを定義します (標準型の階層 節参照):
funcdef ::= [decorators
] "def"funcname
"(" [parameter_list
] ")" ["->"expression
] ":"suite
decorators ::=decorator
+ decorator ::= "@"assignment_expression
NEWLINE parameter_list ::=defparameter
(","defparameter
)* "," "/" ["," [parameter_list_no_posonly
]] |parameter_list_no_posonly
parameter_list_no_posonly ::=defparameter
(","defparameter
)* ["," [parameter_list_starargs
]] |parameter_list_starargs
parameter_list_starargs ::= "*" [parameter
] (","defparameter
)* ["," ["**"parameter
[","]]] | "**"parameter
[","] parameter ::=identifier
[":"expression
] defparameter ::=parameter
["="expression
] funcname ::=identifier
関数定義は実行可能な文です。関数定義を実行すると、現在のローカルな名前空間内で関数名を関数オブジェクト (関数の実行可能コードをくるむラッパー) に束縛します。この関数オブジェクトには、関数が呼び出された際に使われるグローバルな名前空間として、現在のグローバルな名前空間への参照が入っています。
関数定義は関数本体を実行しません; 関数本体は関数が呼び出された時にのみ実行されます。 4
関数定義は一つ以上の デコレータ 式でラップできます。デコレータ式は関数を定義するとき、関数定義の入っているスコープで評価されます。その結果は、関数オブジェクトを唯一の引数にとる呼び出し可能オブジェクトでなければなりません。関数オブジェクトの代わりに、返された値が関数名に束縛されます。複数のデコレータはネストして適用されます。例えば、以下のようなコード:
@f1(arg)
@f2
def func(): pass
は、だいたい次と等価です
def func(): pass
func = f1(arg)(f2(func))
ただし、前者のコードでは元々の関数を func
という名前へ一時的に束縛することはない、というところを除きます。
バージョン 3.9 で変更: Functions may be decorated with any valid
assignment_expression
. Previously, the grammar was
much more restrictive; see PEP 614 for details.
1 つ以上の 仮引数 が parameter =
expression の形を取っているとき、関数は "デフォルト引数値" を持つと言います。デフォルト値を持つ仮引数では、呼び出し時にそれに対応する 実引数 は省略でき、その場合は仮引数のデフォルト値が使われます。ある引数がデフォルト値を持っている場合、それ以降 "*
" が出てくるまでの引数は全てデフォルト値を持っていなければなりません -- これは文法定義では表現されていない構文的制限です。
Default parameter values are evaluated from left to right 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 value 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 parameter 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 呼び出し (call). A
function call always assigns values to all parameters mentioned in the parameter
list, either from positional 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
ordered mapping receiving any excess keyword arguments, defaulting to a
new empty mapping of the same type. Parameters after "*
" or
"*identifier
" are keyword-only parameters and may only be passed
by keyword arguments. Parameters before "/
" are positional-only parameters
and may only be passed by positional arguments.
バージョン 3.8 で変更: The /
function parameter syntax may be used to indicate positional-only
parameters. See PEP 570 for details.
引数には、引数名に続けて ": expression
" 形式の アノテーション を付けられます。
*identifier
や **identifier
の形式でも、すべての引数にはアノテーションをつけられます。
関数には、引数リストの後に "-> expression
" 形式の "return" アノテーションをつけられます。これらのアノテーションは、任意の有効な Python の式が使えます。
アノテーションがあっても、関数の意味論は変わりません。
アノテーションの値は、関数オブジェクトの __annotations__
属性の、引数名をキーとする値として得られます。
__future__
の annotations
インポートを使った場合は、アノテーションは実行時には文字列として保持され、これにより評価の遅延が可能になっています。
そうでない場合は、アノテーションは関数定義が実行されたときに評価されます。
このケースでは、アノテーションはソースコードに現れたのとは違う順序で評価されることがあります。
式を即時に使用するために、無名関数 (名前に束縛されていない関数) を作成することもできます。
これは ラムダ (lambda) の節で解説されているラムダ式を使います。
ラムダ式は簡略化された関数定義の簡略表現に過ぎないことに注意してください; "def
" 文で定義された関数もラムダ式で作成された関数のように、引数として渡せたり、他の名前に割り当てることができます。
複数の式とアノテーションが実行できるので、 "def
" 形式の方がより強力です。
プログラマへのメモ: 関数は第一級オブジェクトです。関数定義内で実行された "def
" 文は、返り値や引数として渡せるローカル関数を定義します。ネストした関数内で使われる自由変数は、 def を含んでいる関数のローカル変数にアクセスできます。詳細は 名前づけと束縛 (naming and binding) 節を参照してください。
8.8. クラス定義¶
クラス定義は、クラスオブジェクトを定義します (標準型の階層 節参照):
classdef ::= [decorators
] "class"classname
[inheritance
] ":"suite
inheritance ::= "(" [argument_list
] ")" classname ::=identifier
クラス定義は実行可能な文です。継承リストは通常、基底クラスリストを与えます (より高度な使い方は、 メタクラス を参照してください)。ですから、リストのそれぞれの要素の評価はサブクラス化しても良いクラスであるべきです。継承リストのないクラスは、デフォルトで、基底クラス object
を継承するので:
class Foo:
pass
は、以下と同等です
class Foo(object):
pass
次にクラスのスイートが、新たな実行フレーム (名前づけと束縛 (naming and binding) を参照してください) 内で、新たに作られたローカル名前空間と元々のグローバル名前空間を使って実行されます (通常、このスイートには主に関数定義が含まれます)。クラスのスイートが実行し終えると、実行フレームは破棄されますが、ローカルな名前空間は保存されます。5 次に、継承リストを基底クラスに、保存されたローカル名前空間を属性値辞書に、それぞれ使ってクラスオブジェクトが生成されます。最後に、もとのローカル名前空間において、クラス名がこのクラスオブジェクトに束縛されます。
クラス本体で属性が定義された順序は新しいクラスの __dict__
に保持されます。
この性質が期待できるのは、クラスが作られた直後かつ定義構文を使って定義されたクラスであるときのみです。
クラス作成は、 メタクラス を利用して大幅にカスタマイズできます。
関数をデコレートするのと同じように、クラスもデコレートすることが出来ます、
@f1(arg)
@f2
class Foo: pass
は、だいたい次と等価です
class Foo: pass
Foo = f1(arg)(f2(Foo))
デコレータ式の評価規則は関数デコレータと同じです。結果はクラス名に束縛されます。
バージョン 3.9 で変更: Classes may be decorated with any valid
assignment_expression
. Previously, the grammar was
much more restrictive; see PEP 614 for details.
プログラマのための注釈: クラス定義内で定義された変数はクラス属性であり、全てのインスタンス間で共有されます。インスタンス属性は、メソッドの中で self.name = value
とすることで設定できます。クラス属性もインスタンス属性も "self.name
" 表記でアクセスでき、この表記でアクセスしたとき、インスタンス属性は同名のクラス属性を隠蔽します。クラス属性は、インスタンス属性のデフォルト値として使えますが、そこにミュータブルな値を使うと予期せぬ結果につながります。 記述子 を使うと、詳細な実装が異なるインスタンス変数を作成できます。
8.9. コルーチン¶
バージョン 3.5 で追加.
8.9.1. コルーチン関数定義¶
async_funcdef ::= [decorators
] "async" "def"funcname
"(" [parameter_list
] ")" ["->"expression
] ":"suite
Execution of Python coroutines can be suspended and resumed at many points
(see coroutine). await
expressions, async for
and
async with
can only be used in the body of a coroutine function.
Functions defined with async def
syntax are always coroutine functions,
even if they do not contain await
or async
keywords.
コルーチン関数の本体の中で yield from
式を使用すると SyntaxError
になります。
コルーチン関数の例:
async def func(param1, param2):
do_stuff()
await some_coroutine()
バージョン 3.7 で変更: await
and async
are now keywords; previously they were only
treated as such inside the body of a coroutine function.
8.9.2. async for
文¶
async_for_stmt ::= "async" for_stmt
An asynchronous iterable provides an __aiter__
method that directly
returns an asynchronous iterator, which can call asynchronous code in
its __anext__
method.
The async for
statement allows convenient iteration over asynchronous
iterables.
以下のコード:
async for TARGET in ITER:
SUITE
else:
SUITE2
は意味論的に以下と等価です:
iter = (ITER)
iter = type(iter).__aiter__(iter)
running = True
while running:
try:
TARGET = await type(iter).__anext__(iter)
except StopAsyncIteration:
running = False
else:
SUITE
else:
SUITE2
See also __aiter__()
and __anext__()
for details.
コルーチン関数の本体の外で async for
文を使用すると SyntaxError
になります。
8.9.3. async with
文¶
async_with_stmt ::= "async" with_stmt
asynchronous context manager は、 enter メソッドと exit メソッド内部で実行を一時停止できる context manager です。
以下のコード:
async with EXPRESSION as TARGET:
SUITE
これは次と等価です:
manager = (EXPRESSION)
aenter = type(manager).__aenter__
aexit = type(manager).__aexit__
value = await aenter(manager)
hit_except = False
try:
TARGET = value
SUITE
except:
hit_except = True
if not await aexit(manager, *sys.exc_info()):
raise
finally:
if not hit_except:
await aexit(manager, None, None, None)
See also __aenter__()
and __aexit__()
for details.
コルーチン関数の本体の外で async with
文を使用すると SyntaxError
になります。
参考
- PEP 492 - async 構文および await 構文付きのコルーチン
コルーチンを Python のまともな独り立ちした概念にし、サポートする構文を追加した提案。
脚注
- 1
例外は、別の例外を送出するような
finally
節が無い場合にのみ呼び出しスタックへ伝わります。新しい例外によって、古い例外は失われます。- 2
In pattern matching, a sequence is defined as one of the following:
a class that inherits from
collections.abc.Sequence
a Python class that has been registered as
collections.abc.Sequence
a builtin class that has its (CPython)
Py_TPFLAGS_SEQUENCE
bit seta class that inherits from any of the above
The following standard library classes are sequences:
注釈
Subject values of type
str
,bytes
, andbytearray
do not match sequence patterns.- 3
In pattern matching, a mapping is defined as one of the following:
a class that inherits from
collections.abc.Mapping
a Python class that has been registered as
collections.abc.Mapping
a builtin class that has its (CPython)
Py_TPFLAGS_MAPPING
bit seta class that inherits from any of the above
The standard library classes
dict
andtypes.MappingProxyType
are mappings.- 4
関数の本体の最初の文として現われる文字列リテラルは、その関数の
__doc__
属性に変換され、その関数の ドキュメンテーション文字列 になります。- 5
クラスの本体の最初の文として現われる文字列リテラルは、その名前空間の
__doc__
要素となり、そのクラスの ドキュメンテーション文字列 になります。