6.式 (expression)

この章では、Python の式における個々の要素の意味について解説します。

表記法に関する注意: この章と以降の章での拡張BNF (extended BNF) 表記は、字句解析規則ではなく、構文規則を記述するために用いられています。ある構文規則 (のある表現方法) が、以下の形式

name ::=  othername

で記述されていて、この構文特有の意味付け (semantics) が記述されていない場合、name の形式をとる構文の意味付けはothername の意味付けと同じになります。

6.1.算術変換 (arithmetic conversion)

When a description of an arithmetic operator below uses the phrase "the numericarguments are converted to a common type", this means that the operatorimplementation for built-in types works as follows:

  • If either argument is a complex number, the other is converted to complex;

  • otherwise, if either argument is a floating point number, the other isconverted to floating point;

  • それ以外場合は、両方の引数は整数でなければならず、変換の必要はありません。

特定の演算子 ('%' 演算子の左引数としての文字列) には、さらに別の規則が適用されます。拡張は、それ自身の型変換のふるまいを定義していなければなりません。

6.2.アトム、原子的要素 (atom)

atom は、式の一番基本的な要素です。もっとも単純な atom は、識別子またはリテラルです。丸括弧、角括弧、または波括弧で囲われた形式 (form) もまた、構文上アトムに分類されます。atom の構文は以下のようになります:

atom ::=identifier |literal |enclosureenclosure ::=parenth_form |list_display |dict_display |set_display               |generator_expression |yield_atom

6.2.1.識別子 (identifier、または名前 (name))

アトムの形になっている識別子 (identifier) は名前 (name) です。字句定義については識別子 (identifier) およびキーワード (keyword) 節を、名前付けや束縛については名前づけと束縛 (naming and binding) 節を参照してください。

名前があるオブジェクトに束縛されている場合、名前 atom を評価するとそのオブジェクトになります。名前が束縛されていない場合、 atom を評価しようとするとNameError 例外を送出します。

Private name mangling: When an identifier that textually occurs in a classdefinition begins with two or more underscore characters and does not end in twoor more underscores, it is considered aprivate name of that class.Private names are transformed to a longer form before code is generated forthem. The transformation inserts the class name, with leading underscoresremoved and a single underscore inserted, in front of the name. For example,the identifier__spam occurring in a class namedHam will be transformedto_Ham__spam. This transformation is independent of the syntacticalcontext in which the identifier is used. If the transformed name is extremelylong (longer than 255 characters), implementation defined truncation may happen.If the class name consists only of underscores, no transformation is done.

6.2.2.リテラル

Python では、文字列やバイト列リテラルと、様々な数値リテラルをサポートしています:

literal ::=stringliteral |bytesliteral             |integer |floatnumber |imagnumber

Evaluation of a literal yields an object of the given type (string, bytes,integer, floating point number, complex number) with the given value. The valuemay be approximated in the case of floating point and imaginary (complex)literals. See sectionリテラル for details.

リテラルは全て変更不能なデータ型に対応します。このため、オブジェクトのアイデンティティはオブジェクトの値ほど重要ではありません。同じ値を持つ複数のリテラルを評価した場合、(それらのリテラルがプログラムの同じ場所由来のものであっても、そうでなくても) 同じオブジェクトを指しているか、まったく同じ値を持つ別のオブジェクトになります。

6.2.3.丸括弧形式 (parenthesized form)

丸括弧形式とは、式リストの一形態で、丸括弧で囲ったものです:

parenth_form ::=  "(" [starred_expression] ")"

丸括弧で囲われた式のリストは、個々の式が表現するものになります: リスト内に少なくとも一つのカンマが入っていた場合、タプルになります; そうでない場合、式のリストを構成している単一の式自体の値になります。

中身が空の丸括弧のペアは、空のタプルオブジェクトを表します。タプルは変更不能なので、リテラルと同じ規則が適用されます (すなわち、空のタプルが二箇所で使われると、それらは同じオブジェクトになることもあるし、ならないこともあります)。

タプルは丸括弧で作成されるのではなく、カンマによって作成されることに注意してください。例外は空のタプルで、この場合には丸括弧が必要です --- 丸括弧のつかない "何も記述しない式 (nothing)" を使えるようにしてしまうと、文法があいまいなものになってしまい、よくあるタイプミスが検出されなくなってしまいます。

6.2.4.リスト、集合、辞書の表示

リスト、集合、辞書を構築するために、 Python は "表示 (display)" と呼ばれる特別な構文を提供していて、次の二種類ずつがあります:

  • コンテナの内容を明示的に列挙する

  • 内包表記 (comprehension) と呼ばれる、ループ処理とフィルター処理の組み合わせを用いた計算結果

内包表記の共通の構文要素は次の通りです:

comprehension ::=assignment_expressioncomp_forcomp_for ::=  ["async"] "for"target_list "in"or_test [comp_iter]comp_iter ::=comp_for |comp_ifcomp_if ::=  "if"or_test [comp_iter]

内包表記はまず単一の式、続いて少なくとも 1 個のfor 節、さらに続いて 0 個以上のfor 節あるいはif 節からなります。この場合、各々のfor 節やif 節を、左から右へ深くなっていくネストしたブロックとみなし、ネストの最内のブロックに到達するごとに内包表記の先頭にある式を評価した結果が、最終的にできあがるコンテナの各要素になります。

ただし、最も左にあるfor 節のイテラブル式を除いて、内包表記は暗黙的にネストされた個別のスコープで実行されます。この仕組みのおかげで、対象のリスト内で代入された名前が外側のスコープに "漏れる" ことはありません。

最も左にあるfor 節のイテラブル式は、それを直接囲んでいるスコープでそのまま評価され、暗黙的な入れ子のスコープに引数として渡されます。後に続くfor 節と、最も左にあるfor 節のフィルター条件はイテラブル式を直接囲んでいるスコープでは評価できません。というのは、それらは最も左のイテラブルから得られる値に依存しているかもしれないからです。例えば次の通りです:[x*yforxinrange(10)foryinrange(x,x+10)]

内包表記が常に適切な型のコンテナになるのを保証するために、yield 式やyieldfrom 式は暗黙的な入れ子のスコープでは禁止されています。

Since Python 3.6, in anasyncdef function, anasyncforclause may be used to iterate over aasynchronous iterator.A comprehension in anasyncdef function may consist of either afor orasyncfor clause following the leadingexpression, may contain additionalfor orasyncforclauses, and may also useawait expressions.If a comprehension contains eitherasyncfor clauses orawait expressions or other asynchronous comprehensions it is calledanasynchronous comprehension. An asynchronous comprehension maysuspend the execution of the coroutine function in which it appears.See alsoPEP 530.

バージョン 3.6 で追加:非同期内包表記が導入されました。

バージョン 3.8 で変更:yield およびyieldfrom は暗黙的な入れ子のスコープでは禁止となりました。

バージョン 3.11 で変更:Asynchronous comprehensions are now allowed inside comprehensions inasynchronous functions. Outer comprehensions implicitly becomeasynchronous.

6.2.5.リスト表示

リスト表示は、角括弧で囲われた式の系列です。系列は空の系列であってもかまいません:

list_display ::=  "[" [starred_list |comprehension] "]"

リスト表示は、新しいリストオブジェクトを与えます。リストの内容は、式のリストまたはリスト内包表記 (list comprehension) で指定されます。カンマで区切られた式のリストが与えられたときは、それらの各要素は左から右へと順に評価され、その順にリスト内に配置されます。内包表記が与えられたときは、内包表記の結果の要素でリストが構成されます。

6.2.6.集合表示

集合表示は波括弧で表され、キーと値を分けるコロンがないことで辞書表現と区別されます:

set_display ::=  "{" (starred_list |comprehension) "}"

集合表示は、新しいミュータブルな集合オブジェクトを与えます。集合の内容は、式の並びまたは内包表記によって指定されます。カンマ区切りの式のリストが与えられたときは、その要素は左から右へ順に評価され、集合オブジェクトに加えられます。内包表記が与えられたときは、内包表記の結果の要素で集合が構成されます。

空集合は{} で構成できません。このリテラルは空の辞書を構成します。

6.2.7.辞書表示

A dictionary display is a possibly empty series of dict items (key/value pairs)enclosed in curly braces:

dict_display ::=  "{" [dict_item_list |dict_comprehension] "}"dict_item_list ::=dict_item (","dict_item)* [","]dict_item ::=expression ":"expression | "**"or_exprdict_comprehension ::=expression ":"expressioncomp_for

辞書表示は、新たな辞書オブジェクトを表します。

If a comma-separated sequence of dict items is given, they are evaluatedfrom left to right to define the entries of the dictionary: each key object isused as a key into the dictionary to store the corresponding value. This meansthat you can specify the same key multiple times in the dict item list, and thefinal dictionary's value for that key will be the last one given.

A double asterisk** denotesdictionary unpacking.Its operand must be amapping. Each mapping item is addedto the new dictionary. Later values replace values already set byearlier dict items and earlier dictionary unpackings.

バージョン 3.5 で追加:辞書表示のアンパックは最初にPEP 448 で提案されました。

辞書内包表記は、リストや集合の内包表記とは対照的に、通常の "for" や "if" 節の前に、コロンで分けられた 2 つの式が必要です。内包表記が起動すると、結果のキーと値の要素が、作られた順に新しい辞書に挿入されます。

Restrictions on the types of the key values are listed earlier in section標準型の階層. (To summarize, the key type should behashable, which excludesall mutable objects.) Clashes between duplicate keys are not detected; the lastvalue (textually rightmost in the display) stored for a given key valueprevails.

バージョン 3.8 で変更:Python 3.8 より前のバージョンでは、辞書内包表記において、キーと値の評価順序は明示されていませんでした。CPython では、値がキーより先に評価されていました。バージョン 3.8 からはPEP 572 で提案されているように、キーが値より先に評価されます。

6.2.8.ジェネレータ式

ジェネレータ式 (generator expression) とは、丸括弧を使ったコンパクトなジェネレータ表記法です:

generator_expression ::=  "("expressioncomp_for ")"

ジェネレータ式は新たなジェネレータオブジェクトを与えます。この構文は内包表記とほぼ同じですが、角括弧や波括弧ではなく、丸括弧で囲まれます。

ジェネレータ式の中で使われている変数は、 (通常のジェネレータと同じように) そのジェネレータオブジェクトに対して__next__() メソッドが呼ばれるときまで評価が遅延されます。ただし、最も左にあるfor 節のイテラブル式は直ちに評価されます。そのためそこで生じたエラーは、最初の値が得られた時点ではなく、ジェネレータ式が定義された時点で発せられます。後に続くfor 節と、最も左にあるfor 節のフィルター条件はイテラブル式を直接囲んでいるスコープでは評価できません。というのは、それらは最も左のイテラブルから得られる値に依存しているかもしれないからです。例えば次の通りです:(x*yforxinrange(10)foryinrange(x,x+10))

関数の唯一の引数として渡す場合には、丸括弧を省略できます。詳しくは呼び出し (call) 節を参照してください。

ジェネレータ式自身の期待される動作を妨げないために、yield 式やyieldfrom 式は暗黙的に定義されたジェネレータでは禁止されています。

ジェネレータ式がasyncfor 節あるいはawait 式を含んでいる場合、それは非同期ジェネレータ式 と呼ばれます。非同期ジェネレータ式は、非同期イテレータである新しい非同期ジェネレータオブジェクトを返します (非同期イテレータ (Asynchronous Iterator) を参照してください)。

バージョン 3.6 で追加:非同期ジェネレータ式が導入されました。

バージョン 3.7 で変更:Python 3.7 より前では、非同期ジェネレータ式はasyncdef コルーチンでしか使えませんでした。3.7 からは、任意の関数で非同期ジェネレータ式が使えるようになりました。

バージョン 3.8 で変更:yield およびyieldfrom は暗黙的な入れ子のスコープでは禁止となりました。

6.2.9.Yield 式

yield_atom ::=  "("yield_expression ")"yield_from ::=  "yield" "from"expressionyield_expression ::=  "yield"expression_list |yield_from

yield 式はジェネレータ 関数や非同期ジェネレータ 関数を定義するときに使われます。従って、関数定義の本体でのみ使えます。関数の本体で yield 式 を使用するとその関数はジェネレータ関数になり、asyncdef 関数の本体で使用するとそのコルーチン関数は非同期ジェネレータ関数になります。例えば次のようになります:

defgen():# defines a generator functionyield123asyncdefagen():# defines an asynchronous generator functionyield123

含まれているスコープの副作用のため、yield 式は暗黙的に定義されたスコープの一部として内包表記やジェネレータ式を実装するのに使うことは許可されていません。

バージョン 3.8 で変更:yield 式は、暗黙的な入れ子のスコープで内包表記やジェネレータ式を実装するための使用が禁止になりました。

ジェネレータ関数についてはすぐ下で説明されています。非同期ジェネレータ関数は、非同期ジェネレータ関数 (asynchronous generator function) 節に分けて説明されています。

When a generator function is called, it returns an iterator known as agenerator. That generator then controls the execution of the generatorfunction. The execution starts when one of the generator's methods is called.At that time, the execution proceeds to the first yield expression, where it issuspended again, returning the value ofexpression_listto the generator's caller,orNone ifexpression_list is omitted.By suspended, we mean that all local state isretained, including the current bindings of local variables, the instructionpointer, the internal evaluation stack, and the state of any exception handling.When the execution is resumed by calling one of the generator's methods, thefunction can proceed exactly as if the yield expression were just anotherexternal call. The value of the yield expression after resuming depends on themethod which resumed the execution. If__next__() is used(typically via either afor or thenext() builtin) then theresult isNone. Otherwise, ifsend() is used, thenthe result will be the value passed in to that method.

これまで説明した内容から、ジェネレータ関数はコルーチンにとてもよく似ています。ジェネレータ関数は何度も生成し、1つ以上のエントリポイントを持ち、その実行は一時停止されます。ジェネレータ関数は yield した後で実行の継続を制御できないことが唯一の違いです。その制御は常にジェネレータの呼び出し元へ移されます。

yield 式はtry 構造内で使用できます。ジェネレータの (参照カウントがゼロに達するか、ガベージコレクションによる) 完了前に再開されない場合、ジェネレータ-イテレータのclose() メソッドが呼ばれ、finally 節が実行されます。

yieldfrom<expr> を使用した場合、与えられた式はイテラブルでなければなりません。そのイテラブルをイテレートすることで生成された値は現在のジェネレータのメソッドの呼び出し元へ直接渡されます。send() で渡されたあらゆる値とthrow() で渡されたあらゆる例外は根底のイテレータに適切なメソッドがあれば渡されます。適切なメソッドがない場合、send()AttributeErrorTypeError を、throw() は渡された例外を即座に送出します。

根底のイテレータの完了時、引き起こされたStopIteration インスタンスのvalue 属性はその yield 式の値となります。StopIteration を起こす際に明示的にセットされるか、サブイテレータがジェネレータであれば (サブイテレータからかえる値で) 自動的にセットされるかのどちらかです。

バージョン 3.3 で変更:サブイテレータに制御フローを委譲するためにyieldfrom<expr> が追加されました。

yield 式が代入文の単独の右辺式であるとき、括弧は省略できます。

参考

PEP 255 - 単純なジェネレータ

Python へのジェネレータとyield 文の導入提案。

PEP 342 - 拡張されたジェネレータを用いたコルーチン

シンプルなコルーチンとして利用できるように、ジェネレータの構文と API を拡張する提案。

PEP 380 - サブジェネレータへの委譲構文

サブジェネレータの委譲を簡単にするための、yield_from 構文の導入提案。

PEP 525 - 非同期ジェネレータ

コルーチン関数へのジェネレータの実装能力の追加によるPEP 492 の拡張提案。

6.2.9.1.ジェネレータ-イテレータメソッド

この説ではジェネレータイテレータのメソッドについて説明します。これらはジェネレータ関数の実行制御に使用できます。

以下のジェネレータメソッドの呼び出しは、ジェネレータが既に実行中の場合ValueError 例外を送出する点に注意してください。

generator.__next__()

Starts the execution of a generator function or resumes it at the lastexecuted yield expression. When a generator function is resumed with a__next__() method, the current yield expression alwaysevaluates toNone. The execution then continues to the next yieldexpression, where the generator is suspended again, and the value of theexpression_list is returned to__next__()'scaller. If the generator exits without yielding another value, aStopIteration exception is raised.

このメソッドは通常、例えばfor ループや組み込みのnext() 関数によって暗黙に呼び出されます。

generator.send(value)

ジェネレータ関数の内部へ値を "送り"、実行を再開します。引数のvalue はその時点の yield 式の結果になります。send() メソッドは次にジェネレータが生成した値を返し、ジェネレータが次の値を生成することなく終了するとStopIteration を送出します。send() が呼び出されてジェネレータが開始するときは、値を受け取る yield 式が存在しないので、None を引数として呼び出さなければなりません。

generator.throw(value)
generator.throw(type[,value[,traceback]])

ジェネレータが中断した位置で例外を発生させて、そのジェネレータ関数が生成する次の値を返します。ジェネレータが値を生成することなく終了するとStopIteration が発生します。ジェネレータ関数が渡された例外を捕捉しない、もしくは違う例外を発生させるなら、その例外は呼び出し元へ伝搬されます。

In typical use, this is called with a single exception instance similar to theway theraise keyword is used.

For backwards compatibility, however, the second signature issupported, following a convention from older versions of Python.Thetype argument should be an exception class, andvalueshould be an exception instance. If thevalue is not provided, thetype constructor is called to get an instance. Iftracebackis provided, it is set on the exception, otherwise any existing__traceback__ attribute stored invalue maybe cleared.

generator.close()

Raises aGeneratorExit at the point where the generator function waspaused. If the generator function then exits gracefully, is already closed,or raisesGeneratorExit (by not catching the exception), closereturns to its caller. If the generator yields a value, aRuntimeError is raised. If the generator raises any other exception,it is propagated to the caller.close() does nothing if the generatorhas already exited due to an exception or normal exit.

6.2.9.2.使用例

以下の簡単なサンプルはジェネレータとジェネレータ関数の振る舞いを実際に紹介します:

>>>defecho(value=None):...print("Execution starts when 'next()' is called for the first time.")...try:...whileTrue:...try:...value=(yieldvalue)...exceptExceptionase:...value=e...finally:...print("Don't forget to clean up when 'close()' is called.")...>>>generator=echo(1)>>>print(next(generator))Execution starts when 'next()' is called for the first time.1>>>print(next(generator))None>>>print(generator.send(2))2>>>generator.throw(TypeError,"spam")TypeError('spam',)>>>generator.close()Don't forget to clean up when 'close()' is called.

yieldfrom の使用例は、"What's New in Python." のPEP 380: サブジェネレータへの委譲構文 を参照してください。

6.2.9.3.非同期ジェネレータ関数 (asynchronous generator function)

asyncdef を使用して定義された関数やメソッドに yield 式があると、その関数は非同期ジェネレータ 関数として定義されます。

非同期ジェネレータ関数が呼び出されると、非同期ジェネレータオブジェクトと呼ばれる非同期イテレータが返されます。そして、そのオブジェクトはジェネレータ関数の実行を制御します。通常、非同期ジェネレータオブジェクトは、コルーチン関数内のasyncfor 文で使われ、これはジェネレータオブジェクトがfor 文で使われる様子に類似します。

Calling one of the asynchronous generator's methods returns anawaitableobject, and the execution starts when this object is awaited on. At that time,the execution proceeds to the first yield expression, where it is suspendedagain, returning the value ofexpression_list to theawaiting coroutine. As with a generator, suspension means that all local stateis retained, including the current bindings of local variables, the instructionpointer, the internal evaluation stack, and the state of any exception handling.When the execution is resumed by awaiting on the next object returned by theasynchronous generator's methods, the function can proceed exactly as if theyield expression were just another external call. The value of the yieldexpression after resuming depends on the method which resumed the execution. If__anext__() is used then the result isNone. Otherwise, ifasend() is used, then the result will be the value passed in to thatmethod.

If an asynchronous generator happens to exit early bybreak, the callertask being cancelled, or other exceptions, the generator's async cleanup codewill run and possibly raise exceptions or access context variables in anunexpected context--perhaps after the lifetime of tasks it depends, orduring the event loop shutdown when the async-generator garbage collection hookis called.To prevent this, the caller must explicitly close the async generator by callingaclose() method to finalize the generator and ultimately detach itfrom the event loop.

非同期ジェネレータ関数では、try 構造内の任意の場所で yield 式が使用できます。ただし、非同期ジェネレータが、(参照カウントがゼロに達するか、ガベージコレクションによる) 終了処理より前に再開されない場合、try 構造内の yield 式は失敗となり、実行待ちだったfinally 節が実行されます。このケースでは、非同期ジェネレータが作動しているイベントループやスケジューラの責務は、非同期ジェネレータのaclose() メソッドを呼び出し、残りのコルーチンオブジェクトを実行し、それによって実行待ちだったfinally 節が実行できるようにします。

To take care of finalization upon event loop termination, an event loop shoulddefine afinalizer function which takes an asynchronous generator-iterator andpresumably callsaclose() and executes the coroutine.Thisfinalizer may be registered by callingsys.set_asyncgen_hooks().When first iterated over, an asynchronous generator-iterator will store theregisteredfinalizer to be called upon finalization. For a reference exampleof afinalizer method see the implementation ofasyncio.Loop.shutdown_asyncgens inLib/asyncio/base_events.py.

yieldfrom<expr> 式は、非同期ジェネレータ関数で使われると文法エラーになります。

6.2.9.4.非同期ジェネレータイテレータメソッド

この小節では、ジェネレータ関数の実行制御に使われる非同期ジェネレータイテレータのメソッドについて説明します。

coroutineagen.__anext__()

Returns an awaitable which when run starts to execute the asynchronousgenerator or resumes it at the last executed yield expression. When anasynchronous generator function is resumed with an__anext__()method, the current yield expression always evaluates toNone in thereturned awaitable, which when run will continue to the next yieldexpression. The value of theexpression_list of theyield expression is the value of theStopIteration exception raised bythe completing coroutine. If the asynchronous generator exits withoutyielding another value, the awaitable instead raises aStopAsyncIteration exception, signalling that the asynchronousiteration has completed.

このメソッドは通常、for ループによって暗黙に呼び出されます。

coroutineagen.asend(value)

Returns an awaitable which when run resumes the execution of theasynchronous generator. As with thesend() method for agenerator, this "sends" a value into the asynchronous generator function,and thevalue argument becomes the result of the current yield expression.The awaitable returned by theasend() method will return the nextvalue yielded by the generator as the value of the raisedStopIteration, or raisesStopAsyncIteration if theasynchronous generator exits without yielding another value. Whenasend() is called to start the asynchronousgenerator, it must be called withNone as the argument,because there is no yield expression that could receive the value.

coroutineagen.athrow(value)
coroutineagen.athrow(type[,value[,traceback]])

Returns an awaitable that raises an exception of typetype at the pointwhere the asynchronous generator was paused, and returns the next valueyielded by the generator function as the value of the raisedStopIteration exception. If the asynchronous generator exitswithout yielding another value, aStopAsyncIteration exception israised by the awaitable.If the generator function does not catch the passed-in exception, orraises a different exception, then when the awaitable is run that exceptionpropagates to the caller of the awaitable.

coroutineagen.aclose()

Returns an awaitable that when run will throw aGeneratorExit intothe asynchronous generator function at the point where it was paused.If the asynchronous generator function then exits gracefully, is alreadyclosed, or raisesGeneratorExit (by not catching the exception),then the returned awaitable will raise aStopIteration exception.Any further awaitables returned by subsequent calls to the asynchronousgenerator will raise aStopAsyncIteration exception. If theasynchronous generator yields a value, aRuntimeError is raisedby the awaitable. If the asynchronous generator raises any other exception,it is propagated to the caller of the awaitable. If the asynchronousgenerator has already exited due to an exception or normal exit, thenfurther calls toaclose() will return an awaitable that does nothing.

6.3.プライマリ

プライマリは、言語において最も結合の強い操作を表します。文法は以下のようになります:

primary ::=atom |attributeref |subscription |slicing |call

6.3.1.属性参照

属性参照は、プライマリの後ろにピリオドと名前を連ねたものです:

attributeref ::=primary "."identifier

The primary must evaluate to an object of a type that supports attributereferences, which most objects do. This object is then asked to produce theattribute whose name is the identifier. The type and value produced isdetermined by the object. Multiple evaluations of the same attributereference may yield different objects.

This production can be customized by overriding the__getattribute__() method or the__getattr__()method. The__getattribute__() method is called first and eitherreturns a value or raisesAttributeError if the attribute is notavailable.

If anAttributeError is raised and the object has a__getattr__()method, that method is called as a fallback.

6.3.2.添字表記 (subscription)

The subscription of an instance of acontainer classwill generally select an element from the container. The subscription of ageneric class will generally return aGenericAlias object.

subscription ::=primary "["expression_list "]"

When an object is subscripted, the interpreter will evaluate the primary andthe expression list.

The primary must evaluate to an object that supports subscription. An objectmay support subscription through defining one or both of__getitem__() and__class_getitem__(). When theprimary is subscripted, the evaluated result of the expression list will bepassed to one of these methods. For more details on when__class_getitem__is called instead of__getitem__, see__class_getitem__ versus __getitem__.

If the expression list contains at least one comma, it will evaluate to atuple containing the items of the expression list. Otherwise, theexpression list will evaluate to the value of the list's sole member.

組み込みオブジェクトでは、__getitem__() によって添字表記をサポートするオブジェクトには 2 種類あります:

  1. マッピング。プライマリがマッピング であれば、式リストの値評価結果はマップ内のいずれかのキー値に相当するオブジェクトにならなければなりません。添字表記は、そのキーに対応するマッピング内の値 (value) を選択します。組み込みのマッピングクラスの例はdict クラスです。

  2. シーケンス。プライマリがシーケンス であれば、式リストの評価結果はint またはslice (以下の節で論じます) でなければなりません。組み込みのシーケンスクラスの例にはstrlisttuple クラスが含まれます。

The formal syntax makes no special provision for negative indices insequences. However, built-in sequences all provide a__getitem__()method that interprets negative indices by adding the length of the sequenceto the index so that, for example,x[-1] selects the last item ofx. Theresulting value must be a nonnegative integer less than the number of items inthe sequence, and the subscription selects the item whose index is that value(counting from zero). Since the support for negative indices and slicingoccurs in the object's__getitem__() method, subclasses overridingthis method will need to explicitly add that support.

文字列 は文字 (character) を要素とする特別な種類のシーケンスです。文字は個別の型ではなく、 1 文字だけからなる文字列です。

6.3.3.スライス表記 (slicing)

スライス表記はシーケンスオブジェクト (文字列、タプルまたはリスト) におけるある範囲の要素を選択します。スライス表記は式として用いたり、代入やdel 文の対象として用いたりできます。スライス表記の構文は以下のようになります:

slicing ::=primary "["slice_list "]"slice_list ::=slice_item (","slice_item)* [","]slice_item ::=expression |proper_sliceproper_slice ::=  [lower_bound] ":" [upper_bound] [ ":" [stride] ]lower_bound ::=expressionupper_bound ::=expressionstride ::=expression

上記の形式的な構文法にはあいまいなところがあります: 式リストに見えるものは、スライスリストにも見えるため、添字表記はスライス表記としても解釈されうるということです。(スライスリストが適切なスライスを含まない場合)、これ以上の構文の複雑化はせず、スライス表記としての解釈よりも添字表記としての解釈が優先されるように定義することで、あいまいさを取り除いています。

The semantics for a slicing are as follows. The primary is indexed (using thesame__getitem__() method asnormal subscription) with a key that is constructed from the slice list, asfollows. If the slice list contains at least one comma, the key is a tuplecontaining the conversion of the slice items; otherwise, the conversion of thelone slice item is the key. The conversion of a slice item that is anexpression is that expression. The conversion of a proper slice is a sliceobject (see section標準型の階層) whosestart,stop andstep attributes are the values of theexpressions given as lower bound, upper bound and stride, respectively,substitutingNone for missing expressions.

6.3.4.呼び出し (call)

呼び出しは、呼び出し可能オブジェクト (例えばfunction) をarguments の系列とともに呼び出します。系列は空の系列であってもかまいません:

call ::=primary "(" [argument_list [","] |comprehension] ")"argument_list ::=positional_arguments [","starred_and_keywords]                            [","keywords_arguments]                          |starred_and_keywords [","keywords_arguments]                          |keywords_argumentspositional_arguments ::=  positional_item ("," positional_item)*positional_item ::=assignment_expression | "*"expressionstarred_and_keywords ::=  ("*"expression |keyword_item)                          ("," "*"expression | ","keyword_item)*keywords_arguments ::=  (keyword_item | "**"expression)                          (","keyword_item | "," "**"expression)*keyword_item ::=identifier "="expression

最後の位置引数やキーワード引数の後にカンマをつけてもかまいません。構文の意味付けに影響を及ぼすことはありません。

The primary must evaluate to a callable object (user-defined functions, built-infunctions, methods of built-in objects, class objects, methods of classinstances, and all objects having a__call__() method are callable). Allargument expressions are evaluated before the call is attempted. Please referto section関数定義 for the syntax of formalparameter lists.

キーワード引数が存在する場合、以下のようにして最初に位置引数 (positional argument) に変換されます。まず、値の入っていないスロットが仮引数に対して生成されます。N 個の位置引数がある場合、位置引数は先頭の N スロットに配置されます。次に、各キーワード引数について、識別子を使って対応するスロットを決定します (識別子が最初の仮引数名と同じなら、最初のスロットを使う、といった具合です)。スロットがすでにすべて埋まっていたならTypeError 例外が送出されます。それ以外の場合、引数をスロットに埋めていきます。 (式がNone であっても、その式でスロットを埋めます)。全ての引数が処理されたら、まだ埋められていないスロットをそれぞれに対応する関数定義時のデフォルト値で埋めます。(デフォルト値は、関数が定義されたときに一度だけ計算されます; 従って、リストや辞書のような変更可能なオブジェクトがデフォルト値として使われると、対応するスロットに引数を指定しない限り、このオブジェクトが全ての呼び出しから共有されます; このような状況は通常避けるべきです。) デフォルト値が指定されていない、値の埋められていないスロットが残っている場合TypeError 例外が送出されます。そうでない場合、値の埋められたスロットからなるリストが呼び出しの引数として使われます。

CPython 実装の詳細: 実装では、名前を持たない位置引数を受け取る組み込み関数を提供されるかもしれません。そういった引数がドキュメント化のために '名付けられて' いたとしても、実際には名付けられていないのでキーワードでは提供されません。 CPython では、C 言語で実装された関数の、名前を持たない位置引数をパースするためにPyArg_ParseTuple() を使用します。

仮引数スロットの数よりも多くの位置引数がある場合、構文*identifier を使って指定された仮引数がないかぎり、TypeError 例外が送出されます; 仮引数*identifier がある場合、この仮引数は余分な位置引数が入ったタプル (もしくは、余分な位置引数がない場合には空のタプル) を受け取ります。

キーワード引数のいずれかが仮引数名に対応しない場合、構文**identifier を使って指定された仮引数がない限り、TypeError 例外が送出されます; 仮引数**identifier がある場合、この仮引数は余分なキーワード引数が入った (キーワードをキーとし、引数値をキーに対応する値とした) 辞書を受け取ります。余分なキーワード引数がない場合には、空の (新たな) 辞書を受け取ります。

関数呼び出しに*expression という構文が現れる場合は、expression の評価結果はイテラブル でなければなりません。そのイテラブルの要素は、追加の位置引数であるかのように扱われます。f(x1,x2,*y,x3,x4) という呼び出しにおいて、y の評価結果がシーケンスy1, ...,yM だった場合は、この呼び出しは M+4 個の位置引数x1,x2,y1, ...,yM,x3,x4 での呼び出しと同じになります。

この結論としては、*expression 構文がキーワード引数の後ろ に来ることもありますが、キーワード引数 (と任意の**expression 引数 -- 下を参照) よりも にあるものとして処理されます。従って、このような動作になります:

>>>deff(a,b):...print(a,b)...>>>f(b=1,*(2,))2 1>>>f(a=1,*(2,))Traceback (most recent call last):  File"<stdin>", line1, in<module>TypeError:f() got multiple values for keyword argument 'a'>>>f(1,*(2,))1 2

キーワード引数と*expression 構文を同じ呼び出しで一緒に使うことはあまりないので、実際に上記のような混乱が頻繁に生じることはありません。

関数呼び出しで**expression 構文が使われた場合、expression の評価結果はマッピング でなければなりません。その内容は追加のキーワード引数として扱われます。キーにマッチする引数が (明示的なキーワード引数によって、あるいは他のアンパックの中で) 既に値を与えられていたなら、TypeError 例外が送出されます。

When**expression is used, each key in this mapping must bea string.Each value from the mapping is assigned to the first formal parametereligible for keyword assignment whose name is equal to the key.A key need not be a Python identifier (e.g."max-temp°F" is acceptable,although it will not match any formal parameter that could be declared).If there is no match to a formal parameterthe key-value pair is collected by the** parameter, if there is one,or if there is not, aTypeError exception is raised.

*identifier**identifier 構文を使った仮引数は、位置引数スロットやキーワード引数名にすることができません。

バージョン 3.5 で変更:関数呼び出しは任意の数の* アンパックと** アンパックを受け取り、位置引数はイテラブルアンパック (*) の後ろに置け、キーワード引数は辞書アンパック (**) の後ろに置けるようになりました。最初にPEP 448 で提案されました。

呼び出しを行うと、例外を送出しない限り、常に何らかの値を返します。None を返す場合もあります。戻り値がどのように算出されるかは、呼び出し可能オブジェクトの形態によって異なります。

各形態では---

ユーザ定義関数:

The code block for the function is executed, passing it the argument list. Thefirst thing the code block will do is bind the formal parameters to thearguments; this is described in section関数定義. When the code blockexecutes areturn statement, this specifies the return value of thefunction call.

組み込み関数またはメソッド:

結果はインタプリタに依存します; 組み込み関数やメソッドの詳細は組み込み関数 を参照してください。

クラスオブジェクト:

そのクラスの新しいインスタンスが返されます。

クラスインスタンスメソッド:

対応するユーザ定義の関数が呼び出されます。このとき、呼び出し時の引数リストより一つ長い引数リストで呼び出されます: インスタンスが引数リストの先頭に追加されます。

クラスインスタンス:

The class must define a__call__() method; the effect is then the same asif that method was called.

6.4.Await 式

awaitable オブジェクトでのcoroutine 実行を一時停止します。coroutine function 内でのみ使用できます。

await_expr ::=  "await"primary

バージョン 3.5 で追加.

6.5.べき乗演算 (power operator)

べき乗演算は、左側にある単項演算子よりも強い結合優先順位となります。一方、右側にある単項演算子よりは弱い結合優先順位になっています。構文は以下のようになります:

power ::=  (await_expr |primary) ["**"u_expr]

従って、べき乗演算子と単項演算子からなる演算列が丸括弧で囲われていない場合、演算子は右から左へと評価されます (この場合は演算子の評価順序を強制しません。つまり-1**2-1 になります)。

べき乗演算子の意味は、二つの引数で呼び出される組み込み関数pow() と同じで、左引数を右引数乗して与えます。数値引数はまず共通の型に変換され、結果はその型です。

整数の被演算子では、第二引数が負でない限り、結果は被演算子と同じ型になります; 第二引数が負の場合、全ての引数は浮動小数点型に変換され、浮動小数点型が返されます。例えば10**2100 を返しますが、10**-20.01 を返します。

0.0 を負の数でべき乗するとZeroDivisionError を送出します。負の数を小数でべき乗した結果は複素数 (complex number) になります。 (以前のバージョンではValueError を送出していました)

This operation can be customized using the special__pow__() method.

6.6.単項算術演算とビット単位演算 (unary arithmetic and bitwise operation)

全ての単項算術演算とビット単位演算は、同じ優先順位を持っています:

u_expr ::=power | "-"u_expr | "+"u_expr | "~"u_expr

The unary- (minus) operator yields the negation of its numeric argument; theoperation can be overridden with the__neg__() special method.

The unary+ (plus) operator yields its numeric argument unchanged; theoperation can be overridden with the__pos__() special method.

The unary~ (invert) operator yields the bitwise inversion of its integerargument. The bitwise inversion ofx is defined as-(x+1). It onlyapplies to integral numbers or to custom objects that override the__invert__() special method.

上記の三つはいずれも、引数が正しい型でない場合にはTypeError 例外が送出されます。

6.7.二項算術演算 (binary arithmetic operation)

二項算術演算は、慣習的な優先順位を踏襲しています。演算子のいずれかは、特定の非数値型にも適用されるので注意してください。べき乗 (power) 演算子を除き、演算子には二つのレベル、すなわち乗算的 (multiplicatie) 演算子と加算的 (additie) 演算子しかありません:

m_expr ::=u_expr |m_expr "*"u_expr |m_expr "@"m_expr |m_expr "//"u_expr |m_expr "/"u_expr |m_expr "%"u_expra_expr ::=m_expr |a_expr "+"m_expr |a_expr "-"m_expr

The* (multiplication) operator yields the product of its arguments. Thearguments must either both be numbers, or one argument must be an integer andthe other must be a sequence. In the former case, the numbers are converted to acommon type and then multiplied together. In the latter case, sequencerepetition is performed; a negative repetition factor yields an empty sequence.

This operation can be customized using the special__mul__() and__rmul__() methods.

@ (at) 演算子は行列の乗算に対し使用されます。Python の組み込み型はこの演算子を実装していません。

バージョン 3.5 で追加.

/ (除算: division) および// (切り捨て除算: floor division) は、引数同士の商を与えます。数値引数はまず共通の型に変換されます。整数の除算結果は浮動小数点になりますが、整数の切り捨て除算結果は整数になります; この場合、結果は数学的な除算に 'floor' 関数 を適用したものになります。ゼロによる除算を行うとZeroDivisionError 例外を送出します。

This operation can be customized using the special__truediv__() and__floordiv__() methods.

The% (modulo) operator yields the remainder from the division of the firstargument by the second. The numeric arguments are first converted to a commontype. A zero right argument raises theZeroDivisionError exception. Thearguments may be floating point numbers, e.g.,3.14%0.7 equals0.34(since3.14 equals4*0.7+0.34.) The modulo operator always yields aresult with the same sign as its second operand (or zero); the absolute value ofthe result is strictly smaller than the absolute value of the second operand[1].

切り捨て除算演算と剰余演算は、恒等式:x==(x//y)*y+(x%y) の関係にあります。切り捨て除算や剰余はまた、組み込み関数divmod():divmod(x,y)==(x//y,x%y) とも関係しています。[2]

% 演算子は、数値に対する剰余演算を行うのに加えて、文字列 (string) オブジェクトにオーバーロードされ、旧式の文字列の書式化 (いわゆる補間) を行います。文字列の書式化の構文は Python ライブラリリファレンスprintf 形式の文字列書式化 節を参照してください。

Themodulo operation can be customized using the special__mod__() method.

The floor division operator, the modulo operator, and thedivmod()function are not defined for complex numbers. Instead, convert to a floatingpoint number using theabs() function if appropriate.

The+ (addition) operator yields the sum of its arguments. The argumentsmust either both be numbers or both be sequences of the same type. In theformer case, the numbers are converted to a common type and then added together.In the latter case, the sequences are concatenated.

This operation can be customized using the special__add__() and__radd__() methods.

The- (subtraction) operator yields the difference of its arguments. Thenumeric arguments are first converted to a common type.

This operation can be customized using the special__sub__() method.

6.8.シフト演算 (shifting operation)

シフト演算は、算術演算よりも低い優先順位を持っています:

shift_expr ::=a_expr |shift_expr ("<<" | ">>")a_expr

これらは整数を引数にとります。引数は共通の型に変換されます。シフト演算は第一引数を、第二引数で与えられたビット数だけ、左または右にビットシフトします。

This operation can be customized using the special__lshift__() and__rshift__() methods.

n ビットの右シフトはpow(2,n) による除算として定義されます。n ビットの左シフトはpow(2,n) による乗算として定義されます。

6.9.ビット単位演算の二項演算 (binary bitwise operation)

以下の三つのビット単位演算には、それぞれ異なる優先順位レベルがあります:

and_expr ::=shift_expr |and_expr "&"shift_exprxor_expr ::=and_expr |xor_expr "^"and_expror_expr ::=xor_expr |or_expr "|"xor_expr

The& operator yields the bitwise AND of its arguments, which must beintegers or one of them must be a custom object overriding__and__() or__rand__() special methods.

The^ operator yields the bitwise XOR (exclusive OR) of its arguments, whichmust be integers or one of them must be a custom object overriding__xor__() or__rxor__() special methods.

The| operator yields the bitwise (inclusive) OR of its arguments, whichmust be integers or one of them must be a custom object overriding__or__() or__ror__() special methods.

6.10.比較

C 言語と違って、Python における比較演算子は同じ優先順位をもっており、全ての算術演算子、シフト演算子、ビット単位演算子よりも低くなっています。またa<b<c が数学で伝統的に用いられているのと同じ解釈になる点も C 言語と違います:

comparison ::=or_expr (comp_operatoror_expr)*comp_operator ::=  "<" | ">" | "==" | ">=" | "<=" | "!="                   | "is" ["not"] | ["not"] "in"

Comparisons yield boolean values:True orFalse. Customrich comparison methods may return non-boolean values. In this casePython will callbool() on such value in boolean contexts.

比較はいくらでも連鎖することができます。例えばx<y<=zx<yandy<=z と等価になります。ただしこの場合、前者ではy はただ一度だけ評価される点が異なります (どちらの場合でも、x<y が偽になるとz の値はまったく評価されません)。

形式的には、a,b,c, ...,y,z が式でop1,op2, ...,opN が比較演算子である場合、aop1bop2c...yopNzaop1bandbop2cand...yopNz と等価になります。ただし、前者では各式は多くても一度しか評価されません。

aop1bop2c と書いた場合、a からc までの範囲にあるかどうかのテストを指すのではないことに注意してください。例えばx<y>z は (きれいな書き方ではありませんが) 完全に正しい文法です。

6.10.1.値の比較

演算子<,>,==,>=,<=, および!= は2つのオブジェクトの値を比較します。オブジェクトが同じ型を持つ必要はりません。

オブジェクト、値、および型 の章では、オブジェクトは (型や id に加えて) 値を持つことを述べています。オブジェクトの値は Python ではやや抽象的な概念です: 例えば、オブジェクトの値にアクセスする正統な方法はありません。また、その全てのデータ属性から構成されるなどの特定の方法で、オブジェクトの値を構築する必要性もありません。比較演算子は、オブジェクトの値とは何かについての特定の概念を実装しています。この比較の実装によって、間接的にオブジェクトの値を定義していると考えることもできます。

Because all types are (direct or indirect) subtypes ofobject, theyinherit the default comparison behavior fromobject. Types cancustomize their comparison behavior by implementingrich comparison methods like__lt__(), described in基本的なカスタマイズ.

等価比較 (== および!=) のデフォルトの振る舞いは、オブジェクトの同一性に基づいています。従って、同一のインスタンスの等価比較の結果は等しいとなり、同一でないインスタンスの等価比較の結果は等しくないとなります。デフォルトの振る舞いをこのようにしたのは、全てのオブジェクトを反射的 (reflexive つまりxisy ならばx==y) なものにしたかったからです。

デフォルトの順序比較 (<,>,<=,>=) は提供されません; 比較しようとするとTypeError が送出されます。この振る舞いをデフォルトの振る舞いにした動機は、等価性と同じような不変性が欠けているからです。

同一でないインスタンスは常に等価でないとする等価比較のデフォルトの振る舞いは、型が必要とするオブジェクトの値や値に基づいた等価性の実用的な定義とは対照的に思えるでしょう。そのような型では比較の振る舞いをカスタマイズする必要が出てきて、実際にたくさんの組み込み型でそれが行われています。

次のリストでは、最重要の組み込み型の比較の振る舞いを解説しています。

  • いくつかの組み込みの数値型 (数値型 int, float, complex) と標準ライブラリの型fractions.Fraction およびdecimal.Decimal は、これらの型の範囲で異なる型とも比較できますが、複素数では順序比較がサポートされていないという制限があります。関わる型の制限の範囲内では、精度のロス無しに数学的に (アルゴリズム的に) 正しい比較が行われます。

    非数値であるfloat('NaN')decimal.Decimal('NaN') は特別です。数と非数値との任意の順序比較は偽です。直観に反する帰結として、非数値は自分自身と等価ではないことになります。例えばx=float('NaN') ならば、3<x,x<3,x==x は全て偽で、x!=x は真です。この振る舞いは IEEE 754 に従ったものです。

  • None andNotImplemented are singletons.PEP 8 advises thatcomparisons for singletons should always be done withis orisnot,never the equality operators.

  • バイナリシーケンス (bytes またはbytearray のインスタンス) は、これらの型の範囲で異なる型とも比較できます。比較は要素の数としての値を使った辞書式順序で行われます。

  • 文字列 (str のインスタンス) の比較は、文字の Unicode のコードポイントの数としての値 (組み込み関数ord() の返り値) を使った辞書式順序で行われます。[3]

    文字列とバイナリシーケンスは直接には比較できません。

  • シーケンス (tuple,list, orrange のインスタンス) の比較は、同じ型どうしでしか行えず、 range は順序比較をサポートしていません。異なる型どうしの等価比較の結果は等価でないとなり、異なる型どうしの順序比較はTypeError を送出します。

    Sequences compare lexicographically using comparison of correspondingelements. The built-in containers typically assume identical objects areequal to themselves. That lets them bypass equality tests for identicalobjects to improve performance and to maintain their internal invariants.

    組み込みのコレクションどうしの辞書式比較は次のように動作します:

    • 比較の結果が等価となる2つのコレクションは、同じ型、同じ長さ、対応する要素どうしの比較の結果が等価でなければなりません (例えば、[1,2]==(1,2) は型が同じでないので偽です)。

    • 順序比較をサポートしているコレクションの順序は、最初の等価でない要素の順序と同じになります (例えば、[1,2,x]<=[1,2,y]x<=y と同じ値になります)。対応する要素が存在しない場合、短い方のコレクションの方が先の順序となります (例えば、[1,2]<[1,2,3] は真です)。

  • マッピング (dict のインスタンス) の比較の結果が等価となるのは、同じ(key,value) を持っているときかつそのときに限ります。キーと値の等価比較では反射性が強制されます。

    順序比較 (<,>,<=,>=) はTypeError を送出します。

  • 集合 (set またはfrozenset のインスタンス) の比較は、これらの型の範囲で異なる型とも行えます。

    集合には、部分集合あるいは上位集合かどうかを基準とする順序比較が定義されています。この関係は全順序を定義しません (例えば、{1,2}{2,3} という2つの集合は片方がもう一方の部分集合でもなく上位集合でもありません)。従って、集合は全順序性に依存する関数の引数として適切ではありません (例えば、min(),max(),sorted() は集合のリストを入力として与えると未定義な結果となります)。

    集合の比較では、その要素の反射性が強制されます。

  • 他の組み込み型のほとんどは比較メソッドが実装されておらず、デフォルトの比較の振る舞いを継承します。

比較の振る舞いをカスタマイズしたユーザ定義クラスは、可能なら次の一貫性の規則に従う必要があります:

  • 等価比較は反射的でなければなりません。つまり、同一のオブジェクトは等しくなければなりません:

    xisy ならばx==y

  • 比較は対称的でなければなりません。つまり、以下の式の結果は同じでなければなりません:

    x==yy==x

    x!=yy!=x

    x<yy>x

    x<=yy>=x

  • 比較は推移的でなければなりません。以下の (包括的でない) 例がその説明です:

    x>yandy>z ならばx>z

    x<yandy<=z ならばx<z

  • 比較の逆は真偽値の否定でなければなりません。つまり、以下の式の結果は同じでなければなりません:

    x==ynotx!=y

    x<ynotx>=y (全順序の場合)

    x>ynotx<=y (全順序の場合)

    最後の2式は全順序コレクションに当てはまります (たとえばシーケンスには当てはまりますが、集合やマッピングには当てはまりません)。total_ordering() デコレータも参照してください。

  • hash() の結果は等価性と一貫している必要があります。等価なオブジェクトどうしは同じハッシュ値を持つか、ハッシュ値が計算できないものとされる必要があります。

Python はこの一貫性規則を強制しません。事実、非数値がこの規則に従わない例となります。

6.10.2.所属検査演算

演算子in およびnotin は所属関係を調べます。xins の評価は、xs の要素であればTrue となり、そうでなければFalse となります。xnotinsxins の否定を返します。すべての組み込みのシーケンス型と集合型に加えて、辞書もin を辞書が与えられたキーを持っているかを調べる演算子としてサポートしています。リスト、タプル、集合、凍結集合、辞書、 collections.deque のようなコンテナ型において、式xinyany(xiseorx==eforeiny) と等価です。

文字列やバイト列型については、xinyxy の部分文字列であるとき、かつそのときに限りTrue になります。これはy.find(x)!=-1 と等価です。空文字列は、他の任意の文字列の部分文字列とみなされます。従って""in"abc"True を返すことになります。

For user-defined classes which define the__contains__() method,xiny returnsTrue ify.__contains__(x) returns a true value, andFalse otherwise.

For user-defined classes which do not define__contains__() but do define__iter__(),xiny isTrue if some valuez, for which theexpressionxiszorx==z is true, is produced while iterating overy.If an exception is raised during the iteration, it is as ifin raisedthat exception.

Lastly, the old-style iteration protocol is tried: if a class defines__getitem__(),xiny isTrue if and only if there is a non-negativeinteger indexi such thatxisy[i]orx==y[i], and no lower integer indexraises theIndexError exception. (If any other exception is raised, it is asifin raised that exception).

演算子notinin の真理値を反転した値として定義されています。

6.10.3.同一性の比較

演算子is およびisnot は、オブジェクトの同一性に対するテストを行います:xisy は、xy が同じオブジェクトを指すとき、かつそのときに限り真になります。オブジェクトの同一性はid() 関数を使って判定されます。xisnotyis の真値を反転したものになります。[4]

6.11.ブール演算 (boolean operation)

or_test ::=and_test |or_test "or"and_testand_test ::=not_test |and_test "and"not_testnot_test ::=comparison | "not"not_test

In the context of Boolean operations, and also when expressions are used bycontrol flow statements, the following values are interpreted as false:False,None, numeric zero of all types, and empty strings and containers(including strings, tuples, lists, dictionaries, sets and frozensets). Allother values are interpreted as true. User-defined objects can customize theirtruth value by providing a__bool__() method.

演算子not は、引数が偽である場合にはTrue を、それ以外の場合にはFalse になります。

xandy は、まずx を評価します;x が偽ならx の値を返します; それ以外の場合には、y を評価した結果値を返します。

xory は、まずx を評価します;x が真ならx の値を返します; それ以外の場合には、y を評価した結果値を返します。

なお、andor も、返す値をTrueFalse に制限せず、最後に評価した引数を返します。この仕様が便利なときもあります。例えばs が文字列で、空文字列ならデフォルトの値に置き換えたいとき、式sor'foo' は望んだ値を与えます。not は必ず新しい値を作成するので、引数の型に関係なくブール値を返します (例えば、not'foo''' ではなくFalse になります)。

6.12.代入式

assignment_expression ::=  [identifier ":="]expression

An assignment expression (sometimes also called a "named expression" or"walrus") assigns anexpression to anidentifier, while also returning the value of theexpression.

One common use case is when handling matched regular expressions:

ifmatching:=pattern.search(data):do_something(matching)

Or, when processing a file stream in chunks:

whilechunk:=file.read(9000):process(chunk)

Assignment expressions must be surrounded by parentheses whenused as expression statements and when used as sub-expressions inslicing, conditional, lambda,keyword-argument, and comprehension-if expressions andinassert,with, andassignment statements.In all other places where they can be used, parentheses are not required,including inif andwhile statements.

バージョン 3.8 で追加:代入式に関してより詳しくはPEP 572 を参照してください。

6.13.条件式 (Conditional Expressions)

conditional_expression ::=or_test ["if"or_test "else"expression]expression ::=conditional_expression |lambda_expr

条件式 (しばしば "三項演算子" と呼ばれます) は最も優先度が低いPython の演算です。

xifCelsey という式は最初にx ではなく条件C を評価します。C が true の場合x が評価され値が返されます。 それ以外の場合にはy が評価され返されます。

条件演算に関してより詳しくはPEP 308 を参照してください。

6.14.ラムダ (lambda)

lambda_expr ::=  "lambda" [parameter_list] ":"expression

ラムダ式 (ラムダ形式とも呼ばれます) は無名関数を作成するのに使います。式lambdaparameters:expression は関数オブジェクトになります。この無名オブジェクトは以下に定義されている関数オブジェクト同様に動作します:

def <lambda>(parameters):    return expression

引数の一覧の構文は関数定義 を参照してください。ラムダ式で作成された関数は文やアノテーションを含むことができない点に注意してください。

6.15.式のリスト

expression_list ::=expression (","expression)* [","]starred_list ::=starred_item (","starred_item)* [","]starred_expression ::=expression | (starred_item ",")* [starred_item]starred_item ::=assignment_expression | "*"or_expr

リスト表示や辞書表示の一部になっているものを除き、少なくとも一つのカンマを含む式のリストはタプルになります。タプルの長さは、リストにある式の数に等しくなります。式は左から右へ評価されます。

アスタリスク*イテラブルのアンパック を意味します。この被演算子はイテラブル でなければなりません。このイテラブルはアンパックされた位置で要素のシーケンスに展開され、新しいタプル、リスト、集合に入れ込まれます。

バージョン 3.5 で追加:式リストでのイテラブルのアンパックは最初にPEP 448 で提案されました。

A trailing comma is required only to create a one-item tuple,such as1,; it is optional in all other cases.A single expression without atrailing comma doesn't create a tuple, but rather yields the value of thatexpression. (To create an empty tuple, use an empty pair of parentheses:().)

6.16.評価順序

Python は、式を左から右へと順に評価します。ただし、代入式を評価するときは、右辺が左辺よりも先に評価されます。

以下に示す実行文の各行での評価順序は、添え字の数字順序と同じになります:

expr1,expr2,expr3,expr4(expr1,expr2,expr3,expr4){expr1:expr2,expr3:expr4}expr1+expr2*(expr3-expr4)expr1(expr2,expr3,*expr4,**expr5)expr3,expr4=expr1,expr2

6.17.演算子の優先順位

以下の表は Python における演算子の優先順位を要約したものです。優先順位の最も高い (結合が最も強い) ものから最も低い (結合が最も弱い) ものに並べてあります。同じボックス内の演算子の優先順位は同じです。構文が明示的に示されていないものは二項演算子です。同じボックス内の演算子は、左から右へとグループ化されます (例外として、べき乗および条件式は右から左にグループ化されます)。

比較 節で述べられているように、比較、所属、同一性のテストは全てが同じ優先順位を持っていて、左から右に連鎖するという特徴を持っていることに注意してください。

演算子

説明

(expressions...),

[expressions...],{key:value...},{expressions...}

結合式または括弧式、リスト表示、辞書表示、集合表示

x[index],x[index:index],x(arguments...),x.attribute

添字指定、スライス操作、呼び出し、属性参照

awaitx

Await 式

**

べき乗[5]

+x,-x,~x

正数、負数、ビット単位 NOT

*,@,/,//,%

乗算、行列乗算、除算、切り捨て除算、剰余[6]

+,-

加算および減算

<<,>>

シフト演算

&

ビット単位 AND

^

ビット単位 XOR

|

ビット単位 OR

in,notin,is,isnot,<,<=,>,>=,!=,==

所属や同一性のテストを含む比較

notx

ブール演算 NOT

and

ブール演算 AND

or

ブール演算 OR

if --else

条件式

lambda

ラムダ式

:=

代入式

脚注

[1]

abs(x%y)<abs(y) は数学的には真となりますが、浮動小数点に対する演算の場合には、値丸め (roundoff) のために数値計算的に真にならない場合があります。例えば、Python の浮動小数点型が IEEE754 倍精度数型になっているプラットフォームを仮定すると、-1e-100%1e1001e100 と同じ符号になるはずなのに、計算結果は-1e-100+1e100 となります。これは数値計算的には厳密に1e100 と等価です。関数math.fmod() は、最初の引数と符号が一致するような値を返すので、上記の場合には-1e-100 を返します。どちらのアプローチが適切かは、アプリケーションに依存します。

[2]

x が y の正確な整数倍に非常に近いと、丸めのためにx//y(x-x%y)//y よりも 1 だけ大きくなる可能性があります。そのような場合、Python はdivmod(x,y)[0]*y+x%yx に非常に近くなるという関係を保つために、後者の値を返します。

[3]

Unicode 標準では、コードポイント (code point) (例えば、U+0041) と抽象文字 (abstract character) (例えば、"LATIN CAPITAL LETTER A") を区別します。Unicode のほとんどの抽象文字は 1 つのコードポイントだけを使って表現されますが、複数のコードポイントの列を使っても表現できる抽象文字もたくさんあります。例えば、抽象文字 "LATIN CAPITAL LETTER C WITH CEDILLA" はコード位置 U+00C7 にある合成済み文字 (precomposed character) 1 つだけでも表現できますし、コード位置 U+0043 (LATIN CAPITAL LETTER C) にある基底文字 (base character) の後ろに、コード位置 U+0327 (COMBINING CEDILLA) にある結合文字 (combining character) が続く列としても表現できます。

文字列の比較操作は Unicode のコードポイントのレベルで行われます。これは人間にとっては直感的ではないかもしれません。例えば、"\u00C7"=="\u0043\u0327" は、どちらの文字も同じ抽象文字 "LATIN CAPITAL LETTER C WITH CEDILLA" を表現しているにもかかわらず、その結果はFalse となります。

抽象文字のレベルで (つまり、人間にとって直感的な方法で) 文字列を比較するにはunicodedata.normalize() を使ってください。

[4]

自動的なガベージコレクション、フリーリスト、ディスクリプタの動的特性のために、インスタンスメソッドや定数の比較を行うようなときにis 演算子の利用は、一見すると普通ではない振る舞いだと気付くかもしれません。詳細はそれぞれのドキュメントを確認してください。

[5]

べき乗演算子** は、右側にある単項算術演算子あるいは単項ビット演算子より弱い結合優先順位となります。つまり2**-10.5 になります。

[6]

% 演算子は文字列フォーマットにも使われ、同じ優先順位が当てはまります。