%% Generated by Sphinx. \def\sphinxdocclass{ltjsbook} \IfFileExists{luatex85.sty} {\RequirePackage{luatex85}} {\ifdefined\luatexversion\ifnum\luatexversion>84\relax \PackageError{sphinx} {** With this LuaTeX (\the\luatexversion),Sphinx requires luatex85.sty **} {** Add the LaTeX package luatex85 to your TeX installation, and try again **} \endinput\fi\fi} \documentclass[a4paper,10pt]{sphinxmanual} \ifdefined\pdfpxdimen \let\sphinxpxdimen\pdfpxdimen\else\newdimen\sphinxpxdimen \fi \sphinxpxdimen=.75bp\relax %% turn off hyperref patch of \index as sphinx.xdy xindy module takes care of %% suitable \hyperpage mark-up, working around hyperref-xindy incompatibility \PassOptionsToPackage{hyperindex=false}{hyperref} \PassOptionsToPackage{warn}{textcomp} \catcode`^^^^00a0\active\protected\def^^^^00a0{\leavevmode\nobreak\ } \usepackage{cmap} \usepackage{amsmath,amssymb,amstext} \usepackage[Bjarne]{fncychap} \usepackage{sphinx} \fvset{fontsize=\small} \usepackage{geometry} % Include hyperref last. \usepackage{hyperref} % Fix anchor placement for figures with captions. \usepackage{hypcap}% it must be loaded after hyperref. % Set up styles of URL: it should be placed after hyperref. \urlstyle{same} \usepackage{sphinxmessages} \setcounter{tocdepth}{1} \usepackage[noto-otf]{luatexja-preset}\usepackage{newunicodechar}\newunicodechar{^^^^212a}{K}\makeatletter\titleformat{\subsubsection}{\normalsize\py@HeaderFamily}{\py@TitleColor\thesubsubsection}{0.5em}{\py@TitleColor}\titleformat{\paragraph}{\normalsize\py@HeaderFamily}{\py@TitleColor\theparagraph}{0.5em}{\py@TitleColor}\titleformat{\subparagraph}{\normalsize\py@HeaderFamily}{\py@TitleColor\thesubparagraph}{0.5em}{\py@TitleColor}\makeatother\setlength{\footskip}{16.4pt} \title{The Python Language Reference} \date{3月 13, 2023} \release{3.9.16} \author{Guido van Rossum\\and the Python development team} \newcommand{\sphinxlogo}{\vbox{}} \renewcommand{\releasename}{リリース} \makeindex \begin{document} \pagestyle{empty} \sphinxmaketitle \pagestyle{plain} \sphinxtableofcontents \pagestyle{normal} \phantomsection\label{\detokenize{reference/index::doc}} このリファレンスマニュアルでは、Python 言語の文法と、 "コアとなるセマンティクス" について記述します。このマニュアルはそっけない書き方かもしれませんが、正確さと完全さを優先しています。必須でない組み込みオブジェクト型や組み込み関数、組み込みモジュールに関するセマンティクスは、 \DUrole{xref,std,std-ref}{library\sphinxhyphen{}index} で述べられています。形式ばらない Python 言語入門には、 \DUrole{xref,std,std-ref}{tutorial\sphinxhyphen{}index} を参照してください。 C 言語あるいはC++プログラマ向けには、このマニュアルとは別に二つのマニュアルがあります。 \DUrole{xref,std,std-ref}{extending\sphinxhyphen{}index} では、Python 拡張モジュールを書くための高レベルな様式について述べています。また、 \DUrole{xref,std,std-ref}{c\sphinxhyphen{}api\sphinxhyphen{}index} では、C/C++ プログラマが利用できるインターフェースについて詳細に記述しています。 \chapter{はじめに} \label{\detokenize{reference/introduction:introduction}}\label{\detokenize{reference/introduction:id1}}\label{\detokenize{reference/introduction::doc}} このリファレンスマニュアルは、Python プログラミング言語自体に関する記述です。チュートリアルとして書かれたものではありません。 私は本マニュアルをできるだけ正確に書こうとする一方で、文法や字句解析以外の全てについて、形式化された仕様記述ではなく英語を使うことにしました。そうすることで、このドキュメントが平均的な読者にとってより読みやすくなっているはずですが、ややあいまいな部分も残っていることでしょう。従って、もし読者のあなたが火星から来ている人で、このドキュメントだけから Python を再度実装しようとしているのなら、色々と推測しなければならないことがあり、実際にはおそらく全く別の言語を実装する羽目になるでしょう。逆に、あなたが Python を利用しており、Python 言語のある特定の領域において、厳密な規則が何か疑問に思った場合、その答えはこのドキュメントで確実に見つけられることでしょう。もしより形式化された言語定義をお望みなら、あなたの時間を提供していただいてかまいません \sphinxhyphen{}\sphinxhyphen{}\sphinxhyphen{} もしくは、クローン生成装置でも発明してください :\sphinxhyphen{})。 実装に関する詳細を言語リファレンスのドキュメントに載せすぎるのは危険なことです \sphinxhyphen{}\sphinxhyphen{}\sphinxhyphen{} 実装は変更されるかもしれず、同じ言語でも異なる実装は異なった動作をするかもしれないからです。一方、CPython が広く使われている一つの Python 実装 (別の実装も支持され続けていますが) なので、特定のクセについては、特に実装によって何らかの制限が加えられている場合には、触れておく価値があります。従って、このテキスト全体にわたって短い "実装に関する注釈 (imprementation notes)" がちりばめられています。 Python 実装はいずれも、数々の組み込みモジュールと標準モジュールが付属します。それらについては、 \DUrole{xref,std,std-ref}{library\sphinxhyphen{}index} でドキュメント化されています。いくつかの組み込みモジュールについては、言語定義と重要なかかわりをもっているときについて触れています。 \section{別のPythonの実装} \label{\detokenize{reference/introduction:alternate-implementations}}\label{\detokenize{reference/introduction:implementations}} Pythonの実装としては、群を抜いて有名な実装がひとつ存在しています。それ以外の実装に関しても、特定のユーザ間で興味が持たれています。 よく知られている実装には以下のものがあります: \begin{description} \item[{CPython}] \leavevmode これは最も保守されている初代のPython実装で、C言語で書かれています。ほとんどの場合、言語の新機能がいち早く実装されます。 \item[{Jython}] \leavevmode Javaで実装されたPythonです。この実装はJavaアプリケーションのためのスクリプト言語として、もしくはJavaクラスライブラリを使ったアプリケーションを作成するために使用することができます。また、Javaライブラリのテストを作成するためにもしばしば使用されています。さらなる情報については \sphinxhref{http://www.jython.org/}{the Jython website} を参照してください。 \item[{Python for .NET}] \leavevmode この実装は内部ではCPythonを使用していますが、 .NETアプリケーションによって管理されているので、 .NETライブラリを参照することが可能です。この実装はBrian Lloydによって作成されました。さらなる情報については、 \sphinxhref{https://pythonnet.github.io/}{Python for .NET home page} を参照してください。 \item[{IronPython}] \leavevmode .NETでPythonを使用するためのもう一つの実装です。Python.NETとは異なり、完全にILを生成することができるPythonの実装あり、直接Pythonコードを.NETアセンブリにコンパイルします。これはJythonの初代の開発者であるJim Huguninによって作られました。さらなる情報については \sphinxhref{http://ironpython.net/}{the IronPython website} を参照してください。 \item[{PyPy}] \leavevmode 完全にPythonで書かれたPythonの実装です。他の実装には見られない、スタックレスのサポートや、実行時 (Just in Time) コンパイラなどの高度な機能をサポートしています。このプロジェクトの一つの目的は、(Pythonで書かれていることによって、)インタプリタを簡単に修正できるようにして、言語自体での実験を後押しすることです。さらなる情報は \sphinxhref{http://pypy.org/}{the PyPy project's home page} にあります。 \end{description} これらの各実装はこのマニュアルで文書化された言語とは多少異なっている、もしくは、標準のPythonドキュメントと何処が異なっているかを定めた情報が公開されているでしょう。あなたが使用している実装上で、代替手段を使う必要があるかどうかを判断するためには、各実装の仕様書を参照してください。 \section{本マニュアルにおける表記法} \label{\detokenize{reference/introduction:notation}}\label{\detokenize{reference/introduction:id2}} \index{BNF@\spxentry{BNF}}\index{grammar@\spxentry{grammar}}\index{syntax@\spxentry{syntax}}\index{notation@\spxentry{notation}}\ignorespaces 字句解析と構文に関する記述では、BNF 文法記法に手を加えたものを使っています。この記法では、以下のような記述形式をとります: \begin{productionlist} \phantomsection\label{\detokenize{reference/introduction:grammar-token-name}}\production{name}{ {\hyperref[\detokenize{reference/introduction:grammar-token-lc-letter}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{lc\_letter}}}}} ({\hyperref[\detokenize{reference/introduction:grammar-token-lc-letter}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{lc\_letter}}}}} | "\_")*} \phantomsection\label{\detokenize{reference/introduction:grammar-token-lc_letter}}\production{lc\_letter}{ "a"..."z"} \end{productionlist} 最初の行は、\sphinxcode{\sphinxupquote{name}} が \sphinxcode{\sphinxupquote{lc\_letter}} の後ろにゼロ個またはそれ以上の \sphinxcode{\sphinxupquote{lc\_letter}} とアンダースコアが続いたものであることを示しています。そして、\sphinxcode{\sphinxupquote{lc\_letter}} は \sphinxcode{\sphinxupquote{'a'}} から \sphinxcode{\sphinxupquote{'z'}} までの何らかの文字一字であることを示します。 (この規則は、このドキュメントに記述されている字句規則と構文規則において定義されている名前 (name) で一貫して使われています)。 各規則は name (規則によって定義されているものの名前) と \sphinxcode{\sphinxupquote{::=}} から始まります。垂直線 (\sphinxcode{\sphinxupquote{|}}) は、複数の選択項目を分かち書きするときに使います; この記号は、この記法において最も結合優先度の低い演算子です。アスタリスク (\sphinxcode{\sphinxupquote{*}}) は、直前にくる要素のゼロ個以上の繰り返しを表します; 同様に、プラス (\sphinxcode{\sphinxupquote{+}}) は一個以上の繰り返しで、角括弧 (\sphinxcode{\sphinxupquote{{[} {]}}}) に囲われた字句は、字句がゼロ個か一個出現する (別の言い方をすれば、囲いの中の字句はオプションである) ことを示します。\sphinxcode{\sphinxupquote{*}} および \sphinxcode{\sphinxupquote{+}} 演算子の結合範囲は可能な限り狭くなっています; 字句のグループ化には丸括弧を使います。リテラル文字列はクオートで囲われます。空白はトークンを分割しているときのみ意味を持ちます。規則は通常、一行中に収められています; 多数の選択肢のある規則は、最初の行につづいて、垂直線の後ろに各々別の行として記述されます。 \index{lexical definitions@\spxentry{lexical definitions}}\index{ASCII@\spxentry{ASCII}}\ignorespaces (上の例のような) 字句定義では、他に二つの慣習が使われています: 三つのドットで区切られている二つのリテラル文字は、二つの文字の ASCII 文字コードにおける (包含的な) 範囲から文字を一字選ぶことを示します。各カッコ中の字句 (\sphinxcode{\sphinxupquote{<...>}}) は、定義済みのシンボルを記述する非形式的なやりかたです; 例えば、'制御文字' を書き表す必要があるときなどに使われることがあります。 字句と構文規則の定義の間で使われている表記はほとんど同じですが、その意味には大きな違いがあります: 字句定義は入力ソース中の個々の文字を取り扱いますが、構文定義は字句解析で生成された一連のトークンを取り扱います。次節 ("字句解析") における BNF はすべて字句定義のためのものです; それ以降の章では、構文定義のために使っています。 \chapter{字句解析} \label{\detokenize{reference/lexical_analysis:lexical-analysis}}\label{\detokenize{reference/lexical_analysis:lexical}}\label{\detokenize{reference/lexical_analysis::doc}} \index{lexical analysis@\spxentry{lexical analysis}}\index{parser@\spxentry{parser}}\index{token@\spxentry{token}}\ignorespaces Python で書かれたプログラムは \sphinxstyleemphasis{パーザ (parser)} に読み込まれます。パーザへの入力は、 \sphinxstyleemphasis{字句解析器 (lexical analyzer)} によって生成された一連の \sphinxstyleemphasis{トークン (token)} からなります。この章では、字句解析器がファイルをトークン列に分解する方法について解説します。 Python はプログラムテキストを Unicode コードポイントとして読み込みます。ソースファイルのエンコーディングはエンコーディング宣言で与えられ、デフォルトは UTF\sphinxhyphen{}8 です。詳細は \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 3120@\spxentry{PEP 3120}}\sphinxhref{https://www.python.org/dev/peps/pep-3120}{\sphinxstylestrong{PEP 3120}} を参照してください。ソースファイルがデコードできなければ、 \sphinxcode{\sphinxupquote{SyntaxError}} が送出されます。 \section{行構造} \label{\detokenize{reference/lexical_analysis:line-structure}}\label{\detokenize{reference/lexical_analysis:id1}} \index{line structure@\spxentry{line structure}}\ignorespaces Python プログラムは多数の \sphinxstyleemphasis{論理行 (logical lines)} に分割されます。 \subsection{論理行 (logical line)} \label{\detokenize{reference/lexical_analysis:logical-lines}}\label{\detokenize{reference/lexical_analysis:id2}} \index{logical line@\spxentry{logical line}}\index{physical line@\spxentry{physical line}}\index{line joining@\spxentry{line joining}}\index{NEWLINE token@\spxentry{NEWLINE token}}\ignorespaces 論理行の終端は、トークン NEWLINE で表されます。構文上許されている場合 (複合文: compound statement 中の実行文: statement) を除いて、実行文は論理行間にまたがることはできません。論理行は一行またはそれ以上の \sphinxstyleemphasis{物理行(physical line)} からなり、物理行の末尾には明示的または非明示的な \sphinxstyleemphasis{行連結(line joining)} 規則が続きます。 \subsection{物理行 (physical line)} \label{\detokenize{reference/lexical_analysis:physical-lines}}\label{\detokenize{reference/lexical_analysis:id3}} 物理行とは、行終端コードで区切られた文字列のことです。 ソースファイルやソース文字列では、各プラットフォームごとの標準の行終端コードを使用することができます。 Unix形式ではASCII LF (行送り: linefeed)文字、 Windows形式ではASCII 配列の CR LF (復帰: return に続いて行送り) 、 Macintosh形式ではASCII CR (復帰) 文字です。 これら全ての形式のコードは、違うプラットフォームでも等しく使用することができます。 入力の末尾も、最後の物理行の暗黙的な終端としての役割を果たします。 Pythonに埋め込む場合には、標準のC言語の改行文字の変換規則 (ASCII LFを表現した文字コード \sphinxcode{\sphinxupquote{\textbackslash{}n}} が行終端となります) に従って、 Python APIにソースコードを渡す必要があります。 \subsection{コメント (Comments)} \label{\detokenize{reference/lexical_analysis:comments}}\label{\detokenize{reference/lexical_analysis:id4}} \index{comment@\spxentry{comment}}\index{hash character@\spxentry{hash character}}\index{\# (hash)@\spxentry{\#}\spxextra{hash}!comment@\spxentry{comment}}\ignorespaces コメントは文字列リテラル内に入っていないハッシュ文字 (\sphinxcode{\sphinxupquote{\#}}) から始まり、同じ物理行の末端で終わります。 非明示的な行継続規則が適用されていない限り、コメントは論理行を終端させます。 コメントは構文上無視されます。 \subsection{エンコード宣言 (encoding declaration)} \label{\detokenize{reference/lexical_analysis:encoding-declarations}}\label{\detokenize{reference/lexical_analysis:encodings}} \index{source character set@\spxentry{source character set}}\index{encoding declarations (source file)@\spxentry{encoding declarations}\spxextra{source file}}\index{\# (hash)@\spxentry{\#}\spxextra{hash}!source encoding declaration@\spxentry{source encoding declaration}}\ignorespaces Python スクリプト中の一行目か二行目にあるコメントが正規表現 \sphinxcode{\sphinxupquote{coding{[}=:{]}\textbackslash{}s*({[}\sphinxhyphen{}\textbackslash{}w.{]}+)}} にマッチする場合、コメントはエンコード宣言として処理されます; この表現の最初のグループがソースコードファイルのエンコードを指定します。エンコード宣言は自身の行になければなりません。二行目にある場合、一行目もコメントのみの行でなければなりません。エンコード宣言式として推奨する形式は \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{c+c1}{\PYGZsh{} \PYGZhy{}*\PYGZhy{} coding: \PYGZlt{}encoding\PYGZhy{}name\PYGZgt{} \PYGZhy{}*\PYGZhy{}} \end{sphinxVerbatim} これは GNU Emacs で認識できます。または \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{c+c1}{\PYGZsh{} vim:fileencoding=\PYGZlt{}encoding\PYGZhy{}name\PYGZgt{}} \end{sphinxVerbatim} これは、Bram Moolenar による VIM が認識できる形式です。 エンコーディング宣言が見つからなければ、デフォルトのエンコーディングは UTF\sphinxhyphen{}8 です。さらに、ファイルの先頭のバイト列が UTF\sphinxhyphen{}8 バイトオーダ記号 (\sphinxcode{\sphinxupquote{b'\textbackslash{}xef\textbackslash{}xbb\textbackslash{}xbf'}}) なら、ファイルのエンコーディングは UTF\sphinxhyphen{}8 と宣言されているものとします (この機能は Microsoft の \sphinxstyleliteralstrong{\sphinxupquote{notepad}} やその他のエディタでサポートされています)。 If an encoding is declared, the encoding name must be recognized by Python (see \DUrole{xref,std,std-ref}{standard\sphinxhyphen{}encodings}). The encoding is used for all lexical analysis, including string literals, comments and identifiers. \subsection{明示的な行継続} \label{\detokenize{reference/lexical_analysis:explicit-line-joining}}\label{\detokenize{reference/lexical_analysis:explicit-joining}} \index{physical line@\spxentry{physical line}}\index{line joining@\spxentry{line joining}}\index{line continuation@\spxentry{line continuation}}\index{backslash character@\spxentry{backslash character}}\ignorespaces 二つまたはそれ以上の物理行を論理行としてつなげるためには、バックスラッシュ文字 (\sphinxcode{\sphinxupquote{\textbackslash{}}}) を使って以下のようにします: 物理行が文字列リテラルやコメント中の文字でないバックスラッシュで終わっている場合、後続する行とつなげて一つの論理行を構成し、バックスラッシュおよびバックスラッシュの後ろにある行末文字を削除します。例えば: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{if} \PYG{l+m+mi}{1900} \PYG{o}{\PYGZlt{}} \PYG{n}{year} \PYG{o}{\PYGZlt{}} \PYG{l+m+mi}{2100} \PYG{o+ow}{and} \PYG{l+m+mi}{1} \PYG{o}{\PYGZlt{}}\PYG{o}{=} \PYG{n}{month} \PYG{o}{\PYGZlt{}}\PYG{o}{=} \PYG{l+m+mi}{12} \PYGZbs{} \PYG{o+ow}{and} \PYG{l+m+mi}{1} \PYG{o}{\PYGZlt{}}\PYG{o}{=} \PYG{n}{day} \PYG{o}{\PYGZlt{}}\PYG{o}{=} \PYG{l+m+mi}{31} \PYG{o+ow}{and} \PYG{l+m+mi}{0} \PYG{o}{\PYGZlt{}}\PYG{o}{=} \PYG{n}{hour} \PYG{o}{\PYGZlt{}} \PYG{l+m+mi}{24} \PYGZbs{} \PYG{o+ow}{and} \PYG{l+m+mi}{0} \PYG{o}{\PYGZlt{}}\PYG{o}{=} \PYG{n}{minute} \PYG{o}{\PYGZlt{}} \PYG{l+m+mi}{60} \PYG{o+ow}{and} \PYG{l+m+mi}{0} \PYG{o}{\PYGZlt{}}\PYG{o}{=} \PYG{n}{second} \PYG{o}{\PYGZlt{}} \PYG{l+m+mi}{60}\PYG{p}{:} \PYG{c+c1}{\PYGZsh{} Looks like a valid date} \PYG{k}{return} \PYG{l+m+mi}{1} \end{sphinxVerbatim} バックスラッシュで終わる行にはコメントを入れることはできません。また、バックスラッシュを使ってコメントを継続することはできません。バックスラッシュが文字列リテラル中にある場合を除き、バックスラッシュの後ろにトークンを継続することはできません (すなわち、物理行内の文字列リテラル以外のトークンをバックスラッシュを使って分断することはできません)。上記以外の場所では、文字列リテラル外にあるバックスラッシュはどこにあっても不正となります。 \subsection{非明示的な行継続} \label{\detokenize{reference/lexical_analysis:implicit-line-joining}}\label{\detokenize{reference/lexical_analysis:implicit-joining}} 丸括弧 (parentheses)、角括弧 (square bracket) 、および波括弧 (curly brace) 内の式は、バックスラッシュを使わずに一行以上の物理行に分割することができます。例えば: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{month\PYGZus{}names} \PYG{o}{=} \PYG{p}{[}\PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{Januari}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{,} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{Februari}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{,} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{Maart}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{,} \PYG{c+c1}{\PYGZsh{} These are the} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{April}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{,} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{Mei}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{,} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{Juni}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{,} \PYG{c+c1}{\PYGZsh{} Dutch names} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{Juli}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{,} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{Augustus}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{,} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{September}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{,} \PYG{c+c1}{\PYGZsh{} for the months} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{Oktober}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{,} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{November}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{,} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{December}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{]} \PYG{c+c1}{\PYGZsh{} of the year} \end{sphinxVerbatim} 非明示的に継続された行にはコメントを含めることができます。継続行のインデントは重要ではありません。空の継続行を書くことができます。非明示的な継続行中には、NEWLINE トークンは存在しません。非明示的な行の継続は、三重クオートされた文字列 (下記参照) でも発生します; この場合には、コメントを含めることができません。 \subsection{空行} \label{\detokenize{reference/lexical_analysis:blank-lines}}\label{\detokenize{reference/lexical_analysis:id5}} \index{blank line@\spxentry{blank line}}\ignorespaces スペース、タブ、フォームフィード、およびコメントのみを含む論理行は無視されます (すなわち、NEWLINE トークンは生成されません)。文を対話的に入力している際には、空行の扱いは行読み込み\sphinxhyphen{}評価\sphinxhyphen{}出力 (read\sphinxhyphen{}eval\sphinxhyphen{}print) ループの実装によって異なることがあります。標準的な対話的インタプリタの実装では、完全な空行でできた論理行 (すなわち、空白文字もコメントも全く含まない空行) は、複数行からなる文の終端を示します。 \subsection{インデント} \label{\detokenize{reference/lexical_analysis:indentation}}\label{\detokenize{reference/lexical_analysis:id6}} \index{indentation@\spxentry{indentation}}\index{leading whitespace@\spxentry{leading whitespace}}\index{space@\spxentry{space}}\index{tab@\spxentry{tab}}\index{grouping@\spxentry{grouping}}\index{statement grouping@\spxentry{statement grouping}}\ignorespaces 論理行の行頭にある、先頭の空白 (スペースおよびタブ) の連なりは、その行のインデントレベルを計算するために使われます。インデントレベルは、実行文のグループ化方法を決定するために用いられます。 タブは (左から右の方向に) 1 つにつき 8 つのスペースで置き換えられ、置き換え後の文字数は 8 の倍数になります (Unix で使われている規則と同じになるよう意図されています)。そして、最初の非空白文字までのスペースの総数が、その行のインデントを決定します。インデントは、バックスラッシュで複数の物理行に分割できません; 最初のバックスラッシュまでの空白がインデントを決定します。 ソースファイルがタブとスペースを混在させ、その意味づけがタブのスペース換算数に依存するようなら、インデントは不合理なものとして却下されます。その場合は \sphinxcode{\sphinxupquote{TabError}} が送出されます。 \sphinxstylestrong{プラットフォーム間の互換性に関する注意:} 非 UNIX プラットフォームにおけるテキストエディタの性質上、一つのソースファイル内でタブとインデントを混在させて使うのは賢明ではありません。また、プラットフォームによっては、最大インデントレベルを明示的に制限しているかもしれません。 フォームフィード文字が行の先頭にあっても構いません; フォームフィード文字は上のインデントレベル計算時には無視されます。フォームフィード文字が先頭の空白中の他の場所にある場合、その影響は未定義です (例えば、スペースの数を 0 にリセットするかもしれません)。 \index{INDENT token@\spxentry{INDENT token}}\index{DEDENT token@\spxentry{DEDENT token}}\ignorespaces 連続する行における各々のインデントレベルは、 INDENT および DEDENT トークンを生成するために使われます。トークンの生成はスタックを用いて以下のように行われます。 ファイル中の最初の行を読み出す前に、スタックにゼロが一つ積まれ (push され) ます; このゼロは決して除去 (pop) されることはありません。スタックの先頭に積まれてゆく数字は、常にスタックの末尾から先頭にかけて厳密に増加するようになっています。各論理行の開始位置において、その行のインデントレベル値がスタックの先頭の値と比較されます。値が等しければ何もしません。インデントレベル値がスタック上の値よりも大きければ、インデントレベル値はスタックに積まれ、INDENT トークンが一つ生成されます。インデントレベル値がスタック上の値よりも小さい場合、その値はスタック内のいずれかの値と \sphinxstyleemphasis{等しくなければなりません} ; スタック上のインデントレベル値よりも大きい値はすべて除去され、値が一つ除去されるごとに DEDENT トークンが一つ生成されます。ファイルの末尾では、スタックに残っているゼロより大きい値は全て除去され、値が一つ除去されるごとに DEDENT トークンが一つ生成されます。 以下の例に正しく (しかし当惑させるように) インデントされた Python コードの一部を示します: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{def} \PYG{n+nf}{perm}\PYG{p}{(}\PYG{n}{l}\PYG{p}{)}\PYG{p}{:} \PYG{c+c1}{\PYGZsh{} Compute the list of all permutations of l} \PYG{k}{if} \PYG{n+nb}{len}\PYG{p}{(}\PYG{n}{l}\PYG{p}{)} \PYG{o}{\PYGZlt{}}\PYG{o}{=} \PYG{l+m+mi}{1}\PYG{p}{:} \PYG{k}{return} \PYG{p}{[}\PYG{n}{l}\PYG{p}{]} \PYG{n}{r} \PYG{o}{=} \PYG{p}{[}\PYG{p}{]} \PYG{k}{for} \PYG{n}{i} \PYG{o+ow}{in} \PYG{n+nb}{range}\PYG{p}{(}\PYG{n+nb}{len}\PYG{p}{(}\PYG{n}{l}\PYG{p}{)}\PYG{p}{)}\PYG{p}{:} \PYG{n}{s} \PYG{o}{=} \PYG{n}{l}\PYG{p}{[}\PYG{p}{:}\PYG{n}{i}\PYG{p}{]} \PYG{o}{+} \PYG{n}{l}\PYG{p}{[}\PYG{n}{i}\PYG{o}{+}\PYG{l+m+mi}{1}\PYG{p}{:}\PYG{p}{]} \PYG{n}{p} \PYG{o}{=} \PYG{n}{perm}\PYG{p}{(}\PYG{n}{s}\PYG{p}{)} \PYG{k}{for} \PYG{n}{x} \PYG{o+ow}{in} \PYG{n}{p}\PYG{p}{:} \PYG{n}{r}\PYG{o}{.}\PYG{n}{append}\PYG{p}{(}\PYG{n}{l}\PYG{p}{[}\PYG{n}{i}\PYG{p}{:}\PYG{n}{i}\PYG{o}{+}\PYG{l+m+mi}{1}\PYG{p}{]} \PYG{o}{+} \PYG{n}{x}\PYG{p}{)} \PYG{k}{return} \PYG{n}{r} \end{sphinxVerbatim} 以下の例は、様々なインデントエラーになります: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{def} \PYG{n+nf}{perm}\PYG{p}{(}\PYG{n}{l}\PYG{p}{)}\PYG{p}{:} \PYG{c+c1}{\PYGZsh{} error: first line indented} \PYG{k}{for} \PYG{n}{i} \PYG{o+ow}{in} \PYG{n+nb}{range}\PYG{p}{(}\PYG{n+nb}{len}\PYG{p}{(}\PYG{n}{l}\PYG{p}{)}\PYG{p}{)}\PYG{p}{:} \PYG{c+c1}{\PYGZsh{} error: not indented} \PYG{n}{s} \PYG{o}{=} \PYG{n}{l}\PYG{p}{[}\PYG{p}{:}\PYG{n}{i}\PYG{p}{]} \PYG{o}{+} \PYG{n}{l}\PYG{p}{[}\PYG{n}{i}\PYG{o}{+}\PYG{l+m+mi}{1}\PYG{p}{:}\PYG{p}{]} \PYG{n}{p} \PYG{o}{=} \PYG{n}{perm}\PYG{p}{(}\PYG{n}{l}\PYG{p}{[}\PYG{p}{:}\PYG{n}{i}\PYG{p}{]} \PYG{o}{+} \PYG{n}{l}\PYG{p}{[}\PYG{n}{i}\PYG{o}{+}\PYG{l+m+mi}{1}\PYG{p}{:}\PYG{p}{]}\PYG{p}{)} \PYG{c+c1}{\PYGZsh{} error: unexpected indent} \PYG{k}{for} \PYG{n}{x} \PYG{o+ow}{in} \PYG{n}{p}\PYG{p}{:} \PYG{n}{r}\PYG{o}{.}\PYG{n}{append}\PYG{p}{(}\PYG{n}{l}\PYG{p}{[}\PYG{n}{i}\PYG{p}{:}\PYG{n}{i}\PYG{o}{+}\PYG{l+m+mi}{1}\PYG{p}{]} \PYG{o}{+} \PYG{n}{x}\PYG{p}{)} \PYG{k}{return} \PYG{n}{r} \PYG{c+c1}{\PYGZsh{} error: inconsistent dedent} \end{sphinxVerbatim} (実際は、最初の 3 つのエラーはパーザによって検出されます; 最後のエラーのみが字句解析器で見つかります \sphinxhyphen{}\sphinxhyphen{}\sphinxhyphen{} \sphinxcode{\sphinxupquote{return r}} のインデントは、スタックから逐次除去されていくどのインデントレベル値とも一致しません) \subsection{トークン間の空白} \label{\detokenize{reference/lexical_analysis:whitespace-between-tokens}}\label{\detokenize{reference/lexical_analysis:whitespace}} 論理行の先頭や文字列の内部にある場合を除き、空白文字であるスペース、タブ、およびフォームフィードは、トークンを分割するために自由に利用することができます。二つのトークンを並べて書くと別のトークンとしてみなされてしまうような場合には、トークンの間に空白が必要となります (例えば、ab は一つのトークンですが、 a b は二つのトークンとなります)。 \section{その他のトークン} \label{\detokenize{reference/lexical_analysis:other-tokens}}\label{\detokenize{reference/lexical_analysis:id7}} NEWLINE、INDENT、および DEDENT の他、以下のトークンのカテゴリ: \sphinxstyleemphasis{識別子 (identifier)}, \sphinxstyleemphasis{キーワード(keyword)}, \sphinxstyleemphasis{リテラル}, \sphinxstyleemphasis{演算子 (operator)}, \sphinxstyleemphasis{デリミタ (delimiter)} が存在します。空白文字 (上で述べた行終端文字以外) はトークンではありませんが、トークンを区切る働きがあります。トークンの解析にあいまいさが生じた場合、トークンは左から右に読んで不正でないトークンを構築できる最長の文字列を含むように構築されます。 \section{識別子 (identifier) およびキーワード (keyword)} \label{\detokenize{reference/lexical_analysis:identifiers}}\label{\detokenize{reference/lexical_analysis:identifiers-and-keywords}} \index{identifier@\spxentry{identifier}}\index{name@\spxentry{name}}\ignorespaces 識別子 (または \sphinxstyleemphasis{名前 (name)}) は、以下の字句定義で記述されます。 Python における識別子の構文は、Unicode 標準仕様添付書類 UAX\sphinxhyphen{}31 に基づき、詳細と変更点は以下で定義します。詳しくは \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 3131@\spxentry{PEP 3131}}\sphinxhref{https://www.python.org/dev/peps/pep-3131}{\sphinxstylestrong{PEP 3131}} を参照してください。 ASCII 範囲 (U+0001..U+007F) 内では、識別子として有効な文字は Python 2.x におけるものと同じです。大文字と小文字の \sphinxcode{\sphinxupquote{A}} から \sphinxcode{\sphinxupquote{Z}}、アンダースコア \sphinxcode{\sphinxupquote{\_}}、先頭の文字を除く数字 \sphinxcode{\sphinxupquote{0}} から \sphinxcode{\sphinxupquote{9}} です。 Python 3.0 は、さらに ASCII 範囲外から文字を導入します (\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 3131@\spxentry{PEP 3131}}\sphinxhref{https://www.python.org/dev/peps/pep-3131}{\sphinxstylestrong{PEP 3131}} を参照してください。)。これらの文字については、分類は \sphinxcode{\sphinxupquote{unicodedata}} モジュールに含まれる Unicode Character Database の版を使います。 識別子の長さには制限がありません。大小文字は区別されます。 \begin{productionlist} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-identifier}}\production{identifier}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-xid-start}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{xid\_start}}}}} {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-xid-continue}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{xid\_continue}}}}}*} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-id_start}}\production{id\_start}{ } \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-id_continue}}\production{id\_continue}{ } \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-xid_start}}\production{xid\_start}{ } \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-xid_continue}}\production{xid\_continue}{ } \end{productionlist} 上で言及した Unicode カテゴリコードは以下を表します: \begin{itemize} \item {} \sphinxstyleemphasis{Lu} \sphinxhyphen{} 大文字 (uppercase letters) \item {} \sphinxstyleemphasis{Ll} \sphinxhyphen{} 小文字 (lowercase letters) \item {} \sphinxstyleemphasis{Lt} \sphinxhyphen{} 先頭が大文字 (titlecase letters) \item {} \sphinxstyleemphasis{Lm} \sphinxhyphen{} 修飾文字 (modifier letters) \item {} \sphinxstyleemphasis{Lo} \sphinxhyphen{} その他の文字 (other letters) \item {} \sphinxstyleemphasis{Nl} \sphinxhyphen{} 数値を表す文字 (letter numbers) \item {} \sphinxstyleemphasis{Mn} \sphinxhyphen{} 字幅のない記号 (nonspacing marks) \item {} \sphinxstyleemphasis{Mc} \sphinxhyphen{} 字幅のある結合記号 (spacing combining marks) \item {} \sphinxstyleemphasis{Nd} \sphinxhyphen{} 10 進数字 (decimal numbers) \item {} \sphinxstyleemphasis{Pc} \sphinxhyphen{} 連結用句読記号 (connector punctuations) \item {} \sphinxstyleemphasis{Other\_ID\_Start} \sphinxhyphen{} \sphinxhref{https://www.unicode.org/Public/13.0.0/ucd/PropList.txt}{PropList.txt} にある、後方互換性をサポートするための明示的な文字のリスト \item {} \sphinxstyleemphasis{Other\_ID\_Continue} \sphinxhyphen{} 同様 \end{itemize} すべての識別子は、解析中は正規化形式 NFKC に変換されます。識別子間の比較は NFKC に基づきます。 識別子として有効なすべての Unicode 4.1 の文字を列挙した参考 HTML ファイルが \sphinxurl{https://www.unicode.org/Public/13.0.0/ucd/DerivedCoreProperties.txt} にあります。 \subsection{キーワード (keyword)} \label{\detokenize{reference/lexical_analysis:keywords}}\label{\detokenize{reference/lexical_analysis:id8}} \index{keyword@\spxentry{keyword}}\index{reserved word@\spxentry{reserved word}}\ignorespaces 以下の識別子は、予約語、または Python 言語における \sphinxstyleemphasis{キーワード (keyword)} として使われ、通常の識別子として使うことはできません。キーワードは厳密に下記の通りに綴らなければなりません: \begin{sphinxVerbatim}[commandchars=\\\{\}] False await else import pass None break except in raise True class finally is return and continue for lambda try as def from nonlocal while assert del global not with async elif if or yield \end{sphinxVerbatim} \index{\_, identifiers@\spxentry{\_, identifiers}}\index{\_\_, identifiers@\spxentry{\_\_, identifiers}}\ignorespaces \subsection{予約済みの識別子種 (reserved classes of identifiers)} \label{\detokenize{reference/lexical_analysis:reserved-classes-of-identifiers}}\label{\detokenize{reference/lexical_analysis:id-classes}}\label{\detokenize{reference/lexical_analysis:index-14}} ある種の (キーワードを除く) 識別子には、特殊な意味があります。これらの識別子種は、先頭や末尾にあるアンダースコア文字のパターンで区別されます: \begin{description} \item[{\sphinxcode{\sphinxupquote{\_*}}}] \leavevmode \sphinxcode{\sphinxupquote{from module import *}} で import されません。対話インタプリタでは、直前に行われた評価の結果を記憶するために特殊な識別子 \sphinxcode{\sphinxupquote{\_}} が使われます; この識別子は \sphinxcode{\sphinxupquote{builtins}} モジュール内に記憶されます。対話モードでないとき、 \sphinxcode{\sphinxupquote{\_}} に特別な意味はなく、定義されていません。 {\hyperref[\detokenize{reference/simple_stmts:import}]{\sphinxcrossref{\DUrole{std,std-ref}{import 文}}}} を参照してください。 \begin{sphinxadmonition}{note}{注釈:} 名前 \sphinxcode{\sphinxupquote{\_}} は、しばしば国際化 (internationalization) と共に用いられます; この慣習についての詳しい情報は、 \sphinxcode{\sphinxupquote{gettext}} を参照してください。 \end{sphinxadmonition} \item[{\sphinxcode{\sphinxupquote{\_\_*\_\_}}}] \leavevmode システムで定義された (system\sphinxhyphen{}defined) 名前です。非公式には"dunder"な名前と呼ばれます(訳注: double underscoresの略)。これらの名前はインタープリタと (標準ライブラリを含む) 実装上で定義されています。 現行のシステムでの名前は {\hyperref[\detokenize{reference/datamodel:specialnames}]{\sphinxcrossref{\DUrole{std,std-ref}{特殊メソッド名}}}} などで話題に挙げられています。 Python の将来のバージョンではより多くの名前が定義されることになります。このドキュメントで明記されている用法に従わない、 \sphinxstyleemphasis{あらゆる} \sphinxcode{\sphinxupquote{\_\_*\_\_}} の名前は、いかなるコンテキストにおける利用でも、警告無く損害を引き起こすことがあります。 \item[{\sphinxcode{\sphinxupquote{\_\_*}}}] \leavevmode クラスプライベート (class\sphinxhyphen{}private) な名前です。このカテゴリに属する名前は、クラス定義のコンテキスト上で用いられた場合、基底クラスと派生クラスの "プライベートな" 属性間で名前衝突が起こるのを防ぐために書き直されます。 {\hyperref[\detokenize{reference/expressions:atom-identifiers}]{\sphinxcrossref{\DUrole{std,std-ref}{識別子 (identifier、または名前 (name))}}}} を参照してください。 \end{description} \section{リテラル} \label{\detokenize{reference/lexical_analysis:literals}}\label{\detokenize{reference/lexical_analysis:id9}} \index{literal@\spxentry{literal}}\index{constant@\spxentry{constant}}\ignorespaces リテラル (literal) とは、いくつかの組み込み型の定数を表記したものです。 \index{string literal@\spxentry{string literal}}\index{bytes literal@\spxentry{bytes literal}}\index{ASCII@\spxentry{ASCII}}\index{' (single quote)@\spxentry{'}\spxextra{single quote}!string literal@\spxentry{string literal}}\index{"" (double quote)@\spxentry{""}\spxextra{double quote}!string literal@\spxentry{string literal}}\index{u'@\spxentry{u'}!string literal@\spxentry{string literal}}\index{u""@\spxentry{u""}!string literal@\spxentry{string literal}}\ignorespaces \subsection{文字列およびバイト列リテラル} \label{\detokenize{reference/lexical_analysis:string-and-bytes-literals}}\label{\detokenize{reference/lexical_analysis:strings}}\label{\detokenize{reference/lexical_analysis:index-16}} 文字列リテラルは以下の字句定義で記述されます: \begin{productionlist} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-stringliteral}}\production{stringliteral}{ {[}{\hyperref[\detokenize{reference/lexical_analysis:grammar-token-stringprefix}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{stringprefix}}}}}{]}({\hyperref[\detokenize{reference/lexical_analysis:grammar-token-shortstring}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{shortstring}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-longstring}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{longstring}}}}})} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-stringprefix}}\production{stringprefix}{ "r" | "u" | "R" | "U" | "f" | "F"} \productioncont{ | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-shortstring}}\production{shortstring}{ "'" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-shortstringitem}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{shortstringitem}}}}}* "'" | '"' {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-shortstringitem}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{shortstringitem}}}}}* '"'} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-longstring}}\production{longstring}{ "'''" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-longstringitem}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{longstringitem}}}}}* "'''" | '"""' {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-longstringitem}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{longstringitem}}}}}* '"""'} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-shortstringitem}}\production{shortstringitem}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-shortstringchar}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{shortstringchar}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-stringescapeseq}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{stringescapeseq}}}}}} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-longstringitem}}\production{longstringitem}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-longstringchar}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{longstringchar}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-stringescapeseq}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{stringescapeseq}}}}}} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-shortstringchar}}\production{shortstringchar}{ } \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-longstringchar}}\production{longstringchar}{ } \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-stringescapeseq}}\production{stringescapeseq}{ "\textbackslash{}" } \end{productionlist} \begin{productionlist} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-bytesliteral}}\production{bytesliteral}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-bytesprefix}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{bytesprefix}}}}}({\hyperref[\detokenize{reference/lexical_analysis:grammar-token-shortbytes}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{shortbytes}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-longbytes}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{longbytes}}}}})} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-bytesprefix}}\production{bytesprefix}{ "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-shortbytes}}\production{shortbytes}{ "'" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-shortbytesitem}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{shortbytesitem}}}}}* "'" | '"' {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-shortbytesitem}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{shortbytesitem}}}}}* '"'} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-longbytes}}\production{longbytes}{ "'''" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-longbytesitem}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{longbytesitem}}}}}* "'''" | '"""' {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-longbytesitem}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{longbytesitem}}}}}* '"""'} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-shortbytesitem}}\production{shortbytesitem}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-shortbyteschar}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{shortbyteschar}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-bytesescapeseq}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{bytesescapeseq}}}}}} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-longbytesitem}}\production{longbytesitem}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-longbyteschar}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{longbyteschar}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-bytesescapeseq}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{bytesescapeseq}}}}}} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-shortbyteschar}}\production{shortbyteschar}{ } \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-longbyteschar}}\production{longbyteschar}{ } \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-bytesescapeseq}}\production{bytesescapeseq}{ "\textbackslash{}" } \end{productionlist} 上記の生成規則で示されていない文法的な制限が一つあります。リテラルの {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-stringprefix}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{stringprefix}}}}} や {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-bytesprefix}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{bytesprefix}}}}} と残りの部分の間に空白を入れてはならないことです。ソースコード文字セット (source character set) はエンコーディング宣言で定義されます。エンコーディング宣言がなければ UTF\sphinxhyphen{}8 です。節 {\hyperref[\detokenize{reference/lexical_analysis:encodings}]{\sphinxcrossref{\DUrole{std,std-ref}{エンコード宣言 (encoding declaration)}}}} を参照してください。 \index{triple\sphinxhyphen{}quoted string@\spxentry{triple\sphinxhyphen{}quoted string}}\index{Unicode Consortium@\spxentry{Unicode Consortium}}\index{raw string@\spxentry{raw string}}\index{""""""@\spxentry{""""""}!string literal@\spxentry{string literal}}\index{'''@\spxentry{'''}!string literal@\spxentry{string literal}}\ignorespaces In plain English: Both types of literals can be enclosed in matching single quotes (\sphinxcode{\sphinxupquote{'}}) or double quotes (\sphinxcode{\sphinxupquote{"}}). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as \sphinxstyleemphasis{triple\sphinxhyphen{}quoted strings}). The backslash (\sphinxcode{\sphinxupquote{\textbackslash{}}}) character is used to give special meaning to otherwise ordinary characters like \sphinxcode{\sphinxupquote{n}}, which means 'newline' when escaped (\sphinxcode{\sphinxupquote{\textbackslash{}n}}). It can also be used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. See {\hyperref[\detokenize{reference/lexical_analysis:escape-sequences}]{\sphinxcrossref{\DUrole{std,std-ref}{escape sequences}}}} below for examples. \index{b'@\spxentry{b'}!bytes literal@\spxentry{bytes literal}}\index{b""@\spxentry{b""}!bytes literal@\spxentry{bytes literal}}\ignorespaces バイト列リテラルには、常に \sphinxcode{\sphinxupquote{'b'}} や \sphinxcode{\sphinxupquote{'B'}} が接頭します。これらによって、 \sphinxcode{\sphinxupquote{str}} 型ではなく \sphinxcode{\sphinxupquote{bytes}} 型のインスタンスが作成されます。バイト列リテラルは ASCII 文字のみ含むことができます。 128 以上の数値を持つバイトはエスケープして表されなければなりません。 \index{r'@\spxentry{r'}!raw string literal@\spxentry{raw string literal}}\index{r""@\spxentry{r""}!raw string literal@\spxentry{raw string literal}}\ignorespaces 文字列リテラルとバイト列リテラルの両方は、任意で文字 \sphinxcode{\sphinxupquote{'r'}} または \sphinxcode{\sphinxupquote{'R'}} をプレフィックスに持つことができます; そのような文字列は \sphinxstyleemphasis{raw strings} と呼ばれ、バックスラッシュをリテラル文字として扱います。その結果、文字列リテラルでは raw 文字列中の \sphinxcode{\sphinxupquote{'\textbackslash{}U'}} と \sphinxcode{\sphinxupquote{'\textbackslash{}u'}} のエスケープは特別扱いされません。 Python 2.x の raw unicode リテラルが Python 3.x とは異なる振る舞いをするため、 \sphinxcode{\sphinxupquote{'ur'}} 構文はサポートされません。 \DUrole{versionmodified,added}{バージョン 3.3 で追加: }raw バイト列リテラルの \sphinxcode{\sphinxupquote{'rb'}} プレフィックスが \sphinxcode{\sphinxupquote{'br'}} の同義語として追加されました。 \DUrole{versionmodified,added}{バージョン 3.3 で追加: }Python 2.x と 3.x 両対応のコードベースのメンテナンスを単純化するために、レガシー unicode リテラル (\sphinxcode{\sphinxupquote{u'value'}}) のサポートが再び導入されました。詳細は \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 414@\spxentry{PEP 414}}\sphinxhref{https://www.python.org/dev/peps/pep-0414}{\sphinxstylestrong{PEP 414}} を参照してください。 \index{f'@\spxentry{f'}!formatted string literal@\spxentry{formatted string literal}}\index{f""@\spxentry{f""}!formatted string literal@\spxentry{formatted string literal}}\ignorespaces \sphinxcode{\sphinxupquote{'f'}} または \sphinxcode{\sphinxupquote{'F'}} の接頭辞が付いた文字列リテラルはフォーマット済み文字列リテラル( \sphinxstyleemphasis{formatted string literal} )です。詳細については {\hyperref[\detokenize{reference/lexical_analysis:f-strings}]{\sphinxcrossref{\DUrole{std,std-ref}{フォーマット済み文字列リテラル}}}} を参照してください。接頭辞の \sphinxcode{\sphinxupquote{'f'}} は \sphinxcode{\sphinxupquote{'r'}} と組み合わせられますが、 \sphinxcode{\sphinxupquote{'b'}} や \sphinxcode{\sphinxupquote{'u'}} と組み合わせることはできません。つまりフォーマット済みの raw 文字列リテラルは可ですが、フォーマット済みのバイト列リテラルは不可です。 三重クオートリテラル中には、三連のエスケープされないクオート文字でリテラルを終端してしまわないかぎり、エスケープされていない改行やクオートを書くことができます (さらに、それらはそのまま文字列中に残ります)。(ここでいう "クオート" とは、文字列の囲みを開始するときに使った文字を示し、\sphinxcode{\sphinxupquote{'}} か \sphinxcode{\sphinxupquote{"}} のいずれかです。) \index{physical line@\spxentry{physical line}}\index{escape sequence@\spxentry{escape sequence}}\index{Standard C@\spxentry{Standard C}}\index{C@\spxentry{C}}\index{\textbackslash{} (backslash)@\spxentry{\textbackslash{}}\spxextra{backslash}!escape sequence@\spxentry{escape sequence}}\index{\textbackslash{}\textbackslash{}@\spxentry{\textbackslash{}\textbackslash{}}!escape sequence@\spxentry{escape sequence}}\index{\textbackslash{}a@\spxentry{\textbackslash{}a}!escape sequence@\spxentry{escape sequence}}\index{\textbackslash{}b@\spxentry{\textbackslash{}b}!escape sequence@\spxentry{escape sequence}}\index{\textbackslash{}f@\spxentry{\textbackslash{}f}!escape sequence@\spxentry{escape sequence}}\index{\textbackslash{}n@\spxentry{\textbackslash{}n}!escape sequence@\spxentry{escape sequence}}\index{\textbackslash{}r@\spxentry{\textbackslash{}r}!escape sequence@\spxentry{escape sequence}}\index{\textbackslash{}t@\spxentry{\textbackslash{}t}!escape sequence@\spxentry{escape sequence}}\index{\textbackslash{}v@\spxentry{\textbackslash{}v}!escape sequence@\spxentry{escape sequence}}\index{\textbackslash{}x@\spxentry{\textbackslash{}x}!escape sequence@\spxentry{escape sequence}}\index{\textbackslash{}N@\spxentry{\textbackslash{}N}!escape sequence@\spxentry{escape sequence}}\index{\textbackslash{}u@\spxentry{\textbackslash{}u}!escape sequence@\spxentry{escape sequence}}\index{\textbackslash{}U@\spxentry{\textbackslash{}U}!escape sequence@\spxentry{escape sequence}}\ignorespaces \phantomsection\label{\detokenize{reference/lexical_analysis:escape-sequences}} \sphinxcode{\sphinxupquote{'r'}} または \sphinxcode{\sphinxupquote{'R'}} 接頭文字がつかないかぎり、文字列またはバイト列リテラル中のエスケープシーケンスは標準 C で使われているのと同様の法則にしたがって解釈されます。以下に Python で認識されるエスケープシーケンスを示します: \begin{savenotes}\sphinxattablestart \centering \begin{tabulary}{\linewidth}[t]{|T|T|T|} \hline \sphinxstyletheadfamily エスケープシーケンス &\sphinxstyletheadfamily 意味 &\sphinxstyletheadfamily 注釈 \\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}newline}} & バックスラッシュと改行文字が無視されます &\\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}\textbackslash{}}} & バックスラッシュ (\sphinxcode{\sphinxupquote{\textbackslash{}}}) &\\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}'}} & 一重引用符 (\sphinxcode{\sphinxupquote{'}}) &\\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}"}} & 二重引用符 (\sphinxcode{\sphinxupquote{"}}) &\\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}a}} & ASCII 端末ベル (BEL) &\\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}b}} & ASCII バックスペース (BS) &\\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}f}} & ASCII フォームフィード (FF) &\\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}n}} & ASCII 行送り (LF) &\\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}r}} & ASCII 復帰 (CR) &\\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}t}} & ASCII 水平タブ (TAB) &\\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}v}} & ASCII 垂直タブ (VT) &\\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}ooo}} & 8 進数値 \sphinxstyleemphasis{ooo} を持つ文字 & (1,3) \\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}xhh}} & 16 進数値 \sphinxstyleemphasis{hh} を持つ文字 & (2,3) \\ \hline \end{tabulary} \par \sphinxattableend\end{savenotes} 文字列でのみ認識されるエスケープシーケンスは以下のとおりです: \begin{savenotes}\sphinxattablestart \centering \begin{tabulary}{\linewidth}[t]{|T|T|T|} \hline \sphinxstyletheadfamily エスケープシーケンス &\sphinxstyletheadfamily 意味 &\sphinxstyletheadfamily 注釈 \\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}N\{name\}}} & Unicode データベース中で \sphinxstyleemphasis{name} という名前の文字 & (4) \\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}uxxxx}} & 16\sphinxhyphen{}bit の十六進値 \sphinxstyleemphasis{xxxx} を持つ文字 & (5) \\ \hline \sphinxcode{\sphinxupquote{\textbackslash{}Uxxxxxxxx}} & 32\sphinxhyphen{}bit の十六進値 \sphinxstyleemphasis{xxxxxxxx} を持つ文字 & (6) \\ \hline \end{tabulary} \par \sphinxattableend\end{savenotes} 注釈: \begin{enumerate} \sphinxsetlistlabels{\arabic}{enumi}{enumii}{(}{)}% \item {} 標準 C と同じく、最大で 3 桁の 8 進数まで受理します。 \item {} 標準 C とは違い、ちょうど 2 桁の 16 進数しか受理されません。 \item {} バイト列リテラル中では、十六進および八進エスケープは与えられた値のバイトを表します。文字列リテラル中では、エスケープ文字は与えられた値を持つ Unicode 文字を表します。 \item {} \DUrole{versionmodified,changed}{バージョン 3.3 で変更: }name aliases % \begin{footnote}[1]\sphinxAtStartFootnote \sphinxurl{https://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt} % \end{footnote} に対するサポートが追加されました。 \item {} ちょうど 4 桁の 16 進数しか受理されません。 \item {} あらゆるユニコード文字はこのようにしてエンコードすることができます。正確に8文字の16進数字が必要です。 \end{enumerate} \index{unrecognized escape sequence@\spxentry{unrecognized escape sequence}}\ignorespaces 標準の C とは違い、認識されなかったエスケープシーケンスはすべて、そのまま文字列中に残ります。すなわち、\sphinxstyleemphasis{バックスラッシュも結果中に残ります}。(この挙動はデバッグの際に便利です: エスケープシーケンスが誤入力されたら、その出力結果が失敗しているのが分かりやすくなります。) 文字列中でのみ認識されるエスケープシーケンスは、バイト列リテラルには、認識されないエスケープシーケンスとして分類されるので注意してください。 \begin{quote} \DUrole{versionmodified,changed}{バージョン 3.6 で変更: }認識されなかったエスケープシーケンスは \sphinxcode{\sphinxupquote{DeprecationWarning}} を生成します。これは将来のバージョンでは \sphinxcode{\sphinxupquote{SyntaxWarning}} になり、いずれ \sphinxcode{\sphinxupquote{SyntaxError}} になります。 \end{quote} raw リテラルでも、引用符はバックスラッシュでエスケープできますが、バックスラッシュ自体も文字列に残ります; 例えば、\sphinxcode{\sphinxupquote{r"\textbackslash{}""}} は有効な文字列リテラルで、バックスラッシュと二重引用符からなる文字列を表します; \sphinxcode{\sphinxupquote{r"\textbackslash{}"}} は無効な文字列リテラルです (raw リテラルを奇数個連なったバックスラッシュで終わらせることはできません)。具体的には、(バックスラッシュが直後のクオート文字をエスケープしてしまうので) \sphinxstyleemphasis{raw文字列を単一のバックスラッシュで終わらせることはできません} さらに、バックスラッシュの直後に改行がきても、行継続を意味する \sphinxstyleemphasis{のではなく}、リテラルの一部であるそれら二つの文字として解釈されます。 \subsection{文字列リテラルの結合 (concatenation)} \label{\detokenize{reference/lexical_analysis:string-literal-concatenation}}\label{\detokenize{reference/lexical_analysis:string-concatenation}} 文字列やバイト列リテラルは、互いに異なる引用符を使っていても (空白文字で区切っても) 複数隣接させることができます。これは各々の文字列を結合するのと同じ意味を持ちます。したがって、\sphinxcode{\sphinxupquote{"hello" 'world'}} は \sphinxcode{\sphinxupquote{"helloworld"}} と同じです。この機能を使うと、バックスラッシュを減らしたり、長い文字列を手軽に分離して複数行にまたがらせたり、あるいは部分文字列ごとにコメントを追加することさえできます。例えば: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{re}\PYG{o}{.}\PYG{n}{compile}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{[A\PYGZhy{}Za\PYGZhy{}z\PYGZus{}]}\PYG{l+s+s2}{\PYGZdq{}} \PYG{c+c1}{\PYGZsh{} letter or underscore} \PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{[A\PYGZhy{}Za\PYGZhy{}z0\PYGZhy{}9\PYGZus{}]*}\PYG{l+s+s2}{\PYGZdq{}} \PYG{c+c1}{\PYGZsh{} letter, digit or underscore} \PYG{p}{)} \end{sphinxVerbatim} この機能は文法レベルで定義されていますが、スクリプトをコンパイルする際の処理として実現されることに注意してください。実行時に文字列表現を結合したければ、 '+' 演算子を使わなければなりません。また、リテラルの結合においては、結合する各要素に異なる引用符形式を使ったり (raw 文字列と三重引用符を混ぜることさえできます) 、フォーマット済み文字列リテラルと通常の文字列リテラルを結合したりすることもできますので注意してください。 \index{formatted string literal@\spxentry{formatted string literal}}\index{interpolated string literal@\spxentry{interpolated string literal}}\index{string@\spxentry{string}!formatted literal@\spxentry{formatted literal}}\index{string@\spxentry{string}!interpolated literal@\spxentry{interpolated literal}}\index{f\sphinxhyphen{}string@\spxentry{f\sphinxhyphen{}string}}\index{fstring@\spxentry{fstring}}\index{\sphinxleftcurlybrace{}\sphinxrightcurlybrace{} (curly brackets)@\spxentry{\sphinxleftcurlybrace{}\sphinxrightcurlybrace{}}\spxextra{curly brackets}!in formatted string literal@\spxentry{in formatted string literal}}\index{"! (exclamation)@\spxentry{"!}\spxextra{exclamation}!in formatted string literal@\spxentry{in formatted string literal}}\index{: (colon)@\spxentry{:}\spxextra{colon}!in formatted string literal@\spxentry{in formatted string literal}}\index{= (equals)@\spxentry{=}\spxextra{equals}!for help in debugging using string literals@\spxentry{for help in debugging using string literals}}\ignorespaces \subsection{フォーマット済み文字列リテラル} \label{\detokenize{reference/lexical_analysis:formatted-string-literals}}\label{\detokenize{reference/lexical_analysis:f-strings}}\label{\detokenize{reference/lexical_analysis:index-24}} \DUrole{versionmodified,added}{バージョン 3.6 で追加.} フォーマット済み文字列リテラル( \sphinxstyleemphasis{formatted string literal} )または \sphinxstyleemphasis{f\sphinxhyphen{}string} は、接頭辞 \sphinxcode{\sphinxupquote{'f'}} または \sphinxcode{\sphinxupquote{'F'}} の付いた文字列リテラルです。これらの文字列には、波括弧 \sphinxcode{\sphinxupquote{\{\}}} で区切られた式である置換フィールドを含めることができます。他の文字列リテラルの場合は内容が常に一定で変わることが無いのに対して、フォーマット済み文字列リテラルは実行時に式として評価されます。 エスケープシーケンスは通常の文字列リテラルと同様にデコードされます (ただしリテラルが raw 文字列でもある場合は除きます) 。エスケープシーケンスをデコードした後は、文字列の内容は次の文法で解釈されます: \begin{productionlist} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-f_string}}\production{f\_string}{ ({\hyperref[\detokenize{reference/lexical_analysis:grammar-token-literal-char}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{literal\_char}}}}} | "\{\{" | "\}\}" | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-replacement-field}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{replacement\_field}}}}})*} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-replacement_field}}\production{replacement\_field}{ "\{" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-f-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{f\_expression}}}}} {[}"="{]} {[}"!" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-conversion}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{conversion}}}}}{]} {[}":" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-format-spec}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{format\_spec}}}}}{]} "\}"} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-f_expression}}\production{f\_expression}{ ({\hyperref[\detokenize{reference/expressions:grammar-token-conditional-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{conditional\_expression}}}}} | "*" {\hyperref[\detokenize{reference/expressions:grammar-token-or-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{or\_expr}}}}})} \productioncont{ ("," {\hyperref[\detokenize{reference/expressions:grammar-token-conditional-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{conditional\_expression}}}}} | "," "*" {\hyperref[\detokenize{reference/expressions:grammar-token-or-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{or\_expr}}}}})* {[}","{]}} \productioncont{ | {\hyperref[\detokenize{reference/expressions:grammar-token-yield-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield\_expression}}}}}} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-conversion}}\production{conversion}{ "s" | "r" | "a"} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-format_spec}}\production{format\_spec}{ ({\hyperref[\detokenize{reference/lexical_analysis:grammar-token-literal-char}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{literal\_char}}}}} | NULL | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-replacement-field}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{replacement\_field}}}}})*} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-literal_char}}\production{literal\_char}{ } \end{productionlist} 文字列のうち、波括弧で囲まれた部分以外は文字通り解釈されます。ただし、二重波括弧 \sphinxcode{\sphinxupquote{'\{\{'}} および \sphinxcode{\sphinxupquote{'\}\}'}} は単一の波括弧に置き換えられます。単一の開き波括弧 \sphinxcode{\sphinxupquote{'\{'}} は置換フィールドの始まりを意味し、その中身は Python の式で始まります。(デバッグ時に便利な機能として) 式のテキストと、評価後の値との両者を表示したい場合には、式の後に等号 \sphinxcode{\sphinxupquote{'='}} を加えてください。その後ろには、感嘆符 \sphinxcode{\sphinxupquote{'!'}} によって導入される変換フィールドを続けることができます。さらに、\sphinxcode{\sphinxupquote{':'}} に続いて書式指定子を追加できます。置換フィールドは単一の閉じ波括弧 \sphinxcode{\sphinxupquote{'\}'}} で終わります。 フォーマット済文字列リテラルの中に現れる式は、括弧で囲まれた通常の Python の式のように扱われますが、いくつかの例外があります。まず、空の式は許されません。そして、{\hyperref[\detokenize{reference/expressions:lambda}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{lambda}}}}} 式および代入式 \sphinxcode{\sphinxupquote{:=}} は明示的に括弧で囲む必要があります。置換フィールド内の式 (replacement expressions) は (例えば、三重クオート文字列などを用いて) 改行を含むことができますが、コメントを含むことはできません。フォーマット済文字列リテラル内の式は、当該リテラルが出現するコンテキストで、左から右の順で評価されます。 \DUrole{versionmodified,changed}{バージョン 3.7 で変更: }Python 3.7 より前のバージョンでは、{\hyperref[\detokenize{reference/expressions:await}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{await}}}}} 式および {\hyperref[\detokenize{reference/compound_stmts:async-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async for}}}}} 句を含む内包表記は、実装に伴う問題の都合により許されていませんでした。 等号 \sphinxcode{\sphinxupquote{'='}} が指定されたとき、出力文字列は、式のテキスト表現、等号 \sphinxcode{\sphinxupquote{'='}}、および評価された式を含みます。開き波括弧 \sphinxcode{\sphinxupquote{'\{'}} の直後、式の中、および \sphinxcode{\sphinxupquote{'='}} の後に含まれる空白文字はすべて保存されます。書式指定子が存在しない限り、\sphinxcode{\sphinxupquote{'='}} を指定した場合は、式に対して \sphinxcode{\sphinxupquote{repr()}} を適用した結果が出力になります。一方、書式指定子が存在する場合は、変換フィールドで \sphinxcode{\sphinxupquote{'!r'}} が指定されていない限り、デフォルトで \sphinxcode{\sphinxupquote{str()}} が適用されます。 \DUrole{versionmodified,added}{バージョン 3.8 で追加: }等号 \sphinxcode{\sphinxupquote{'='}}。 もし変換フィールドが指定されていた場合、式の評価結果はフォーマットの前に変換されます。変換 \sphinxcode{\sphinxupquote{'!s'}} は \sphinxcode{\sphinxupquote{str()}} を、 \sphinxcode{\sphinxupquote{'!r'}} は \sphinxcode{\sphinxupquote{repr()}} を、そして \sphinxcode{\sphinxupquote{'!a'}} は \sphinxcode{\sphinxupquote{ascii()}} を呼び出します。 その結果は、続いて \sphinxcode{\sphinxupquote{format()}} のプロトコルでフォーマットされます。書式指定子は式または変換結果の {\hyperref[\detokenize{reference/datamodel:object.__format__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_format\_\_()}}}}} メソッドに渡されます。書式指定子が省略された場合は、空文字列が渡されます。そしてフォーマットされた結果は、文字列全体の最終的な値に挿入されます。 トップレベルの書式指定子はネストした置換フィールドを含むことができます。これらネストしたフィールドは、それら自身に変換フィールドおよび \DUrole{xref,std,std-ref}{format specifiers} を含むことができますが、さらにネストした置換フィールドを含むことはできません。\DUrole{xref,std,std-ref}{format specifier mini\sphinxhyphen{}language 2} の仕様は \sphinxcode{\sphinxupquote{str.format()}} メソッドで使われているものと同一です。 フォーマット済み文字列リテラルは他の文字列リテラルと結合できますが、置換フィールドを複数のリテラルに分割して書くことはできません。 フォーマット済み文字列リテラルの例をいくつか挙げます: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{name} \PYG{o}{=} \PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{Fred}\PYG{l+s+s2}{\PYGZdq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{He said his name is }\PYG{l+s+si}{\PYGZob{}}\PYG{n}{name}\PYG{l+s+si}{!r\PYGZcb{}}\PYG{l+s+s2}{.}\PYG{l+s+s2}{\PYGZdq{}} \PYG{g+go}{\PYGZdq{}He said his name is \PYGZsq{}Fred\PYGZsq{}.\PYGZdq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{He said his name is }\PYG{l+s+si}{\PYGZob{}}\PYG{n+nb}{repr}\PYG{p}{(}\PYG{n}{name}\PYG{p}{)}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{.}\PYG{l+s+s2}{\PYGZdq{}} \PYG{c+c1}{\PYGZsh{} repr() is equivalent to !r} \PYG{g+go}{\PYGZdq{}He said his name is \PYGZsq{}Fred\PYGZsq{}.\PYGZdq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{width} \PYG{o}{=} \PYG{l+m+mi}{10} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{precision} \PYG{o}{=} \PYG{l+m+mi}{4} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{value} \PYG{o}{=} \PYG{n}{decimal}\PYG{o}{.}\PYG{n}{Decimal}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{12.34567}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{result: }\PYG{l+s+si}{\PYGZob{}}\PYG{n}{value}\PYG{l+s+si}{:}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{width}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{.}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{precision}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}} \PYG{c+c1}{\PYGZsh{} nested fields} \PYG{g+go}{\PYGZsq{}result: 12.35\PYGZsq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{today} \PYG{o}{=} \PYG{n}{datetime}\PYG{p}{(}\PYG{n}{year}\PYG{o}{=}\PYG{l+m+mi}{2017}\PYG{p}{,} \PYG{n}{month}\PYG{o}{=}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{n}{day}\PYG{o}{=}\PYG{l+m+mi}{27}\PYG{p}{)} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{today}\PYG{l+s+si}{:}\PYG{l+s+s2}{\PYGZpc{}B \PYGZpc{}d, \PYGZpc{}Y}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}} \PYG{c+c1}{\PYGZsh{} using date format specifier} \PYG{g+go}{\PYGZsq{}January 27, 2017\PYGZsq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{today}\PYG{l+s+si}{=:}\PYG{l+s+s2}{\PYGZpc{}B \PYGZpc{}d, \PYGZpc{}Y}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}} \PYG{c+c1}{\PYGZsh{} using date format specifier and debugging} \PYG{g+go}{\PYGZsq{}today=January 27, 2017\PYGZsq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{number} \PYG{o}{=} \PYG{l+m+mi}{1024} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{number}\PYG{l+s+si}{:}\PYG{l+s+s2}{\PYGZsh{}0x}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}} \PYG{c+c1}{\PYGZsh{} using integer format specifier} \PYG{g+go}{\PYGZsq{}0x400\PYGZsq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{foo} \PYG{o}{=} \PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{bar}\PYG{l+s+s2}{\PYGZdq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+si}{\PYGZob{}}\PYG{+w}{ }\PYG{n}{foo}\PYG{+w}{ }\PYG{l+s+si}{= \PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}} \PYG{c+c1}{\PYGZsh{} preserves whitespace} \PYG{g+go}{\PYGZdq{} foo = \PYGZsq{}bar\PYGZsq{}\PYGZdq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{line} \PYG{o}{=} \PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{The mill}\PYG{l+s+s2}{\PYGZsq{}}\PYG{l+s+s2}{s closed}\PYG{l+s+s2}{\PYGZdq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{line}\PYG{+w}{ }\PYG{l+s+si}{= \PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}} \PYG{g+go}{\PYGZsq{}line = \PYGZdq{}The mill\PYGZbs{}\PYGZsq{}s closed\PYGZdq{}\PYGZsq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{line}\PYG{+w}{ }\PYG{l+s+si}{= :}\PYG{l+s+s2}{20}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}} \PYG{g+go}{\PYGZdq{}line = The mill\PYGZsq{}s closed \PYGZdq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{line}\PYG{+w}{ }\PYG{l+s+si}{= !r:}\PYG{l+s+s2}{20}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}} \PYG{g+go}{\PYGZsq{}line = \PYGZdq{}The mill\PYGZbs{}\PYGZsq{}s closed\PYGZdq{} \PYGZsq{}} \end{sphinxVerbatim} 通常の文字列リテラルと構文が共通なので(訳註:通常の文字列リテラルにおける引用符の扱いと同様に)、置換フィールド中に、外側のフォーマット済み文字列リテラルで使われている引用符を含めることはできません: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{abc }\PYG{l+s+si}{\PYGZob{}}\PYG{n}{a}\PYG{p}{[}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{x}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{]}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{ def}\PYG{l+s+s2}{\PYGZdq{}} \PYG{c+c1}{\PYGZsh{} error: outer string literal ended prematurely} \PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{abc }\PYG{l+s+si}{\PYGZob{}}\PYG{n}{a}\PYG{p}{[}\PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{x}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{]}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{ def}\PYG{l+s+s2}{\PYGZdq{}} \PYG{c+c1}{\PYGZsh{} workaround: use different quoting} \end{sphinxVerbatim} 式の中でバックスラッシュは使用できず、エラーを送出します: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{newline: }\PYG{l+s+si}{\PYGZob{}}\PYG{n+nb}{ord}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+se}{\PYGZbs{}n}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{)}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}} \PYG{c+c1}{\PYGZsh{} raises SyntaxError} \end{sphinxVerbatim} バックスラッシュでのエスケープが必要な値を含める必要がある場合は、一時変数を作成してください。 \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{newline} \PYG{o}{=} \PYG{n+nb}{ord}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+se}{\PYGZbs{}n}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{)} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{newline: }\PYG{l+s+si}{\PYGZob{}}\PYG{n}{newline}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZdq{}} \PYG{g+go}{\PYGZsq{}newline: 10\PYGZsq{}} \end{sphinxVerbatim} フォーマット済み文字列リテラルは、たとえ式を含んでいなかったとしても、 docstring としては使えません。 \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k}{def} \PYG{n+nf}{foo}\PYG{p}{(}\PYG{p}{)}\PYG{p}{:} \PYG{g+gp}{... } \PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{Not a docstring}\PYG{l+s+s2}{\PYGZdq{}} \PYG{g+gp}{...} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{foo}\PYG{o}{.}\PYG{n+nv+vm}{\PYGZus{}\PYGZus{}doc\PYGZus{}\PYGZus{}} \PYG{o+ow}{is} \PYG{k+kc}{None} \PYG{g+go}{True} \end{sphinxVerbatim} フォーマット済み文字列リテラルを Python に追加した提案 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 498@\spxentry{PEP 498}}\sphinxhref{https://www.python.org/dev/peps/pep-0498}{\sphinxstylestrong{PEP 498}} も参照してください。また関連する文字列フォーマットの仕組みを使っている \sphinxcode{\sphinxupquote{str.format()}} も参照してください。 \subsection{数値リテラル} \label{\detokenize{reference/lexical_analysis:numeric-literals}}\label{\detokenize{reference/lexical_analysis:numbers}} \index{number@\spxentry{number}}\index{numeric literal@\spxentry{numeric literal}}\index{integer literal@\spxentry{integer literal}}\index{floating point literal@\spxentry{floating point literal}}\index{hexadecimal literal@\spxentry{hexadecimal literal}}\index{octal literal@\spxentry{octal literal}}\index{binary literal@\spxentry{binary literal}}\index{decimal literal@\spxentry{decimal literal}}\index{imaginary literal@\spxentry{imaginary literal}}\index{complex literal@\spxentry{complex literal}}\ignorespaces 数値リテラルには 3 種類あります。整数 (integer)、浮動小数点数 (floating point number)、虚数(imaginary numbers) です。複素数リテラルは存在しません。(複素数は実数と虚数の和として作れます)。 数値リテラルには符号が含まれていないことに注意してください; \sphinxcode{\sphinxupquote{\sphinxhyphen{}1}} のような句は、実際には単項演算子 (unary operator) '\sphinxcode{\sphinxupquote{\sphinxhyphen{}}}' とリテラル \sphinxcode{\sphinxupquote{1}} を組み合わせたものです。 \index{0b@\spxentry{0b}!integer literal@\spxentry{integer literal}}\index{0o@\spxentry{0o}!integer literal@\spxentry{integer literal}}\index{0x@\spxentry{0x}!integer literal@\spxentry{integer literal}}\index{\_ (underscore)@\spxentry{\_}\spxextra{underscore}!in numeric literal@\spxentry{in numeric literal}}\ignorespaces \subsection{整数リテラル} \label{\detokenize{reference/lexical_analysis:integer-literals}}\label{\detokenize{reference/lexical_analysis:integers}}\label{\detokenize{reference/lexical_analysis:index-27}} 整数リテラルは以下の字句定義で記述されます: \begin{productionlist} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-integer}}\production{integer}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-decinteger}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{decinteger}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-bininteger}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{bininteger}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-octinteger}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{octinteger}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-hexinteger}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{hexinteger}}}}}} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-decinteger}}\production{decinteger}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-nonzerodigit}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{nonzerodigit}}}}} ({[}"\_"{]} {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-digit}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{digit}}}}})* | "0"+ ({[}"\_"{]} "0")*} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-bininteger}}\production{bininteger}{ "0" ("b" | "B") ({[}"\_"{]} {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-bindigit}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{bindigit}}}}})+} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-octinteger}}\production{octinteger}{ "0" ("o" | "O") ({[}"\_"{]} {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-octdigit}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{octdigit}}}}})+} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-hexinteger}}\production{hexinteger}{ "0" ("x" | "X") ({[}"\_"{]} {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-hexdigit}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{hexdigit}}}}})+} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-nonzerodigit}}\production{nonzerodigit}{ "1"..."9"} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-digit}}\production{digit}{ "0"..."9"} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-bindigit}}\production{bindigit}{ "0" | "1"} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-octdigit}}\production{octdigit}{ "0"..."7"} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-hexdigit}}\production{hexdigit}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-digit}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{digit}}}}} | "a"..."f" | "A"..."F"} \end{productionlist} 値がメモリ上に収まるかどうかという問題を除けば、整数リテラルには長さの制限がありません。 アンダースコアはリテラルの値を判断するにあたって無視されます。そのためアンダースコアを使って数字をグループ化することで読みやすくできます。アンダースコアは数字と数字の間に 1 つだけ、あるいは \sphinxcode{\sphinxupquote{0x}} のような基数指定の直後に 1 つだけ挿入できます。 なお、非 0 の十進数の先頭には 0 を付けられません。これは、Python がバージョン 3.0 以前に使っていた C 形式の八進リテラルとの曖昧さを回避するためです。 整数リテラルの例をいくつか示します: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{l+m+mi}{7} \PYG{l+m+mi}{2147483647} \PYG{l+m+mo}{0o177} \PYG{l+m+mb}{0b100110111} \PYG{l+m+mi}{3} \PYG{l+m+mi}{79228162514264337593543950336} \PYG{l+m+mo}{0o377} \PYG{l+m+mh}{0xdeadbeef} \PYG{l+m+mi}{100\PYGZus{}000\PYGZus{}000\PYGZus{}000} \PYG{l+m+mb}{0b\PYGZus{}1110\PYGZus{}0101} \end{sphinxVerbatim} \DUrole{versionmodified,changed}{バージョン 3.6 で変更: }グループ化を目的としたリテラル中のアンダースコアが許されるようになりました。 \index{. (dot)@\spxentry{.}\spxextra{dot}!in numeric literal@\spxentry{in numeric literal}}\index{e@\spxentry{e}!in numeric literal@\spxentry{in numeric literal}}\index{\_ (underscore)@\spxentry{\_}\spxextra{underscore}!in numeric literal@\spxentry{in numeric literal}}\ignorespaces \subsection{浮動小数点数リテラル} \label{\detokenize{reference/lexical_analysis:floating-point-literals}}\label{\detokenize{reference/lexical_analysis:floating}}\label{\detokenize{reference/lexical_analysis:index-28}} 浮動小数点数リテラルは以下の字句定義で記述されます: \begin{productionlist} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-floatnumber}}\production{floatnumber}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-pointfloat}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{pointfloat}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-exponentfloat}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{exponentfloat}}}}}} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-pointfloat}}\production{pointfloat}{ {[}{\hyperref[\detokenize{reference/lexical_analysis:grammar-token-digitpart}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{digitpart}}}}}{]} {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-fraction}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{fraction}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-digitpart}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{digitpart}}}}} "."} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-exponentfloat}}\production{exponentfloat}{ ({\hyperref[\detokenize{reference/lexical_analysis:grammar-token-digitpart}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{digitpart}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-pointfloat}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{pointfloat}}}}}) {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-exponent}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{exponent}}}}}} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-digitpart}}\production{digitpart}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-digit}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{digit}}}}} ({[}"\_"{]} {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-digit}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{digit}}}}})*} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-fraction}}\production{fraction}{ "." {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-digitpart}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{digitpart}}}}}} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-exponent}}\production{exponent}{ ("e" | "E") {[}"+" | "\sphinxhyphen{}"{]} {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-digitpart}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{digitpart}}}}}} \end{productionlist} なお、整数部と指数部は常に 10 を基数として解釈されます。例えば、\sphinxcode{\sphinxupquote{077e010}} は正しい表記であり、\sphinxcode{\sphinxupquote{77e10}} と同じ数を表します。浮動小数点数リテラルの取りうる値の範囲は実装に依存します。整数リテラルと同じように、アンダースコアで数字をグループ分けできます。 浮動小数点数リテラルの例をいくつか示します: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{l+m+mf}{3.14} \PYG{l+m+mf}{10.} \PYG{l+m+mf}{.001} \PYG{l+m+mf}{1e100} \PYG{l+m+mf}{3.14e\PYGZhy{}10} \PYG{l+m+mf}{0e0} \PYG{l+m+mf}{3.14\PYGZus{}15\PYGZus{}93} \end{sphinxVerbatim} \DUrole{versionmodified,changed}{バージョン 3.6 で変更: }グループ化を目的としたリテラル中のアンダースコアが許されるようになりました。 \index{j@\spxentry{j}!in numeric literal@\spxentry{in numeric literal}}\ignorespaces \subsection{虚数 (imaginary) リテラル} \label{\detokenize{reference/lexical_analysis:imaginary-literals}}\label{\detokenize{reference/lexical_analysis:imaginary}}\label{\detokenize{reference/lexical_analysis:index-29}} 虚数リテラルは以下のような字句定義で記述されます: \begin{productionlist} \phantomsection\label{\detokenize{reference/lexical_analysis:grammar-token-imagnumber}}\production{imagnumber}{ ({\hyperref[\detokenize{reference/lexical_analysis:grammar-token-floatnumber}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{floatnumber}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-digitpart}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{digitpart}}}}}) ("j" | "J")} \end{productionlist} 虚数リテラルは、実数部が 0.0 の複素数を表します。複素数は二つ組の浮動小数点型の数値で表され、それぞれの数値は浮動小数点型と同じ定義域の範囲を持ちます。実数部がゼロでない浮動小数点を生成するには、 \sphinxcode{\sphinxupquote{(3+4j)}} のように虚数リテラルに浮動小数点数を加算します。以下に虚数リテラルの例をいくつか示します: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{l+m+mf}{3.14}\PYG{n}{j} \PYG{l+m+mf}{10.}\PYG{n}{j} \PYG{l+m+mi}{10}\PYG{n}{j} \PYG{l+m+mf}{.001}\PYG{n}{j} \PYG{l+m+mf}{1e100j} \PYG{l+m+mf}{3.14e\PYGZhy{}10}\PYG{n}{j} \PYG{l+m+mf}{3.14\PYGZus{}15\PYGZus{}93}\PYG{n}{j} \end{sphinxVerbatim} \section{演算子} \label{\detokenize{reference/lexical_analysis:operators}}\label{\detokenize{reference/lexical_analysis:id11}} \index{operators@\spxentry{operators}}\ignorespaces 以下のトークンは演算子です: \begin{sphinxVerbatim}[commandchars=\\\{\}] + \PYGZhy{} * ** / // \PYGZpc{} @ \PYGZlt{}\PYGZlt{} \PYGZgt{}\PYGZgt{} \PYGZam{} | \PYGZca{} \PYGZti{} := \PYGZlt{} \PYGZgt{} \PYGZlt{}= \PYGZgt{}= == != \end{sphinxVerbatim} \section{デリミタ (delimiter)} \label{\detokenize{reference/lexical_analysis:delimiters}}\label{\detokenize{reference/lexical_analysis:id12}} \index{delimiters@\spxentry{delimiters}}\ignorespaces 以下のトークンは文法上のデリミタとして働きます: \begin{sphinxVerbatim}[commandchars=\\\{\}] ( ) [ ] \PYGZob{} \PYGZcb{} , : . ; @ = \PYGZhy{}\PYGZgt{} += \PYGZhy{}= *= /= //= \PYGZpc{}= @= \PYGZam{}= |= \PYGZca{}= \PYGZgt{}\PYGZgt{}= \PYGZlt{}\PYGZlt{}= **= \end{sphinxVerbatim} ピリオドは浮動小数点数や虚数リテラル中にも置けます。ピリオド三つの列はスライス表記における省略符号 (ellipsis) リテラルとして特別な意味を持ちます。リスト後半の累算代入演算子 (augmented assignment operator) は、字句的にはデリミタとして振舞いますが、演算も行います。 以下の印字可能 ASCII 文字は、他のトークンの一部として特殊な意味を持っていたり、字句解析器にとって重要な意味を持っています: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYGZsq{} \PYGZdq{} \PYGZsh{} \PYGZbs{} \end{sphinxVerbatim} 以下の印字可能 ASCII 文字は、Python では使われていません。これらの文字が文字列リテラルやコメントの外にある場合、無条件にエラーとなります: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYGZdl{} ? ` \end{sphinxVerbatim} \subsubsection*{脚注} \chapter{データモデル} \label{\detokenize{reference/datamodel:data-model}}\label{\detokenize{reference/datamodel:datamodel}}\label{\detokenize{reference/datamodel::doc}} \section{オブジェクト、値、および型} \label{\detokenize{reference/datamodel:objects-values-and-types}}\label{\detokenize{reference/datamodel:objects}} \index{object@\spxentry{object}}\index{data@\spxentry{data}}\ignorespaces Python における \sphinxstyleemphasis{オブジェクト (object)} とは、データを抽象的に表したものです。Python プログラムにおけるデータは全て、オブジェクトまたはオブジェクト間の関係として表されます。(ある意味では、プログラムコードもまたオブジェクトとして表されます。これはフォン・ノイマン: Von Neumann の "プログラム記憶方式コンピュータ: stored program computer" のモデルに適合します。) \index{組み込み関数@\spxentry{組み込み関数}!id@\spxentry{id}}\index{id@\spxentry{id}!組み込み関数@\spxentry{組み込み関数}}\index{組み込み関数@\spxentry{組み込み関数}!type@\spxentry{type}}\index{type@\spxentry{type}!組み込み関数@\spxentry{組み込み関数}}\index{identity of an object@\spxentry{identity of an object}}\index{value of an object@\spxentry{value of an object}}\index{type of an object@\spxentry{type of an object}}\index{mutable object@\spxentry{mutable object}}\index{immutable object@\spxentry{immutable object}}\ignorespaces すべてのオブジェクトは、同一性 (identity)、型、値をもっています。 \sphinxstyleemphasis{同一性} は生成されたあとは変更されません。これはオブジェクトのアドレスのようなものだと考えられるかもしれません。 '{\hyperref[\detokenize{reference/expressions:is}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{is}}}}}' 演算子は2つのオブジェクトの同一性を比較します。 \sphinxcode{\sphinxupquote{id()}} 関数は同一性を表す整数を返します。 \sphinxstylestrong{CPython implementation detail:} CPython では、\sphinxcode{\sphinxupquote{id(x)}} は \sphinxcode{\sphinxupquote{x}} が格納されているメモリ上のアドレスを返します。 オブジェクトの型はオブジェクトがサポートする操作 (例: \sphinxcode{\sphinxupquote{len()}} をサポートするか) と、オブジェクトが取りうる値を決定します。 \sphinxcode{\sphinxupquote{type()}} 関数はオブジェクトの型 (型自体もオブジェクトです) を返します。同一性と同じく、オブジェクトの型(\sphinxstyleemphasis{type}) も変更不可能です。 % \begin{footnote}[1]\sphinxAtStartFootnote 特定の条件が満たされた場合、オブジェクトの type を変更することが \sphinxstyleemphasis{できます} 。これは、正しく扱われなかった場合にとても奇妙な動作を引き起こすので、一般的には良い考えではありません。 % \end{footnote} オブジェクトによっては \sphinxstyleemphasis{値} を変更することが可能です。値を変更できるオブジェクトのことを \sphinxstyleemphasis{mutable} と呼びます。生成後に値を変更できないオブジェクトのことを \sphinxstyleemphasis{immutable} と呼びます。(mutable なオブジェクトへの参照を格納している immutableなコンテナオブジェクトの値は、その格納しているオブジェクトの値が変化した時に変化しますが、コンテナがどのオブジェクトを格納しているのかが変化しないのであれば immutable だと考えることができます。したがって、immutable かどうかは値が変更可能かどうかと完全に一致するわけではありません) オブジェクトが mutable かどうかはその型によって決まります。例えば、数値型、文字列型とタプル型のインスタンスは immutable で、dict や list は mutable です。 \index{garbage collection@\spxentry{garbage collection}}\index{reference counting@\spxentry{reference counting}}\index{unreachable object@\spxentry{unreachable object}}\ignorespaces オブジェクトを明示的に破壊することはできません; しかし、オブジェクトに到達不能 (unreachable) になると、ガベージコレクション (garbage\sphinxhyphen{}collection) によって処理されるかもしれません。ガベージコレクションを遅らせたり、全く行わない実装も許されています \sphinxhyphen{}\sphinxhyphen{}\sphinxhyphen{} 到達可能なオブジェクトを処理してしまわないかぎり、ガベージコレクションをどう実装するかは実装品質の問題です。 \sphinxstylestrong{CPython implementation detail:} 現在の CPython 実装では参照カウント(reference\sphinxhyphen{}counting) 方式を使っており、(オプションとして) 循環参照を行っているごみオブジェクトを遅延検出します。この実装ではほとんどのオブジェクトを到達不能になると同時に処理することができますが、循環参照を含むごみオブジェクトの収集が確実に行われるよう保証しているわけではありません。循環参照を持つごみオブジェクト収集の制御については、 \sphinxcode{\sphinxupquote{gc}} モジュールを参照してください。 CPython以外の実装は別の方式を使っており、CPythonも将来は別の方式を使うかもしれません。オブジェクトが到達不能になったときに即座に終了処理されることに頼らないでください (ですからファイルは必ず明示的に閉じてください)。 実装のトレース機能やデバッグ機能を使えば、通常は収集されてしまうようなオブジェクトを生存させることがあるので注意してください。また、 '{\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}}...{\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}}' 文を使って例外を捕捉できるようにすると、オブジェクトを生存させることがあります。 オブジェクトには、開かれたファイルやウィンドウといった、 "外部の (external) " リソースへの参照を含むものがあります。これらのリソースは、オブジェクトがガベージコレクションされた際に解放されるものと理解されていますが、ガベージコレクションが行われる保証はないので、こうしたオブジェクトは外部リソースを明示的に解放する方法、大抵は \sphinxcode{\sphinxupquote{close()}} メソッドも提供しています。こうしたオブジェクトは明示的に close するよう強く推奨されます。この操作をする際には、'{\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}}...{\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}}' 文や、 '{\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}}' 文を使うと便利です。 \index{container@\spxentry{container}}\ignorespaces 他のオブジェクトに対する参照をもつオブジェクトもあります; これらは \sphinxstyleemphasis{コンテナ (container)} と呼ばれます。コンテナオブジェクトの例として、タプル、リスト、および辞書が挙げられます。オブジェクトへの参照自体がコンテナの値の一部です。ほとんどの場合、コンテナの値というと、コンテナに入っているオブジェクトの値のことを指し、それらオブジェクトのアイデンティティではありません; しかしながら、コンテナの変更可能性について述べる場合、今まさにコンテナに入っているオブジェクトのアイデンティティのことを指します。したがって、 (タプルのように) 変更不能なオブジェクトが変更可能なオブジェクトへの参照を含む場合、その値が変化するのは変更可能なオブジェクトが変更された時、ということになります。 型はオブジェクトの動作のほとんど全てに影響します。オブジェクトのアイデンティティが重要かどうかでさえ、ある意味では型に左右されます: 変更不能な型では、新たな値を計算するような操作を行うと、実際には同じ型と値を持った既存のオブジェクトへの参照を返すことがありますが、変更可能なオブジェクトではそのような動作は起こりえません。例えば、 \sphinxcode{\sphinxupquote{a = 1; b = 1}} とすると、 \sphinxcode{\sphinxupquote{a}} と \sphinxcode{\sphinxupquote{b}} は値 1 を持つ同じオブジェクトを参照するときもあるし、そうでないときもあります。これは実装に依存します。しかし、 \sphinxcode{\sphinxupquote{c = {[}{]}; d = {[}{]}}} とすると、 \sphinxcode{\sphinxupquote{c}} と \sphinxcode{\sphinxupquote{d}} はそれぞれ二つの異なった、互いに一意な、新たに作成された空のリストを参照することが保証されています。 (\sphinxcode{\sphinxupquote{c = d = {[}{]}}} とすると、 \sphinxcode{\sphinxupquote{c}} と \sphinxcode{\sphinxupquote{d}} の両方に同じオブジェクトを代入します) \section{標準型の階層} \label{\detokenize{reference/datamodel:the-standard-type-hierarchy}}\label{\detokenize{reference/datamodel:types}} \index{type@\spxentry{type}}\index{data@\spxentry{data}!type@\spxentry{type}}\index{type@\spxentry{type}!data@\spxentry{data}}\index{type@\spxentry{type}!hierarchy@\spxentry{hierarchy}}\index{hierarchy@\spxentry{hierarchy}!type@\spxentry{type}}\index{extension@\spxentry{extension}!module@\spxentry{module}}\index{module@\spxentry{module}!extension@\spxentry{extension}}\index{C@\spxentry{C}!language@\spxentry{language}}\index{language@\spxentry{language}!C@\spxentry{C}}\ignorespaces 以下は Python に組み込まれている型のリストです。(実装によって、C、Java、またはその他の言語で書かれた) 拡張モジュールで、その他の型が定義されていることがあります。新たな型 (有理数や、整数を効率的に記憶する配列、など) の追加は、たいてい標準ライブラリを通して提供されますが、将来のバージョンの Python では、型の階層構造にこのような追加がなされるかもしれません。 \index{attribute@\spxentry{attribute}}\index{special@\spxentry{special}!attribute@\spxentry{attribute}}\index{attribute@\spxentry{attribute}!special@\spxentry{special}}\index{generic@\spxentry{generic}!special attribute@\spxentry{special} \spxentry{attribute}}\index{special@\spxentry{special}!attribute, generic@\spxentry{attribute}, \spxentry{generic}}\index{attribute@\spxentry{attribute}!generic special@\spxentry{generic} \spxentry{special}}\ignorespaces 以下に説明する型のいくつかには、 '特殊属性 (special attribute)' を列挙した段落があります。これらの属性は実装へのアクセス手段を提供するもので、一般的な用途に利用するためのものではありません。特殊属性の定義は将来変更される可能性があります。 \begin{description} \item[{None}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!None@\spxentry{None}}\index{None@\spxentry{None}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces この型には単一の値しかありません。この値を持つオブジェクトはただ一つしか存在しません。このオブジェクトは組み込み名 \sphinxcode{\sphinxupquote{None}} でアクセスされます。このオブジェクトは、様々な状況で値が存在しないことをしめします。例えば、明示的に値を返さない関数は \sphinxcode{\sphinxupquote{None}} を返します。 \sphinxcode{\sphinxupquote{None}} の真値 (truth value) は偽 (false) です。 \item[{NotImplemented}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!NotImplemented@\spxentry{NotImplemented}}\index{NotImplemented@\spxentry{NotImplemented}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces この型には単一の値しかありません。 この値を持つオブジェクトはただ一つしか存在しません。 このオブジェクトは、 \sphinxcode{\sphinxupquote{NotImplemented}} というPythonで決められている名前でアクセスされます。 数値メソッドと拡張比較メソッドに渡された被演算子を処理する演算子が実装されていない場合、この値を返すべきです。 (この次にインタープリタは被演算子を反転させて演算をするか、その演算子に依存する他のフォールバックの処理を試します。) この処理では真偽値コンテキストでの評価はしてはいけません。 詳細は \DUrole{xref,std,std-ref}{implementing\sphinxhyphen{}the\sphinxhyphen{}arithmetic\sphinxhyphen{}operations} を参照してください。 \DUrole{versionmodified,changed}{バージョン 3.9 で変更: }\sphinxcode{\sphinxupquote{NotImplemented}} の評価は非推奨です。 現時点で真と評価されていても \sphinxcode{\sphinxupquote{DeprecationWarning}} が出ます。 この警告は将来のバージョンの Python で \sphinxcode{\sphinxupquote{TypeError}} を送出します。 \item[{Ellipsis}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!Ellipsis@\spxentry{Ellipsis}}\index{Ellipsis@\spxentry{Ellipsis}!オブジェクト@\spxentry{オブジェクト}}\index{...@\spxentry{...}!ellipsis literal@\spxentry{ellipsis literal}}\ignorespaces この型には単一の値しかありません。この値を持つオブジェクトはただ一つしか存在しません。このオブジェクトはリテラル \sphinxcode{\sphinxupquote{...}} またはPythonで決められている名前 \sphinxcode{\sphinxupquote{Ellipsis}} でアクセスされます。真理値は真 (true)です。 \item[{\sphinxcode{\sphinxupquote{numbers.Number}}}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!numeric@\spxentry{numeric}}\index{numeric@\spxentry{numeric}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces 数値リテラルによって作成されたり、算術演算や組み込みの算術関数によって返されるオブジェクトです。数値オブジェクトは変更不能です; 一度値が生成されると、二度と変更されることはありません。Python の数値オブジェクトはいうまでもなく数学で言うところの数値と強く関係していますが、コンピュータ内で数値を表現する際に伴う制限を受けています。 The string representations of the numeric classes, computed by {\hyperref[\detokenize{reference/datamodel:object.__repr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_repr\_\_()}}}}} and {\hyperref[\detokenize{reference/datamodel:object.__str__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_str\_\_()}}}}}, have the following properties: \begin{itemize} \item {} その文字列は、クラスコンストラクタに渡したときに、元の数値の値を持つオブジェクトを生成する有効な数値リテラルです。 \item {} できるなら、10を底として表現されます。 \item {} 小数点の前にある 1 つのゼロを除いて、上に連なるゼロは表示されません。 \item {} 小数点の後にある 1 つのゼロを除いて、下に連なるゼロは表示されません。 \item {} 符号は数値が負数のときのみ表示されます。 \end{itemize} Python は整数、浮動小数点数、複素数の間で区別を行っています: \begin{description} \item[{\sphinxcode{\sphinxupquote{numbers.Integral}} (整数)}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!integer@\spxentry{integer}}\index{integer@\spxentry{integer}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces 整数型は、整数(正の数および負の数)を表す数学的集合内における要素を表現する型です。 整数には 2 種類あります: \begin{description} \item[{整数 (\sphinxcode{\sphinxupquote{int}})}] \leavevmode 無制限の範囲の数を表現しますが、利用可能な (仮想) メモリサイズの制限のみを受けます。シフト演算やマスク演算のために2進数表現を持つと想定されます。負の数は符号ビットが左に無限に延びているような錯覚を与える 2 の補数表現の変型で表されます。 \item[{ブール値 (\sphinxcode{\sphinxupquote{bool}})}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!Boolean@\spxentry{Boolean}}\index{Boolean@\spxentry{Boolean}!オブジェクト@\spxentry{オブジェクト}}\index{False@\spxentry{False}}\index{True@\spxentry{True}}\ignorespaces 真偽値の False と True を表します。\sphinxcode{\sphinxupquote{False}} と \sphinxcode{\sphinxupquote{True}} を表す 2 つのオブジェクトのみがブール値オブジェクトです。ブール型は整数型の派生型であり、ほとんどの状況でそれぞれ 0 と 1 のように振る舞いますが、例外として文字列に変換されたときはそれぞれ \sphinxcode{\sphinxupquote{"False"}} および \sphinxcode{\sphinxupquote{"True"}} という文字列が返されます。 \end{description} \index{integer@\spxentry{integer}!representation@\spxentry{representation}}\index{representation@\spxentry{representation}!integer@\spxentry{integer}}\ignorespaces 整数表現に関する規則は、負の整数を含むシフト演算やマスク演算において、最も有意義な解釈ができるように意図されています。 \item[{\sphinxcode{\sphinxupquote{numbers.Real}} (\sphinxcode{\sphinxupquote{float}}) (実数)}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!floating point@\spxentry{floating point}}\index{floating point@\spxentry{floating point}!オブジェクト@\spxentry{オブジェクト}}\index{floating point@\spxentry{floating point}!number@\spxentry{number}}\index{number@\spxentry{number}!floating point@\spxentry{floating point}}\index{C@\spxentry{C}!language@\spxentry{language}}\index{language@\spxentry{language}!C@\spxentry{C}}\index{Java@\spxentry{Java}!language@\spxentry{language}}\index{language@\spxentry{language}!Java@\spxentry{Java}}\ignorespaces この型は計算機レベルの倍精度浮動小数点数を表現します。表現可能な値の範囲やオーバーフローの扱いは計算機のアーキテクチャ(および、CやJavaによる実装)に従います。Pythonは単精度浮動小数点数をサポートしません。一般的に単精度浮動小数点数を使う理由はプロセッサーとメモリの使用を節約するためと説明されます。しかし、こうした節約はPythonでオブジェクトを扱う際のオーバーヘッドに比べれば微々たるものです。また、2種類の浮動小数点数型を持つことで複雑になる理由はありません。 \item[{\sphinxcode{\sphinxupquote{numbers.Complex}} (\sphinxcode{\sphinxupquote{complex}})}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!complex@\spxentry{complex}}\index{complex@\spxentry{complex}!オブジェクト@\spxentry{オブジェクト}}\index{complex@\spxentry{complex}!number@\spxentry{number}}\index{number@\spxentry{number}!complex@\spxentry{complex}}\ignorespaces この型は、計算機レベルで倍精度とされている浮動小数点を 2 つ一組にして複素数を表現します。浮動小数点について述べたのと同じ性質が当てはまります。複素数 \sphinxcode{\sphinxupquote{z}} の実数部および虚数部は、それぞれ読み出し専用属性 \sphinxcode{\sphinxupquote{z.real}} および \sphinxcode{\sphinxupquote{z.imag}} で取り出すことができます。 \end{description} \item[{シーケンス型 (sequence)}] \leavevmode \index{組み込み関数@\spxentry{組み込み関数}!len@\spxentry{len}}\index{len@\spxentry{len}!組み込み関数@\spxentry{組み込み関数}}\index{オブジェクト@\spxentry{オブジェクト}!sequence@\spxentry{sequence}}\index{sequence@\spxentry{sequence}!オブジェクト@\spxentry{オブジェクト}}\index{index operation@\spxentry{index operation}}\index{item selection@\spxentry{item selection}}\index{subscription@\spxentry{subscription}}\ignorespaces この型は、有限の順序集合 (ordered set) を表現します。要素は非負の整数でインデクス化されています。組み込み関数 \sphinxcode{\sphinxupquote{len()}} を使うと、シーケンスの要素数を返します。シーケンスの長さが \sphinxstyleemphasis{n} の場合、インデクスは 0, 1, ..., \sphinxstyleemphasis{n} \sphinxhyphen{}1 からなる集合です。シーケンス \sphinxstyleemphasis{a} の要素 \sphinxstyleemphasis{i} は \sphinxcode{\sphinxupquote{a{[}i{]}}} で選択します。 \index{slicing@\spxentry{slicing}}\ignorespaces シーケンスはスライス操作 (slice) もサポートしています: \sphinxcode{\sphinxupquote{a{[}i:j{]}}} とすると、 \sphinxstyleemphasis{i} \sphinxcode{\sphinxupquote{<=}} \sphinxstyleemphasis{k} \sphinxcode{\sphinxupquote{<}} \sphinxstyleemphasis{j} であるインデクス \sphinxstyleemphasis{k} をもつ全ての要素を選択します。式表現としてスライスを用いた場合、スライスは同じ型をもつ新たなシーケンスを表します。新たなシーケンス内では、インデクス集合が 0 から始まるようにインデクスの値を振りなおします。 シーケンスによっては、第三の "ステップ (step)" パラメタを持つ "拡張スライス (extended slice)" もサポートしています: \sphinxcode{\sphinxupquote{a{[}i:j:k{]}}} は、 \sphinxcode{\sphinxupquote{x = i + n*k}}, \sphinxstyleemphasis{n} \sphinxcode{\sphinxupquote{>=}} \sphinxcode{\sphinxupquote{0}} かつ \sphinxstyleemphasis{i} \sphinxcode{\sphinxupquote{<=}} \sphinxstyleemphasis{x} \sphinxcode{\sphinxupquote{<}} \sphinxstyleemphasis{j} であるようなインデクス \sphinxstyleemphasis{x} を持つような \sphinxstyleemphasis{a} 全ての要素を選択します。 シーケンスは、変更可能なものか、そうでないかで区別されています: \begin{description} \item[{変更不能なシーケンス (immutable sequence)}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!immutable sequence@\spxentry{immutable sequence}}\index{immutable sequence@\spxentry{immutable sequence}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!immutable@\spxentry{immutable}}\index{immutable@\spxentry{immutable}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces 変更不能なシーケンス型のオブジェクトは、一度生成されるとその値を変更することができません。 (オブジェクトに他のオブジェクトへの参照が入っている場合、参照されているオブジェクトは変更可能なオブジェクトでもよく、その値は変更される可能性があります; しかし、変更不能なオブジェクトが直接参照しているオブジェクトの集合自体は、変更することができません。) 以下の型は変更不能なシーケンス型です: \index{string@\spxentry{string}!immutable sequences@\spxentry{immutable sequences}}\ignorespaces \begin{description} \item[{文字列型 (string)}] \leavevmode \index{組み込み関数@\spxentry{組み込み関数}!chr@\spxentry{chr}}\index{chr@\spxentry{chr}!組み込み関数@\spxentry{組み込み関数}}\index{組み込み関数@\spxentry{組み込み関数}!ord@\spxentry{ord}}\index{ord@\spxentry{ord}!組み込み関数@\spxentry{組み込み関数}}\index{character@\spxentry{character}}\index{integer@\spxentry{integer}}\index{Unicode@\spxentry{Unicode}}\ignorespaces 文字列はUnicodeコードポイントを表現する値の配列です。文字列中のどのコードポイントも \sphinxcode{\sphinxupquote{U+0000 \sphinxhyphen{} U+10FFFF}} の範囲で表現されることができます。Pythonは \sphinxcode{\sphinxupquote{char}} 型を持ちません。代わりに、文字列中のどのコードポイントも長さ ''1'' の文字列オブジェクトとして表現することができます。組み込み関数 \sphinxcode{\sphinxupquote{ord()}} は文字列形式を \sphinxcode{\sphinxupquote{U+0000 \sphinxhyphen{} U+10FFFF}} の範囲の整数に変換します。また、組み込み関数 \sphinxcode{\sphinxupquote{chr()}} は \sphinxcode{\sphinxupquote{0 \sphinxhyphen{} 10FFFF}} の範囲の整数を対応する長さ \sphinxcode{\sphinxupquote{1}} の文字列に変換します。\sphinxcode{\sphinxupquote{str.encode()}} はテキストエンコーディングを使うことで \sphinxcode{\sphinxupquote{str}} を \sphinxcode{\sphinxupquote{bytes}} に変換するために使うことができます。また、\sphinxcode{\sphinxupquote{bytes.decode()}} によりその逆が実行することができます。 \item[{タプル型 (tuple)}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!tuple@\spxentry{tuple}}\index{tuple@\spxentry{tuple}!オブジェクト@\spxentry{オブジェクト}}\index{singleton@\spxentry{singleton}!tuple@\spxentry{tuple}}\index{tuple@\spxentry{tuple}!singleton@\spxentry{singleton}}\index{empty@\spxentry{empty}!tuple@\spxentry{tuple}}\index{tuple@\spxentry{tuple}!empty@\spxentry{empty}}\ignorespaces タプルの要素は任意の Python オブジェクトです。二つ以上の要素からなるタプルは、個々の要素を表現する式をカンマで区切って構成します。単一の要素からなるタプル (単集合 'singleton') を作るには、要素を表現する式の直後にカンマをつけます (単一の式だけではタプルを形成しません。これは、式をグループ化するのに丸括弧を使えるようにしなければならないからです)。要素の全くない丸括弧の対を作ると空のタプルになります。 \item[{bytes}] \leavevmode \index{bytes@\spxentry{bytes}}\index{byte@\spxentry{byte}}\ignorespaces bytes オブジェクトは不変な配列です。要素は 8\sphinxhyphen{}bit バイトで、 0 <= x < 256 の範囲の整数で表現されます。 (\sphinxcode{\sphinxupquote{b'abc'}} のような) bytes リテラルや組み込みの \sphinxcode{\sphinxupquote{bytes()}} コンストラクタを使って bytes オブジェクトを作成できます。また、 bytes オブジェクトは \sphinxcode{\sphinxupquote{decode()}} メソッドを通して文字列にデコードできます。 \end{description} \item[{変更可能なシーケンス型 (mutable sequence)}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!mutable sequence@\spxentry{mutable sequence}}\index{mutable sequence@\spxentry{mutable sequence}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!mutable@\spxentry{mutable}}\index{mutable@\spxentry{mutable}!オブジェクト@\spxentry{オブジェクト}}\index{assignment@\spxentry{assignment}!statement@\spxentry{statement}}\index{statement@\spxentry{statement}!assignment@\spxentry{assignment}}\index{subscription@\spxentry{subscription}}\index{slicing@\spxentry{slicing}}\ignorespaces 変更可能なシーケンスは、作成した後で変更することができます。変更可能なシーケンスでは、添字表記やスライス表記を使って指定された要素に代入を行うことができ、 {\hyperref[\detokenize{reference/simple_stmts:del}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{del}}}}} (delete) 文を使って要素を削除することができます。 Python に最初から組み込まれている変更可能なシーケンス型は、今のところ二つです: \begin{description} \item[{リスト型 (list)}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!list@\spxentry{list}}\index{list@\spxentry{list}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces リストの要素は任意の Python オブジェクトにできます。リストは、角括弧の中にカンマで区切られた式を並べて作ります。 (長さが 0 や 1 のシーケンスを作るために特殊な場合分けは必要ないことに注意してください。) \item[{バイト配列}] \leavevmode \index{bytearray@\spxentry{bytearray}}\ignorespaces bytearray オブジェクトは変更可能な配列です。組み込みの \sphinxcode{\sphinxupquote{bytearray()}} コンストラクタによって作成されます。変更可能なことを除けば (つまりハッシュ化できない)、 byte array は変更不能な \sphinxcode{\sphinxupquote{bytes}} オブジェクトと同じインターフェースと機能を提供します。 \end{description} \index{モジュール@\spxentry{モジュール}!array@\spxentry{array}}\index{array@\spxentry{array}!モジュール@\spxentry{モジュール}}\ignorespaces 拡張モジュール \sphinxcode{\sphinxupquote{array}} や、 \sphinxcode{\sphinxupquote{collections}} モジュールには、さらなるミュータブルなシーケンス型の例があります。 \end{description} \item[{集合型}] \leavevmode \index{組み込み関数@\spxentry{組み込み関数}!len@\spxentry{len}}\index{len@\spxentry{len}!組み込み関数@\spxentry{組み込み関数}}\index{オブジェクト@\spxentry{オブジェクト}!set type@\spxentry{set type}}\index{set type@\spxentry{set type}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces 集合型は、順序のない、ユニークで不変なオブジェクトの有限集合を表現します。そのため、(配列の)添字を使ったインデックスアクセスはできません。ただし、イテレートは可能で、組み込み関数 \sphinxcode{\sphinxupquote{len()}} は集合の要素数を返します。集合型の一般的な使い方は、集合に属しているかの高速なテスト、シーケンスからの重複の排除、共通集合・和集合・差・対称差といった数学的な演算の計算です。 集合の要素には、辞書のキーと同じ普遍性に関するルールが適用されます。数値型は通常の数値比較のルールに従うことに注意してください。もし2つの数値の比較結果が同値である(例えば、 \sphinxcode{\sphinxupquote{1}} と \sphinxcode{\sphinxupquote{1.0}})なら、そのうちの1つのみを集合に含めることができます。 現在、2つの組み込み集合型があります: \begin{description} \item[{集合型}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!set@\spxentry{set}}\index{set@\spxentry{set}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces 可変な集合型です。組み込みの \sphinxcode{\sphinxupquote{set()}} コンストラクタで作成され、後から \sphinxcode{\sphinxupquote{add()}} などのいくつかのメソッドで更新できます。 \item[{Frozen set 型}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!frozenset@\spxentry{frozenset}}\index{frozenset@\spxentry{frozenset}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces 不変な集合型です。組み込みの \sphinxcode{\sphinxupquote{frozenset()}} コンストラクタによって作成されます。 frozenset は不変で {\hyperref[\detokenize{glossary:term-hashable}]{\sphinxtermref{\DUrole{xref,std,std-term}{ハッシュ可能}}}} なので、別の集合型の要素になったり、辞書のキーにすることができます。 \end{description} \item[{マッピング型 (mapping)}] \leavevmode \index{組み込み関数@\spxentry{組み込み関数}!len@\spxentry{len}}\index{len@\spxentry{len}!組み込み関数@\spxentry{組み込み関数}}\index{subscription@\spxentry{subscription}}\index{オブジェクト@\spxentry{オブジェクト}!mapping@\spxentry{mapping}}\index{mapping@\spxentry{mapping}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces 任意のインデクス集合でインデクス化された、オブジェクトからなる有限の集合を表現します。添字表記 \sphinxcode{\sphinxupquote{a{[}k{]}}} は、 \sphinxcode{\sphinxupquote{k}} でインデクス指定された要素を \sphinxcode{\sphinxupquote{a}} から選択します; 選択された要素は式の中で使うことができ、代入や {\hyperref[\detokenize{reference/simple_stmts:del}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{del}}}}} 文の対象にすることができます。組み込み関数 \sphinxcode{\sphinxupquote{len()}} は、マッピング内の要素数を返します。 Python に最初から組み込まれているマッピング型は、今のところ一つだけです: \begin{description} \item[{辞書型 (dictionary)}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!dictionary@\spxentry{dictionary}}\index{dictionary@\spxentry{dictionary}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces ほぼ任意の値でインデクスされたオブジェクトからなる有限の集合を表します。 キー (key) として使えない値の唯一の型は、リストや辞書、そしてオブジェクトの同一性でなく値で比較されるその他の変更可能な型です。 これは、辞書型を効率的に実装する上で、キーのハッシュ値が不変である必要があるためです。 数値型をキーに使う場合、キー値は通常の数値比較における規則に従います: 二つの値が等しくなる場合 (例えば \sphinxcode{\sphinxupquote{1}} と \sphinxcode{\sphinxupquote{1.0}})、互いに同じ辞書のエントリを表すインデクスとして使うことができます。 辞書は挿入の順序を保持します。つまり、キーは辞書に追加された順番に生成されていきます。既存のキーを置き換えても、キーの順序は変わりません。キーを削除したのちに再挿入すると、元の場所ではなく辞書の最後に追加されます。 辞書は変更可能な型です; 辞書は \sphinxcode{\sphinxupquote{\{...\}}} 表記で生成します ({\hyperref[\detokenize{reference/expressions:dict}]{\sphinxcrossref{\DUrole{std,std-ref}{辞書表示}}}} を参照してください)。 \index{モジュール@\spxentry{モジュール}!dbm.ndbm@\spxentry{dbm.ndbm}}\index{dbm.ndbm@\spxentry{dbm.ndbm}!モジュール@\spxentry{モジュール}}\index{モジュール@\spxentry{モジュール}!dbm.gnu@\spxentry{dbm.gnu}}\index{dbm.gnu@\spxentry{dbm.gnu}!モジュール@\spxentry{モジュール}}\ignorespaces 拡張モジュール \sphinxcode{\sphinxupquote{dbm.ndbm}} 、 \sphinxcode{\sphinxupquote{dbm.gnu}} は、 \sphinxcode{\sphinxupquote{collections}} モジュールのように、別のマッピング型の例を提供しています。 \DUrole{versionmodified,changed}{バージョン 3.7 で変更: }Pythonのバージョン3.6では、辞書は挿入順序を保持しませんでした。CPython 3.6では挿入順序は保持されましたが、それは策定された言語の仕様というより、その当時の実装の細部とみなされていました。 \end{description} \item[{呼び出し可能型 (callable type)}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!callable@\spxentry{callable}}\index{callable@\spxentry{callable}!オブジェクト@\spxentry{オブジェクト}}\index{function@\spxentry{function}!call@\spxentry{call}}\index{call@\spxentry{call}!function@\spxentry{function}}\index{invocation@\spxentry{invocation}}\index{function@\spxentry{function}!argument@\spxentry{argument}}\index{argument@\spxentry{argument}!function@\spxentry{function}}\ignorespaces 関数呼び出し操作 ({\hyperref[\detokenize{reference/expressions:calls}]{\sphinxcrossref{\DUrole{std,std-ref}{呼び出し (call)}}}} 参照) を行うことができる型です: \begin{description} \item[{ユーザ定義関数 (user\sphinxhyphen{}defined function)}] \leavevmode \index{user\sphinxhyphen{}defined@\spxentry{user\sphinxhyphen{}defined}!function@\spxentry{function}}\index{function@\spxentry{function}!user\sphinxhyphen{}defined@\spxentry{user\sphinxhyphen{}defined}}\index{オブジェクト@\spxentry{オブジェクト}!function@\spxentry{function}}\index{function@\spxentry{function}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!user\sphinxhyphen{}defined function@\spxentry{user\sphinxhyphen{}defined function}}\index{user\sphinxhyphen{}defined function@\spxentry{user\sphinxhyphen{}defined function}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces ユーザ定義関数オブジェクトは、関数定義を行うことで生成されます ({\hyperref[\detokenize{reference/compound_stmts:function}]{\sphinxcrossref{\DUrole{std,std-ref}{関数定義}}}} 参照)。関数は、仮引数 (formal parameter) リストと同じ数の要素が入った引数リストとともに呼び出されます。 特殊属性: \index{\_\_doc\_\_ (function attribute)@\spxentry{\_\_doc\_\_}\spxextra{function attribute}}\index{\_\_name\_\_ (function attribute)@\spxentry{\_\_name\_\_}\spxextra{function attribute}}\index{\_\_module\_\_ (function attribute)@\spxentry{\_\_module\_\_}\spxextra{function attribute}}\index{\_\_dict\_\_ (function attribute)@\spxentry{\_\_dict\_\_}\spxextra{function attribute}}\index{\_\_defaults\_\_ (function attribute)@\spxentry{\_\_defaults\_\_}\spxextra{function attribute}}\index{\_\_closure\_\_ (function attribute)@\spxentry{\_\_closure\_\_}\spxextra{function attribute}}\index{\_\_code\_\_ (function attribute)@\spxentry{\_\_code\_\_}\spxextra{function attribute}}\index{\_\_globals\_\_ (function attribute)@\spxentry{\_\_globals\_\_}\spxextra{function attribute}}\index{\_\_annotations\_\_ (function attribute)@\spxentry{\_\_annotations\_\_}\spxextra{function attribute}}\index{\_\_kwdefaults\_\_ (function attribute)@\spxentry{\_\_kwdefaults\_\_}\spxextra{function attribute}}\index{global@\spxentry{global}!namespace@\spxentry{namespace}}\index{namespace@\spxentry{namespace}!global@\spxentry{global}}\ignorespaces \begin{savenotes}\sphinxattablestart \centering \phantomsection\label{\detokenize{reference/datamodel:index-34}}\nobreak \begin{tabulary}{\linewidth}[t]{|l|L|l|} \hline \sphinxstyletheadfamily 属性 &\sphinxstyletheadfamily 意味 &\sphinxstyletheadfamily \\ \hline \sphinxcode{\sphinxupquote{\_\_doc\_\_}} & 関数のドキュメンテーション文字列で、ドキュメンテーションがない場合は \sphinxcode{\sphinxupquote{None}} になります。サブクラスに継承されません。 & 書き込み可能 \\ \hline \sphinxcode{\sphinxupquote{\_\_name\_\_}} & 関数の名前です。 & 書き込み可能 \\ \hline \sphinxcode{\sphinxupquote{\_\_qualname\_\_}} & 関数の {\hyperref[\detokenize{glossary:term-qualified-name}]{\sphinxtermref{\DUrole{xref,std,std-term}{qualified name}}}} です。 \DUrole{versionmodified,added}{バージョン 3.3 で追加.} & 書き込み可能 \\ \hline \sphinxcode{\sphinxupquote{\_\_module\_\_}} & 関数が定義されているモジュールの名前です。モジュール名がない場合は \sphinxcode{\sphinxupquote{None}} になります。 & 書き込み可能 \\ \hline \sphinxcode{\sphinxupquote{\_\_defaults\_\_}} & デフォルト値を持つ引数に対するデフォルト値が収められたタプルで、デフォルト値を持つ引数がない場合には \sphinxcode{\sphinxupquote{None}} になります & 書き込み可能 \\ \hline \sphinxcode{\sphinxupquote{\_\_code\_\_}} & コンパイルされた関数本体を表現するコードオブジェクトです。 & 書き込み可能 \\ \hline \sphinxcode{\sphinxupquote{\_\_globals\_\_}} & 関数のグローバル変数の入った辞書 (への参照) です \sphinxhyphen{}\sphinxhyphen{}\sphinxhyphen{} この辞書は、関数が定義されているモジュールのグローバルな名前空間を決定します。 & 読み出し専用 \\ \hline \sphinxcode{\sphinxupquote{\_\_dict\_\_}} & 任意の関数属性をサポートするための名前空間が収められています。 & 書き込み可能 \\ \hline \sphinxcode{\sphinxupquote{\_\_closure\_\_}} & \sphinxcode{\sphinxupquote{None}} または関数の個々の自由変数 (引数以外の変数) に対して値を束縛しているセル (cell) 群からなるタプルになります。 \sphinxcode{\sphinxupquote{cell\_contents}} 属性についての情報は下を参照してください。 & 読み出し専用 \\ \hline \sphinxcode{\sphinxupquote{\_\_annotations\_\_}} & パラメータの注釈が入った辞書です。辞書のキーはパラメータ名で、返り値の注釈がある場合は、\sphinxcode{\sphinxupquote{'return'}} がそのキーとなります。 & 書き込み可能 \\ \hline \sphinxcode{\sphinxupquote{\_\_kwdefaults\_\_}} & キーワード専用パラメータのデフォルト値を含む辞書です。 & 書き込み可能 \\ \hline \end{tabulary} \par \sphinxattableend\end{savenotes} 「書き込み可能」とラベルされている属性のほとんどは、代入された値の型をチェックします。 関数オブジェクトはまた、任意の属性を設定したり取得したりできます。この機能は、例えば関数にメタデータを付与したい場合などに使えます。関数の get や set には、通常のドット表記を使います。 \sphinxstyleemphasis{現在の実装では、ユーザ定義の関数でのみ属性をサポートしているので注意して下さい。組み込み関数の属性は将来サポートする予定です。} セルオブジェクトは属性 \sphinxcode{\sphinxupquote{cell\_contents}} を持っています。 これはセルの値を設定するのに加えて、セルの値を得るのにも使えます。 関数定義に関するその他の情報は関数のコードオブジェクトから得られます。後述の内部型 (internal type) に関する説明を参照してください。 \sphinxcode{\sphinxupquote{cell}} 型には \sphinxcode{\sphinxupquote{types}} モジュールからアクセスできます。 \item[{インスタンスメソッド}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!method@\spxentry{method}}\index{method@\spxentry{method}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!user\sphinxhyphen{}defined method@\spxentry{user\sphinxhyphen{}defined method}}\index{user\sphinxhyphen{}defined method@\spxentry{user\sphinxhyphen{}defined method}!オブジェクト@\spxentry{オブジェクト}}\index{user\sphinxhyphen{}defined@\spxentry{user\sphinxhyphen{}defined}!method@\spxentry{method}}\index{method@\spxentry{method}!user\sphinxhyphen{}defined@\spxentry{user\sphinxhyphen{}defined}}\ignorespaces インスタンスメソッドオブジェクトは、クラス、クラスインスタンスと任意の呼び出し可能オブジェクト (通常はユーザ定義関数) を結びつけます。 \index{\_\_func\_\_ (method attribute)@\spxentry{\_\_func\_\_}\spxextra{method attribute}}\index{\_\_self\_\_ (method attribute)@\spxentry{\_\_self\_\_}\spxextra{method attribute}}\index{\_\_doc\_\_ (method attribute)@\spxentry{\_\_doc\_\_}\spxextra{method attribute}}\index{\_\_name\_\_ (method attribute)@\spxentry{\_\_name\_\_}\spxextra{method attribute}}\index{\_\_module\_\_ (method attribute)@\spxentry{\_\_module\_\_}\spxextra{method attribute}}\ignorespaces 読み出し専用の特殊属性: \sphinxcode{\sphinxupquote{\_\_self\_\_}} はクラスインスタンスオブジェクトで、 \sphinxcode{\sphinxupquote{\_\_func\_\_}} は関数オブジェクトです; \sphinxcode{\sphinxupquote{\_\_doc\_\_}} はメソッドのドキュメンテーション文字列 (\sphinxcode{\sphinxupquote{\_\_func\_\_.\_\_doc\_\_}} と同じ) です; \sphinxcode{\sphinxupquote{\_\_name\_\_}} はメソッドの名前 (\sphinxcode{\sphinxupquote{\_\_func\_\_.\_\_name\_\_}} と同じ) です; \sphinxcode{\sphinxupquote{\_\_module\_\_}} はメソッドが定義されたモジュールの名前か、モジュール名がない場合は \sphinxcode{\sphinxupquote{None}} になります。 メソッドもまた、根底にある関数オブジェクトの任意の関数属性に (値の設定はできませんが) アクセスできます。 クラスの属性を (場合によってはそのクラスのインスタンスを介して) 取得するとき、その属性がユーザ定義の関数オブジェクトまたはクラスメソッドオブジェクトであれば、ユーザ定義メソッドオブジェクトが生成されることがあります。 クラスからインスタンスを経由してユーザ定義関数オブジェクトを取得することによってインスタンスメソッドオブジェクトが生成されたとき、 \sphinxcode{\sphinxupquote{\_\_self\_\_}} 属性はそのインスタンスで、このメソッドオブジェクトは束縛されている (bound) といいます。新しいメソッドの \sphinxcode{\sphinxupquote{\_\_func\_\_}} 属性はもとの関数オブジェクトです。 クラスやインスタンスからクラスメソッドオブジェクトを取得することによってインスタンスメソッドオブジェクトが生成されたとき、 \sphinxcode{\sphinxupquote{\_\_self\_\_}} 属性はクラスそのもので、 \sphinxcode{\sphinxupquote{\_\_func\_\_}} 属性はクラスメソッドの根底にある関数オブジェクトです。 インスタンスメソッドオブジェクトが呼び出される際、根底にある関数 (\sphinxcode{\sphinxupquote{\_\_func\_\_}}) が呼び出されます。このとき、クラスインスタンス (\sphinxcode{\sphinxupquote{\_\_self\_\_}}) が引数リストの先頭に挿入されます。例えば、 \sphinxcode{\sphinxupquote{C}} を関数 \sphinxcode{\sphinxupquote{f()}} の定義を含むクラス、 \sphinxcode{\sphinxupquote{x}} を \sphinxcode{\sphinxupquote{C}} のインスタンスとすると、 \sphinxcode{\sphinxupquote{x.f(1)}} の呼び出しは \sphinxcode{\sphinxupquote{C.f(x, 1)}} の呼び出しと同じです。 クラスメソッドオブジェクトからインスタンスメソッドオブジェクトが導出される際、 \sphinxcode{\sphinxupquote{\_\_self\_\_}} に記憶されている "クラスインスタンス" は実際はクラスそのものなので、 \sphinxcode{\sphinxupquote{x.f(1)}} や \sphinxcode{\sphinxupquote{C.f(1)}} の呼び出しは、根底にある関数を \sphinxcode{\sphinxupquote{f}} として \sphinxcode{\sphinxupquote{f(C,1)}} の呼び出しと等価です。 なお、関数オブジェクトからインスタンスメソッドオブジェクトへの変換は、インスタンスから属性が取り出されるたびに行われます。場合によっては、属性をローカル変数に代入しておき、そのローカル変数を呼び出すようにするのが効果的な最適化になります。また、上記の変換はユーザ定義関数に対してのみ行われます; その他の呼び出し可能オブジェクト (および呼び出し可能でない全てのオブジェクト) は、変換されずに取り出されます。それから、クラスインスタンスの属性になっているユーザ定義関数は、束縛メソッドに変換されません; 変換されるのは、関数がクラスの属性である場合 \sphinxstyleemphasis{だけ} です。 \item[{ジェネレータ関数 (generator function)}] \leavevmode \index{generator@\spxentry{generator}!function@\spxentry{function}}\index{generator@\spxentry{generator}!iterator@\spxentry{iterator}}\ignorespaces {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} 文 ({\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\DUrole{std,std-ref}{yield 文}}}} の節を参照) を使う関数もしくはメソッドは \sphinxstyleemphasis{ジェネレータ関数} と呼ばれます。 そのような関数が呼び出されたときは常に、関数の本体を実行するのに使えるイテレータオブジェクトを返します: イテレータの \sphinxcode{\sphinxupquote{iterator.\_\_next\_\_()}} メソッドを呼び出すと、 \sphinxcode{\sphinxupquote{yield}} 文を使って値が提供されるまで関数を実行します。 関数の {\hyperref[\detokenize{reference/simple_stmts:return}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{return}}}}} 文を実行するか終端に達したときは、 \sphinxcode{\sphinxupquote{StopIteration}} 例外が送出され、イテレータが返すべき値の最後まで到達しています。 \item[{コルーチン関数 (coroutine function)}] \leavevmode \index{coroutine@\spxentry{coroutine}!function@\spxentry{function}}\ignorespaces {\hyperref[\detokenize{reference/compound_stmts:async-def}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async def}}}}} を使用して定義された関数やメソッドを \sphinxstyleemphasis{コルーチン関数 (coroutine function)} と呼びます。 呼び出された時、そのような関数は {\hyperref[\detokenize{glossary:term-coroutine}]{\sphinxtermref{\DUrole{xref,std,std-term}{coroutine}}}} オブジェクトを返します。 コルーチン関数は {\hyperref[\detokenize{reference/compound_stmts:async-with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async with}}}}} や {\hyperref[\detokenize{reference/compound_stmts:async-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async for}}}}} 文だけでなく {\hyperref[\detokenize{reference/expressions:await}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{await}}}}} 式を持つことが出来ます。 {\hyperref[\detokenize{reference/datamodel:coroutine-objects}]{\sphinxcrossref{\DUrole{std,std-ref}{コルーチンオブジェクト}}}} を参照してください。 \item[{非同期ジェネレータ関数 (asynchronous generator function)}] \leavevmode \index{asynchronous generator@\spxentry{asynchronous generator}!function@\spxentry{function}}\index{asynchronous generator@\spxentry{asynchronous generator}!asynchronous iterator@\spxentry{asynchronous iterator}}\ignorespaces {\hyperref[\detokenize{reference/compound_stmts:async-def}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async def}}}}} を使って定義され、 {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} 文を使用している関数やメソッドを \sphinxstyleemphasis{asynchronous generator function} と呼びます。 そのような関数は、呼び出されたとき、非同期イテレータオブジェクトを返します。 このオブジェクトは {\hyperref[\detokenize{reference/compound_stmts:async-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async for}}}}} 文で関数の本体を実行するのに使えます。 Calling the asynchronous iterator's {\hyperref[\detokenize{reference/datamodel:object.__anext__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{aiterator.\_\_anext\_\_}}}}} method will return an {\hyperref[\detokenize{glossary:term-awaitable}]{\sphinxtermref{\DUrole{xref,std,std-term}{awaitable}}}} which when awaited will execute until it provides a value using the {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} expression. When the function executes an empty {\hyperref[\detokenize{reference/simple_stmts:return}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{return}}}}} statement or falls off the end, a \sphinxcode{\sphinxupquote{StopAsyncIteration}} exception is raised and the asynchronous iterator will have reached the end of the set of values to be yielded. \item[{組み込み関数 (built\sphinxhyphen{}in function)}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!built\sphinxhyphen{}in function@\spxentry{built\sphinxhyphen{}in function}}\index{built\sphinxhyphen{}in function@\spxentry{built\sphinxhyphen{}in function}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!function@\spxentry{function}}\index{function@\spxentry{function}!オブジェクト@\spxentry{オブジェクト}}\index{C@\spxentry{C}!language@\spxentry{language}}\index{language@\spxentry{language}!C@\spxentry{C}}\ignorespaces 組み込み関数オブジェクトはC関数へのラッパーです。 組み込み関数の例は \sphinxcode{\sphinxupquote{len()}} や \sphinxcode{\sphinxupquote{math.sin()}} (\sphinxcode{\sphinxupquote{math}} は標準の組み込みモジュール) です。 引数の数や型は C 関数で決定されています。 読み出し専用の特殊属性: \sphinxcode{\sphinxupquote{\_\_doc\_\_}} は関数のドキュメンテーション文字列です。 ドキュメンテーションがない場合は \sphinxcode{\sphinxupquote{None}} になります; \sphinxcode{\sphinxupquote{\_\_name\_\_}} は関数の名前です; \sphinxcode{\sphinxupquote{\_\_self\_\_}} は \sphinxcode{\sphinxupquote{None}} に設定されています (組み込みメソッドの節も参照してください); \sphinxcode{\sphinxupquote{\_\_module\_\_}} は、関数が定義されているモジュールの名前です。 モジュール名がない場合は \sphinxcode{\sphinxupquote{None}} になります。 \item[{組み込みメソッド (built\sphinxhyphen{}in method)}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!built\sphinxhyphen{}in method@\spxentry{built\sphinxhyphen{}in method}}\index{built\sphinxhyphen{}in method@\spxentry{built\sphinxhyphen{}in method}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!method@\spxentry{method}}\index{method@\spxentry{method}!オブジェクト@\spxentry{オブジェクト}}\index{built\sphinxhyphen{}in@\spxentry{built\sphinxhyphen{}in}!method@\spxentry{method}}\index{method@\spxentry{method}!built\sphinxhyphen{}in@\spxentry{built\sphinxhyphen{}in}}\ignorespaces 実際には組み込み関数を別の形で隠蔽したもので、こちらの場合には C 関数に渡される何らかのオブジェクトを非明示的な外部引数として持っています。組み込みメソッドの例は、 \sphinxstyleemphasis{alist} をリストオブジェクトとしたときの \sphinxcode{\sphinxupquote{alist.append()}} です。この場合には、読み出し専用の属性 \sphinxcode{\sphinxupquote{\_\_self\_\_}} は \sphinxstyleemphasis{alist} で表されるオブジェクトになります。 \item[{クラス}] \leavevmode Classes are callable. These objects normally act as factories for new instances of themselves, but variations are possible for class types that override {\hyperref[\detokenize{reference/datamodel:object.__new__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_new\_\_()}}}}}. The arguments of the call are passed to {\hyperref[\detokenize{reference/datamodel:object.__new__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_new\_\_()}}}}} and, in the typical case, to {\hyperref[\detokenize{reference/datamodel:object.__init__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_init\_\_()}}}}} to initialize the new instance. \item[{クラスのインスタンス}] \leavevmode Instances of arbitrary classes can be made callable by defining a {\hyperref[\detokenize{reference/datamodel:object.__call__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_call\_\_()}}}}} method in their class. \end{description} \item[{モジュール}] \leavevmode \index{文@\spxentry{文}!import@\spxentry{import}}\index{import@\spxentry{import}!文@\spxentry{文}}\index{オブジェクト@\spxentry{オブジェクト}!module@\spxentry{module}}\index{module@\spxentry{module}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces モジュールは Python コードの基礎的な構成単位で、 {\hyperref[\detokenize{reference/simple_stmts:import}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{import}}}}} 文あるいは \sphinxcode{\sphinxupquote{importlib.import\_module()}} や組み込みの \sphinxcode{\sphinxupquote{\_\_import\_\_()}} のような関数を呼び出すことで起動される {\hyperref[\detokenize{reference/import:importsystem}]{\sphinxcrossref{\DUrole{std,std-ref}{import system}}}} によって作成されます。モジュールオブジェクトは、辞書オブジェクト (これは、モジュール内で定義された関数の \sphinxcode{\sphinxupquote{\_\_globals\_\_}} 属性から参照される辞書です) で実装された名前空間を持っています。属性の参照は、この辞書の検索に翻訳されます。例えば、 \sphinxcode{\sphinxupquote{m.x}} は \sphinxcode{\sphinxupquote{m.\_\_dict\_\_{[}"x"{]}}} と等価です。モジュールオブジェクトは、モジュールの初期化に使われるコードオブジェクトを含んでいません (初期化が終わればもう必要ないからです)。 属性の代入を行うと、モジュールの名前空間辞書の内容を更新します。例えば、 \sphinxcode{\sphinxupquote{m.x = 1}} は \sphinxcode{\sphinxupquote{m.\_\_dict\_\_{[}"x"{]} = 1}} と同じです。 \index{\_\_name\_\_ (module attribute)@\spxentry{\_\_name\_\_}\spxextra{module attribute}}\index{\_\_doc\_\_ (module attribute)@\spxentry{\_\_doc\_\_}\spxextra{module attribute}}\index{\_\_file\_\_ (module attribute)@\spxentry{\_\_file\_\_}\spxextra{module attribute}}\index{\_\_annotations\_\_ (module attribute)@\spxentry{\_\_annotations\_\_}\spxextra{module attribute}}\index{module@\spxentry{module}!namespace@\spxentry{namespace}}\index{namespace@\spxentry{namespace}!module@\spxentry{module}}\ignorespaces 定義済みの (書き込み可能な) 属性: {\hyperref[\detokenize{reference/import:__name__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_name\_\_}}}}} はモジュールの名前です; \sphinxcode{\sphinxupquote{\_\_doc\_\_}} は関数のドキュメンテーション文字列です。ドキュメンテーションがない場合は \sphinxcode{\sphinxupquote{None}} になります; \sphinxcode{\sphinxupquote{\_\_annotations\_\_}} (オプショナル) はモジュールの本体を実行しているときに収集した {\hyperref[\detokenize{glossary:term-variable-annotation}]{\sphinxtermref{\DUrole{xref,std,std-term}{変数アノテーション}}}} が入った辞書です; モジュールがファイルからロードされた場合、 {\hyperref[\detokenize{reference/import:__file__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_file\_\_}}}}} はロードされたモジュールファイルのパス名です。インタプリタに静的にリンクされている C モジュールのような特定の種類のモジュールでは、 {\hyperref[\detokenize{reference/import:__file__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_file\_\_}}}}} 属性は存在しないかもしれません; 共有ライブラリから動的にロードされた拡張モジュールの場合、この属性は 共有ライブラリファイルのパス名になります。 \index{\_\_dict\_\_ (module attribute)@\spxentry{\_\_dict\_\_}\spxextra{module attribute}}\ignorespaces 読み出し専用の特殊属性: \sphinxcode{\sphinxupquote{\_\_dict\_\_}} はモジュールの名前空間で、辞書オブジェクトです。 \sphinxstylestrong{CPython implementation detail:} CPython がモジュール辞書を削除する方法により、モジュール辞書が生きた参照を持っていたとしてもその辞書はモジュールがスコープから外れた時に削除されます。これを避けるには、辞書をコピーするか、辞書を直接使っている間モジュールを保持してください。 \item[{カスタムクラス型}] \leavevmode カスタムクラス型は通常、クラス定義 ({\hyperref[\detokenize{reference/compound_stmts:class}]{\sphinxcrossref{\DUrole{std,std-ref}{クラス定義}}}} 参照) で生成されます。クラスは辞書オブジェクトで実装された名前空間を持っています。クラス属性の参照は、この辞書に対する探索 (lookup) に翻訳されます。例えば、 \sphinxcode{\sphinxupquote{C.x}} は \sphinxcode{\sphinxupquote{C.\_\_dict\_\_{[}"x"{]}}} に翻訳されます (ただし、属性参照の意味を変えられる幾つかのフックがあります)。属性がこの探索で見つからないとき、その基底クラスで探索が続けられます。基底クラスのこの探索は、C3 メソッド解決順序 (MRO=method resolution order) を利用していて、複数の継承経路が共通の祖先につながる「ダイアモンド」継承構造があっても正しく動作します。 C3 MRO についてのより詳細な情報は、 2.3リリースに付属するドキュメント \sphinxurl{https://www.python.org/download/releases/2.3/mro/} にあります。 \index{オブジェクト@\spxentry{オブジェクト}!class@\spxentry{class}}\index{class@\spxentry{class}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!class instance@\spxentry{class instance}}\index{class instance@\spxentry{class instance}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!instance@\spxentry{instance}}\index{instance@\spxentry{instance}!オブジェクト@\spxentry{オブジェクト}}\index{class object@\spxentry{class object}!call@\spxentry{call}}\index{call@\spxentry{call}!class object@\spxentry{class object}}\index{container@\spxentry{container}}\index{オブジェクト@\spxentry{オブジェクト}!dictionary@\spxentry{dictionary}}\index{dictionary@\spxentry{dictionary}!オブジェクト@\spxentry{オブジェクト}}\index{class@\spxentry{class}!attribute@\spxentry{attribute}}\index{attribute@\spxentry{attribute}!class@\spxentry{class}}\ignorespaces クラス (\sphinxcode{\sphinxupquote{C}} とします) 属性参照がクラスメソッドオブジェクトを返そうとするときには、 そのオブジェクトは \sphinxcode{\sphinxupquote{\_\_self\_\_}} 属性が \sphinxcode{\sphinxupquote{C}} であるようなインスタンスメソッドオブジェクトに変換されます。 静的メソッドオブジェクトを返そうとするときには、静的メソッドオブジェクトでラップされたオブジェクトに変換されます。 {\hyperref[\detokenize{reference/datamodel:descriptors}]{\sphinxcrossref{\DUrole{std,std-ref}{デスクリプタ (descriptor) の実装}}}} 節を参照すると、また別の理由でクラスから取り出した属性と実際に \sphinxcode{\sphinxupquote{\_\_dict\_\_}} に保存されているものが異なることがあるのが分かります。 \index{class@\spxentry{class}!attribute assignment@\spxentry{attribute} \spxentry{assignment}}\index{attribute@\spxentry{attribute}!assignment, class@\spxentry{assignment}, \spxentry{class}}\index{assignment@\spxentry{assignment}!class attribute@\spxentry{class} \spxentry{attribute}}\ignorespaces クラス属性を代入すると、そのクラスの辞書だけが更新され、基底クラスの辞書は更新しません。 \index{class object@\spxentry{class object}!call@\spxentry{call}}\index{call@\spxentry{call}!class object@\spxentry{class object}}\ignorespaces クラスオブジェクトを呼び出す (上記を参照) と、クラスインスタンスを生成します (下記を参照)。 \index{\_\_name\_\_ (class attribute)@\spxentry{\_\_name\_\_}\spxextra{class attribute}}\index{\_\_module\_\_ (class attribute)@\spxentry{\_\_module\_\_}\spxextra{class attribute}}\index{\_\_dict\_\_ (class attribute)@\spxentry{\_\_dict\_\_}\spxextra{class attribute}}\index{\_\_bases\_\_ (class attribute)@\spxentry{\_\_bases\_\_}\spxextra{class attribute}}\index{\_\_doc\_\_ (class attribute)@\spxentry{\_\_doc\_\_}\spxextra{class attribute}}\index{\_\_annotations\_\_ (class attribute)@\spxentry{\_\_annotations\_\_}\spxextra{class attribute}}\ignorespaces 特殊属性: \sphinxcode{\sphinxupquote{\_\_name\_\_}} はクラス名です; \sphinxcode{\sphinxupquote{\_\_module\_\_}} はクラスが定義されたモジュール名です; \sphinxcode{\sphinxupquote{\_\_dict\_\_}} はクラスが持つ名前空間が入った辞書です; \sphinxcode{\sphinxupquote{\_\_bases\_\_}} は基底クラスからなるタプルで、基底クラスのリストに表れる順序で並んでいます; \sphinxcode{\sphinxupquote{\_\_doc\_\_}} はクラスのドキュメント文字列で、未定義の場合は None です; \sphinxcode{\sphinxupquote{\_\_annotations\_\_}} (オプショナル) はクラスの本体を実行しているときに収集した {\hyperref[\detokenize{glossary:term-variable-annotation}]{\sphinxtermref{\DUrole{xref,std,std-term}{変数アノテーション}}}} が入った辞書です。 \item[{クラスインスタンス (class instance)}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!class instance@\spxentry{class instance}}\index{class instance@\spxentry{class instance}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!instance@\spxentry{instance}}\index{instance@\spxentry{instance}!オブジェクト@\spxentry{オブジェクト}}\index{class@\spxentry{class}!instance@\spxentry{instance}}\index{instance@\spxentry{instance}!class@\spxentry{class}}\index{class instance@\spxentry{class instance}!attribute@\spxentry{attribute}}\index{attribute@\spxentry{attribute}!class instance@\spxentry{class instance}}\ignorespaces A class instance is created by calling a class object (see above). A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched. When an attribute is not found there, and the instance's class has an attribute by that name, the search continues with the class attributes. If a class attribute is found that is a user\sphinxhyphen{}defined function object, it is transformed into an instance method object whose \sphinxcode{\sphinxupquote{\_\_self\_\_}} attribute is the instance. Static method and class method objects are also transformed; see above under "Classes". See section {\hyperref[\detokenize{reference/datamodel:descriptors}]{\sphinxcrossref{\DUrole{std,std-ref}{デスクリプタ (descriptor) の実装}}}} for another way in which attributes of a class retrieved via its instances may differ from the objects actually stored in the class's \sphinxcode{\sphinxupquote{\_\_dict\_\_}}. If no class attribute is found, and the object's class has a {\hyperref[\detokenize{reference/datamodel:object.__getattr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getattr\_\_()}}}}} method, that is called to satisfy the lookup. \index{class instance@\spxentry{class instance}!attribute assignment@\spxentry{attribute} \spxentry{assignment}}\index{attribute@\spxentry{attribute}!assignment, class instance@\spxentry{assignment}, \spxentry{class instance}}\index{assignment@\spxentry{assignment}!class instance attribute@\spxentry{class instance} \spxentry{attribute}}\ignorespaces Attribute assignments and deletions update the instance's dictionary, never a class's dictionary. If the class has a {\hyperref[\detokenize{reference/datamodel:object.__setattr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_setattr\_\_()}}}}} or {\hyperref[\detokenize{reference/datamodel:object.__delattr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_delattr\_\_()}}}}} method, this is called instead of updating the instance dictionary directly. \index{オブジェクト@\spxentry{オブジェクト}!numeric@\spxentry{numeric}}\index{numeric@\spxentry{numeric}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!sequence@\spxentry{sequence}}\index{sequence@\spxentry{sequence}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!mapping@\spxentry{mapping}}\index{mapping@\spxentry{mapping}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces クラスインスタンスは、ある特定の名前のメソッドを持っている場合、数値型やシーケンス型、あるいはマップ型のように振舞うことができます。 {\hyperref[\detokenize{reference/datamodel:specialnames}]{\sphinxcrossref{\DUrole{std,std-ref}{特殊メソッド名}}}} を参照してください。 \index{\_\_dict\_\_ (instance attribute)@\spxentry{\_\_dict\_\_}\spxextra{instance attribute}}\index{\_\_class\_\_ (instance attribute)@\spxentry{\_\_class\_\_}\spxextra{instance attribute}}\ignorespaces 特殊属性: \sphinxcode{\sphinxupquote{\_\_dict\_\_}} は属性の辞書です; \sphinxcode{\sphinxupquote{\_\_class\_\_}} はインスタンスのクラスです。 \item[{I/O オブジェクト (ファイルオブジェクトの別名)}] \leavevmode \index{組み込み関数@\spxentry{組み込み関数}!open@\spxentry{open}}\index{open@\spxentry{open}!組み込み関数@\spxentry{組み込み関数}}\index{モジュール@\spxentry{モジュール}!io@\spxentry{io}}\index{io@\spxentry{io}!モジュール@\spxentry{モジュール}}\index{popen() (in module os)@\spxentry{popen()}\spxextra{in module os}}\index{makefile() (socket method)@\spxentry{makefile()}\spxextra{socket method}}\index{sys.stdin@\spxentry{sys.stdin}}\index{sys.stdout@\spxentry{sys.stdout}}\index{sys.stderr@\spxentry{sys.stderr}}\index{stdio@\spxentry{stdio}}\index{stdin (in module sys)@\spxentry{stdin}\spxextra{in module sys}}\index{stdout (in module sys)@\spxentry{stdout}\spxextra{in module sys}}\index{stderr (in module sys)@\spxentry{stderr}\spxextra{in module sys}}\ignorespaces {\hyperref[\detokenize{glossary:term-file-object}]{\sphinxtermref{\DUrole{xref,std,std-term}{file object}}}} は開かれたファイルを表します。ファイルオブジェクトを作るための様々なショートカットがあります: \sphinxcode{\sphinxupquote{open()}} 組み込み関数、 \sphinxcode{\sphinxupquote{os.popen()}} 、 \sphinxcode{\sphinxupquote{os.fdopen()}} 、ソケットオブジェクトの \sphinxcode{\sphinxupquote{makefile()}} メソッド (あるいは拡張モジュールから提供される他の関数やメソッド) 。 オブジェクト \sphinxcode{\sphinxupquote{sys.stdin}} 、 \sphinxcode{\sphinxupquote{sys.stdout}} および \sphinxcode{\sphinxupquote{sys.stderr}} は、インタプリタの標準入力、標準出力、および標準エラー出力ストリームに対応するファイルオブジェクトに初期化されます。これらはすべてテキストモードで開かれ、 \sphinxcode{\sphinxupquote{io.TextIOBase}} 抽象クラスによって定義されたインターフェースに従います。 \item[{内部型 (internal type)}] \leavevmode \index{internal type@\spxentry{internal type}}\index{types, internal@\spxentry{types, internal}}\ignorespaces インタプリタが内部的に使っているいくつかの型は、ユーザに公開されています。これらの定義は将来のインタプリタのバージョンでは変更される可能性がありますが、ここでは記述の完全性のために触れておきます。 \index{bytecode@\spxentry{bytecode}}\index{object@\spxentry{object}!code@\spxentry{code}}\index{code object@\spxentry{code object}}\ignorespaces \begin{description} \item[{コードオブジェクト}] \leavevmode コードオブジェクトは \sphinxstyleemphasis{バイトコンパイルされた (byte\sphinxhyphen{}compiled)} 実行可能な Python コード、別名 {\hyperref[\detokenize{glossary:term-bytecode}]{\sphinxtermref{\DUrole{xref,std,std-term}{バイトコード}}}} を表現します。コードオブジェクトと関数オブジェクトの違いは、関数オブジェクトが関数のグローバル変数 (関数を定義しているモジュールのグローバル) に対して明示的な参照を持っているのに対し、コードオブジェクトにはコンテキストがないということです; また、関数オブジェクトではデフォルト引数値を記憶できますが、コードオブジェクトではできません (実行時に計算される値を表現するため)。関数オブジェクトと違い、コードオブジェクトは変更不可能で、変更可能なオブジェクトへの参照を (直接、間接に関わらず) 含みません。 \index{co\_argcount (code object attribute)@\spxentry{co\_argcount}\spxextra{code object attribute}}\index{co\_posonlyargcount (code object attribute)@\spxentry{co\_posonlyargcount}\spxextra{code object attribute}}\index{co\_kwonlyargcount (code object attribute)@\spxentry{co\_kwonlyargcount}\spxextra{code object attribute}}\index{co\_code (code object attribute)@\spxentry{co\_code}\spxextra{code object attribute}}\index{co\_consts (code object attribute)@\spxentry{co\_consts}\spxextra{code object attribute}}\index{co\_filename (code object attribute)@\spxentry{co\_filename}\spxextra{code object attribute}}\index{co\_firstlineno (code object attribute)@\spxentry{co\_firstlineno}\spxextra{code object attribute}}\index{co\_flags (code object attribute)@\spxentry{co\_flags}\spxextra{code object attribute}}\index{co\_lnotab (code object attribute)@\spxentry{co\_lnotab}\spxextra{code object attribute}}\index{co\_name (code object attribute)@\spxentry{co\_name}\spxextra{code object attribute}}\index{co\_names (code object attribute)@\spxentry{co\_names}\spxextra{code object attribute}}\index{co\_nlocals (code object attribute)@\spxentry{co\_nlocals}\spxextra{code object attribute}}\index{co\_stacksize (code object attribute)@\spxentry{co\_stacksize}\spxextra{code object attribute}}\index{co\_varnames (code object attribute)@\spxentry{co\_varnames}\spxextra{code object attribute}}\index{co\_cellvars (code object attribute)@\spxentry{co\_cellvars}\spxextra{code object attribute}}\index{co\_freevars (code object attribute)@\spxentry{co\_freevars}\spxextra{code object attribute}}\ignorespaces 読み出し専用の特殊属性: \sphinxcode{\sphinxupquote{co\_name}} は関数名、 \sphinxcode{\sphinxupquote{co\_argcount}} は位置引数 (位置専用引数とデフォルト値を持つ引数を含む) の総数、 \sphinxcode{\sphinxupquote{co\_posonlyargcount}} は位置専用引数 (デフォルト値を持つ引数を含む) の数、 \sphinxcode{\sphinxupquote{co\_nlocals}} は関数が使う (引数を含めた) ローカル変数の数、 \sphinxcode{\sphinxupquote{co\_varnames}} はローカル変数名を格納したタプル (引数名から始まる)、 \sphinxcode{\sphinxupquote{co\_cellvars}} はネストされた関数で参照されているローカル変数の名前を格納したタプル、 \sphinxcode{\sphinxupquote{co\_freevars}} は自由変数の名前を格納したタプル、 \sphinxcode{\sphinxupquote{co\_code}} はバイトコード列を表現している文字列、 \sphinxcode{\sphinxupquote{co\_consts}} はバイトコードで使われているリテラルを格納したタプル、 \sphinxcode{\sphinxupquote{co\_names}} はバイトコードで使われている名前の入ったタプル、 \sphinxcode{\sphinxupquote{co\_filename}} はバイトコードのコンパイルが行われたファイル名、 \sphinxcode{\sphinxupquote{co\_firstlineno}} は関数の最初の行番号、 \sphinxcode{\sphinxupquote{co\_lnotab}} はバイトコードオフセットから行番号への対応付けをコード化した文字列 (詳細についてはインタープリタのソースコードを参照してください)、 \sphinxcode{\sphinxupquote{co\_stacksize}} は関数で必要なスタックサイズ、 \sphinxcode{\sphinxupquote{co\_flags}} はインタプリタ用の様々なフラグをコード化した整数。 \index{オブジェクト@\spxentry{オブジェクト}!generator@\spxentry{generator}}\index{generator@\spxentry{generator}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces 以下のフラグビットが \sphinxcode{\sphinxupquote{co\_flags}} で定義されています: \sphinxcode{\sphinxupquote{0x04}} ビットは、関数が \sphinxcode{\sphinxupquote{*arguments}} 構文を使って任意の数の位置引数を受理できる場合に立てられます; \sphinxcode{\sphinxupquote{0x08}} ビットは、関数が \sphinxcode{\sphinxupquote{**keywords}} 構文を使ってキーワード引数を受理できる場合に立てられます; \sphinxcode{\sphinxupquote{0x20}} ビットは、関数がジェネレータである場合に立てられます。 将来機能 (future feature) 宣言 (\sphinxcode{\sphinxupquote{from \_\_future\_\_ import division}}) もまた、 \sphinxcode{\sphinxupquote{co\_flags}} のビットを立てることで、コードオブジェクトが特定の機能を有効にしてコンパイルされていることを示します: \sphinxcode{\sphinxupquote{0x2000}} ビットは、関数が将来機能を有効にしてコンパイルされている場合に立てられます; 以前のバージョンの Python では、 \sphinxcode{\sphinxupquote{0x10}} および \sphinxcode{\sphinxupquote{0x1000}} ビットが使われていました。 \sphinxcode{\sphinxupquote{co\_flags}} のその他のビットは将来に内部的に利用するために予約されています。 \index{documentation string@\spxentry{documentation string}}\ignorespaces コードオブジェクトが関数を表現している場合、 \sphinxcode{\sphinxupquote{co\_consts}} の最初の要素は関数のドキュメンテーション文字列になります。ドキュメンテーション文字列が定義されていない場合には \sphinxcode{\sphinxupquote{None}} になります。 \end{description} \phantomsection\label{\detokenize{reference/datamodel:frame-objects}}\begin{description} \item[{フレーム (frame) オブジェクト}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!frame@\spxentry{frame}}\index{frame@\spxentry{frame}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces フレームオブジェクトは実行フレーム (execution frame) を表します。 実行フレームはトレースバックオブジェクト (下記参照) 内に出現し、登録されたトレース関数に渡されます。 \index{f\_back (frame attribute)@\spxentry{f\_back}\spxextra{frame attribute}}\index{f\_code (frame attribute)@\spxentry{f\_code}\spxextra{frame attribute}}\index{f\_globals (frame attribute)@\spxentry{f\_globals}\spxextra{frame attribute}}\index{f\_locals (frame attribute)@\spxentry{f\_locals}\spxextra{frame attribute}}\index{f\_lasti (frame attribute)@\spxentry{f\_lasti}\spxextra{frame attribute}}\index{f\_builtins (frame attribute)@\spxentry{f\_builtins}\spxextra{frame attribute}}\ignorespaces 読み出し専用の特殊属性: \sphinxcode{\sphinxupquote{f\_back}} は直前のスタックフレーム (呼び出し側の方向) で、それがスタックフレームの最下段なら \sphinxcode{\sphinxupquote{None}} です; \sphinxcode{\sphinxupquote{f\_code}} はそのフレームで実行されているコードオブジェクトです; \sphinxcode{\sphinxupquote{f\_locals}} はローカル変数の探索に使われる辞書です; \sphinxcode{\sphinxupquote{f\_globals}} はグローバル変数に使われます; \sphinxcode{\sphinxupquote{f\_builtins}} は組み込みの (Python 固有の) 名前に使われます; \sphinxcode{\sphinxupquote{f\_lasti}} は厳密な命令コード (コードオブジェクトのバイトコード文字列へのインデックス) です。 \sphinxcode{\sphinxupquote{f\_code}} へのアクセスは \sphinxcode{\sphinxupquote{object.\_\_getattr\_\_}} に \sphinxcode{\sphinxupquote{obj}} と \sphinxcode{\sphinxupquote{"f\_code"}} を渡して行いますが、 \DUrole{xref,std,std-ref}{監査イベント} を送出します。 \index{f\_trace (frame attribute)@\spxentry{f\_trace}\spxextra{frame attribute}}\index{f\_trace\_lines (frame attribute)@\spxentry{f\_trace\_lines}\spxextra{frame attribute}}\index{f\_trace\_opcodes (frame attribute)@\spxentry{f\_trace\_opcodes}\spxextra{frame attribute}}\index{f\_lineno (frame attribute)@\spxentry{f\_lineno}\spxextra{frame attribute}}\ignorespaces 特別な書き込み可能な属性: \sphinxcode{\sphinxupquote{f\_trace}} は \sphinxcode{\sphinxupquote{None}} でない場合は、コードの実行中に様々なイベントで呼び出される関数です (デバッガが利用します)。 通常は、ソースの新しい行ごとにイベントが発行されますが、 \sphinxcode{\sphinxupquote{f\_trace\_lines}} を \sphinxcode{\sphinxupquote{False}} に設定することでイベントの発行を無効化できます。 実装は \sphinxcode{\sphinxupquote{f\_trace\_opcodes}} を \sphinxcode{\sphinxupquote{True}} に設定して、命令コードごとのイベントの要求を許可している \sphinxstyleemphasis{かもしれません} 。 これは、トレース関数によって送出された例外がトレースされている関数に漏れ出た場合、未定義なインタープリタの振る舞いにつながるかもしれないことに注意してください。 \sphinxcode{\sphinxupquote{f\_lineno}} はフレーム中における現在の行番号です \sphinxhyphen{}\sphinxhyphen{}\sphinxhyphen{} トレース関数 (trace function) 側でこの値に書き込みを行うと、指定した行にジャンプします (最下段の実行フレームにいるときのみ)。デバッガでは、 f\_fileno を書き込むことで、ジャンプ命令 (Set Next Statement 命令とも) を実装できます。 フレームオブジェクトはメソッドを一つサポートします: \index{clear() (frame のメソッド)@\spxentry{clear()}\spxextra{frame のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:frame.clear}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{frame.}}\sphinxbfcode{\sphinxupquote{clear}}}{}{} このメソッドはフレームが保持しているローカル変数への参照を全て削除します。 また、フレームがジェネレータに属していた場合は、ジェネレータにも終了処理が行われます。 これによってフレームオブジェクトを含んだ循環参照が解消されるようになります (例えば、例外を捕捉し、後で使うためにトレースバックを保存する場合)。 フレームが現在実行中の場合 \sphinxcode{\sphinxupquote{RuntimeError}} が送出されます。 \DUrole{versionmodified,added}{バージョン 3.4 で追加.} \end{fulllineitems} \end{description} \phantomsection\label{\detokenize{reference/datamodel:traceback-objects}}\begin{description} \item[{トレースバック (traceback) オブジェクト}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!traceback@\spxentry{traceback}}\index{traceback@\spxentry{traceback}!オブジェクト@\spxentry{オブジェクト}}\index{stack@\spxentry{stack}!trace@\spxentry{trace}}\index{trace@\spxentry{trace}!stack@\spxentry{stack}}\index{exception@\spxentry{exception}!handler@\spxentry{handler}}\index{handler@\spxentry{handler}!exception@\spxentry{exception}}\index{execution@\spxentry{execution}!stack@\spxentry{stack}}\index{stack@\spxentry{stack}!execution@\spxentry{execution}}\index{exc\_info (in module sys)@\spxentry{exc\_info}\spxextra{in module sys}}\index{last\_traceback (in module sys)@\spxentry{last\_traceback}\spxextra{in module sys}}\index{sys.exc\_info@\spxentry{sys.exc\_info}}\index{sys.last\_traceback@\spxentry{sys.last\_traceback}}\ignorespaces トレースバックオブジェクトは例外のスタックトレースを表現します。 トレースバックオブジェクトは例外が起きたときに暗黙的に作成されたり、 \sphinxcode{\sphinxupquote{types.TracebackType}} を呼び出して明示的にも作成されたりします。 暗黙的に作成されたトレースバックでは、例外ハンドラの検索が実行スタックを戻っていく際、戻ったレベル毎に、トレースバックオブジェクトが現在のトレースバックの前に挿入されます。 例外ハンドラに入ると、スタックトレースをプログラム側で利用できるようになります。({\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\DUrole{std,std-ref}{try 文}}}} を参照。) トレースバックは、 \sphinxcode{\sphinxupquote{sys.exc\_info()}} が返すタプルの三番目の要素や、捕捉した例外の \sphinxcode{\sphinxupquote{\_\_traceback\_\_}} 属性として得られます。 プログラムに適切なハンドラがないとき、スタックトレースは (うまく書式化されて) 標準エラーストリームに書き出されます; インタプリタが対話的に実行されている場合、 \sphinxcode{\sphinxupquote{sys.last\_traceback}} として得ることもできます。 明示的に作成されたトレースバックでは、 \sphinxcode{\sphinxupquote{tb\_next}} 属性がリンクされスタックトレース全体を形成する方法の決定は、トレースバックの作成者に任されます。 \index{tb\_frame (traceback attribute)@\spxentry{tb\_frame}\spxextra{traceback attribute}}\index{tb\_lineno (traceback attribute)@\spxentry{tb\_lineno}\spxextra{traceback attribute}}\index{tb\_lasti (traceback attribute)@\spxentry{tb\_lasti}\spxextra{traceback attribute}}\index{文@\spxentry{文}!try@\spxentry{try}}\index{try@\spxentry{try}!文@\spxentry{文}}\ignorespaces 読み出し専用の特殊属性: \sphinxcode{\sphinxupquote{tb\_frame}} は現在のレベルにおける実行フレームを指します; \sphinxcode{\sphinxupquote{tb\_lineno}} は例外の発生した行番号です; \sphinxcode{\sphinxupquote{tb\_lasti}} は厳密な命令コードです。トレースバック内の行番号や最後に実行された命令は、 {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} 文内で例外が発生し、かつ対応する {\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}} 節や {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節がない場合には、フレームオブジェクト内の行番号とは異なるかもしれません。 \sphinxcode{\sphinxupquote{tb\_frame}} へのアクセスは \sphinxcode{\sphinxupquote{object.\_\_getattr\_\_}} に \sphinxcode{\sphinxupquote{obj}} と \sphinxcode{\sphinxupquote{"tb\_frame"}} を渡して行いますが、 \DUrole{xref,std,std-ref}{監査イベント} を送出します。 \index{tb\_next (traceback attribute)@\spxentry{tb\_next}\spxextra{traceback attribute}}\ignorespaces 書き込み可能な特殊属性: \sphinxcode{\sphinxupquote{tb\_next}} はスタックトレースの次のレベル (例外が発生したフレームの方向) か、あるいは次のレベルが無い場合は \sphinxcode{\sphinxupquote{None}} です。 \DUrole{versionmodified,changed}{バージョン 3.7 で変更: }トレースバックオブジェクトは Python コードから明示的にインスタンス化できるようになり、既存のインスタンスの \sphinxcode{\sphinxupquote{tb\_next}} 属性は更新できるようになりました。 \item[{スライス (slice) オブジェクト}] \leavevmode \index{組み込み関数@\spxentry{組み込み関数}!slice@\spxentry{slice}}\index{slice@\spxentry{slice}!組み込み関数@\spxentry{組み込み関数}}\ignorespaces Slice objects are used to represent slices for {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} methods. They are also created by the built\sphinxhyphen{}in \sphinxcode{\sphinxupquote{slice()}} function. \index{start (slice object attribute)@\spxentry{start}\spxextra{slice object attribute}}\index{stop (slice object attribute)@\spxentry{stop}\spxextra{slice object attribute}}\index{step (slice object attribute)@\spxentry{step}\spxextra{slice object attribute}}\ignorespaces 読み出し専用の特殊属性: \sphinxcode{\sphinxupquote{start}} は下限です; \sphinxcode{\sphinxupquote{stop}} は上限です; \sphinxcode{\sphinxupquote{step}} はステップの値です; それぞれ省略された場合は \sphinxcode{\sphinxupquote{None}} となっています。これらの属性は任意の型を持てます。 スライスオブジェクトはメソッドを一つサポートします: \index{indices() (slice のメソッド)@\spxentry{indices()}\spxextra{slice のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:slice.indices}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{slice.}}\sphinxbfcode{\sphinxupquote{indices}}}{\emph{self}, \emph{length}}{} このメソッドは単一の整数引数 \sphinxstyleemphasis{length} を取り、スライスオブジェクトが \sphinxstyleemphasis{length} 要素のシーケンスに適用されたときに表現する、スライスに関する情報を計算します。このメソッドは 3 つの整数からなるタプルを返します; それぞれ \sphinxstyleemphasis{start} および \sphinxstyleemphasis{stop} のインデックスと、\sphinxstyleemphasis{step} すなわちスライスのまたぎ幅です。インデックス値がないか、範囲外の値であれば、通常のスライスと変わらないやりかたで扱われます。 \end{fulllineitems} \item[{静的メソッド (static method) オブジェクト}] \leavevmode 静的メソッドは、上で説明したような関数オブジェクトからメソッドオブジェクトへの変換を阻止するための方法を提供します。静的メソッドオブジェクトは他の何らかのオブジェクト、通常はユーザ定義メソッドオブジェクトを包むラッパーです。静的メソッドをクラスやクラスインスタンスから取得すると、実際に返されるオブジェクトはラップされたオブジェクトになり、それ以上は変換の対象にはなりません。静的メソッドオブジェクトは通常呼び出し可能なオブジェクトをラップしますが、静的オブジェクト自体は呼び出すことができません。静的オブジェクトは組み込みコンストラクタ \sphinxcode{\sphinxupquote{staticmethod()}} で生成されます。 \item[{クラスメソッドオブジェクト}] \leavevmode クラスメソッドオブジェクトは、静的メソッドオブジェクトに似て、別のオブジェクトを包むラッパーであり、そのオブジェクトをクラスやクラスインスタンスから取り出す方法を代替します。このようにして取得したクラスメソッドオブジェクトの動作については、上の "ユーザ定義メソッド (user\sphinxhyphen{}defined method)" で説明されています。クラスメソッドオブジェクトは組み込みのコンストラクタ \sphinxcode{\sphinxupquote{classmethod()}} で生成されます。 \end{description} \end{description} \section{特殊メソッド名} \label{\detokenize{reference/datamodel:special-method-names}}\label{\detokenize{reference/datamodel:specialnames}} \index{operator@\spxentry{operator}!overloading@\spxentry{overloading}}\index{overloading@\spxentry{overloading}!operator@\spxentry{operator}}\index{\_\_getitem\_\_() (mapping object method)@\spxentry{\_\_getitem\_\_()}\spxextra{mapping object method}}\ignorespaces A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python's approach to \sphinxstyleemphasis{operator overloading}, allowing classes to define their own behavior with respect to language operators. For instance, if a class defines a method named {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}}, and \sphinxcode{\sphinxupquote{x}} is an instance of this class, then \sphinxcode{\sphinxupquote{x{[}i{]}}} is roughly equivalent to \sphinxcode{\sphinxupquote{type(x).\_\_getitem\_\_(x, i)}}. Except where mentioned, attempts to execute an operation raise an exception when no appropriate method is defined (typically \sphinxcode{\sphinxupquote{AttributeError}} or \sphinxcode{\sphinxupquote{TypeError}}). Setting a special method to \sphinxcode{\sphinxupquote{None}} indicates that the corresponding operation is not available. For example, if a class sets {\hyperref[\detokenize{reference/datamodel:object.__iter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_iter\_\_()}}}}} to \sphinxcode{\sphinxupquote{None}}, the class is not iterable, so calling \sphinxcode{\sphinxupquote{iter()}} on its instances will raise a \sphinxcode{\sphinxupquote{TypeError}} (without falling back to {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}}). % \begin{footnote}[2]\sphinxAtStartFootnote The {\hyperref[\detokenize{reference/datamodel:object.__hash__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_hash\_\_()}}}}}, {\hyperref[\detokenize{reference/datamodel:object.__iter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_iter\_\_()}}}}}, {\hyperref[\detokenize{reference/datamodel:object.__reversed__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_reversed\_\_()}}}}}, and {\hyperref[\detokenize{reference/datamodel:object.__contains__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_contains\_\_()}}}}} methods have special handling for this; others will still raise a \sphinxcode{\sphinxupquote{TypeError}}, but may do so by relying on the behavior that \sphinxcode{\sphinxupquote{None}} is not callable. % \end{footnote} 組み込み型をエミュレートするクラスを実装するときは、模範とされるオブジェクトにとって意味がある範囲に実装をとどめるのが重要です。例えば、あるシーケンスは個々の要素の取得はきちんと動くかもしれませんが、スライスの展開が意味をなさないかもしれません。 (W3C のドキュメントオブジェクトモデルにある \sphinxcode{\sphinxupquote{NodeList}} インターフェースがその一例です。) \subsection{基本的なカスタマイズ} \label{\detokenize{reference/datamodel:basic-customization}}\label{\detokenize{reference/datamodel:customization}}\index{\_\_new\_\_() (object のメソッド)@\spxentry{\_\_new\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__new__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_new\_\_}}}{\emph{cls}\sphinxoptional{, \emph{...}}}{}~ \index{subclassing@\spxentry{subclassing}!immutable types@\spxentry{immutable types}}\index{immutable types@\spxentry{immutable types}!subclassing@\spxentry{subclassing}}\ignorespaces クラス \sphinxstyleemphasis{cls} の新しいインスタンスを作るために呼び出されます。 {\hyperref[\detokenize{reference/datamodel:object.__new__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_new\_\_()}}}}} は静的メソッドで (このメソッドは特別扱いされているので、明示的に静的メソッドと宣言する必要はありません)、インスタンスを生成するよう要求されているクラスを第一引数にとります。残りの引数はオブジェクトのコンストラクタの式 (クラスの呼び出し文) に渡されます。 {\hyperref[\detokenize{reference/datamodel:object.__new__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_new\_\_()}}}}} の戻り値は新しいオブジェクトのインスタンス (通常は \sphinxstyleemphasis{cls} のインスタンス) でなければなりません。 典型的な実装では、クラスの新たなインスタンスを生成するときには \sphinxcode{\sphinxupquote{super().\_\_new\_\_(cls{[}, ...{]})}} に適切な引数を指定してスーパクラスの {\hyperref[\detokenize{reference/datamodel:object.__new__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_new\_\_()}}}}} メソッドを呼び出し、新たに生成されたインスタンスに必要な変更を加えてから返します。 If {\hyperref[\detokenize{reference/datamodel:object.__new__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_new\_\_()}}}}} is invoked during object construction and it returns an instance of \sphinxstyleemphasis{cls}, then the new instance’s {\hyperref[\detokenize{reference/datamodel:object.__init__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_init\_\_()}}}}} method will be invoked like \sphinxcode{\sphinxupquote{\_\_init\_\_(self{[}, ...{]})}}, where \sphinxstyleemphasis{self} is the new instance and the remaining arguments are the same as were passed to the object constructor. {\hyperref[\detokenize{reference/datamodel:object.__new__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_new\_\_()}}}}} が \sphinxstyleemphasis{cls} のインスタンスを返さない場合、インスタンスの {\hyperref[\detokenize{reference/datamodel:object.__init__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_init\_\_()}}}}} メソッドは呼び出されません。 {\hyperref[\detokenize{reference/datamodel:object.__new__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_new\_\_()}}}}} の主な目的は、変更不能な型 (int, str, tuple など) のサブクラスでインスタンス生成をカスタマイズすることにあります。また、クラス生成をカスタマイズするために、カスタムのメタクラスでよくオーバーライドされます。 \end{fulllineitems} \index{\_\_init\_\_() (object のメソッド)@\spxentry{\_\_init\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__init__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_init\_\_}}}{\emph{self}\sphinxoptional{, \emph{...}}}{}~ \index{class@\spxentry{class}!constructor@\spxentry{constructor}}\index{constructor@\spxentry{constructor}!class@\spxentry{class}}\ignorespaces インスタンスが ({\hyperref[\detokenize{reference/datamodel:object.__new__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_new\_\_()}}}}} によって) 生成された後、それが呼び出し元に返される前に呼び出されます。引数はクラスのコンストラクタ式に渡したものです。基底クラスとその派生クラスがともに {\hyperref[\detokenize{reference/datamodel:object.__init__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_init\_\_()}}}}} メソッドを持つ場合、派生クラスの {\hyperref[\detokenize{reference/datamodel:object.__init__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_init\_\_()}}}}} メソッドは基底クラスの {\hyperref[\detokenize{reference/datamodel:object.__init__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_init\_\_()}}}}} メソッドを明示的に呼び出して、インスタンスの基底クラス部分が適切に初期化されること保証しなければなりません。例えば、 \sphinxcode{\sphinxupquote{super().\_\_init\_\_({[}args...{]})}} 。 {\hyperref[\detokenize{reference/datamodel:object.__new__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_new\_\_()}}}}} と {\hyperref[\detokenize{reference/datamodel:object.__init__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_init\_\_()}}}}} は連携してオブジェクトを構成する ({\hyperref[\detokenize{reference/datamodel:object.__new__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_new\_\_()}}}}} が作成し、 {\hyperref[\detokenize{reference/datamodel:object.__init__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_init\_\_()}}}}} がそれをカスタマイズする) ので、 {\hyperref[\detokenize{reference/datamodel:object.__init__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_init\_\_()}}}}} から非 \sphinxcode{\sphinxupquote{None}} 値を返してはいけません; そうしてしまうと、実行時に \sphinxcode{\sphinxupquote{TypeError}} が送出されてしまいます。 \end{fulllineitems} \index{\_\_del\_\_() (object のメソッド)@\spxentry{\_\_del\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__del__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_del\_\_}}}{\emph{self}}{}~ \index{destructor@\spxentry{destructor}}\index{finalizer@\spxentry{finalizer}}\index{文@\spxentry{文}!del@\spxentry{del}}\index{del@\spxentry{del}!文@\spxentry{文}}\ignorespaces インスタンスが破棄されるときに呼び出されます。 これはファイナライザや (適切ではありませんが) デストラクタとも呼ばれます。 基底クラスが {\hyperref[\detokenize{reference/datamodel:object.__del__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_del\_\_()}}}}} メソッドを持っている場合は、派生クラスの {\hyperref[\detokenize{reference/datamodel:object.__del__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_del\_\_()}}}}} メソッドは何であれ、基底クラスの {\hyperref[\detokenize{reference/datamodel:object.__del__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_del\_\_()}}}}} メソッドを明示的に呼び出して、インスタンスの基底クラス部分をきちんと確実に削除しなければなりません。 {\hyperref[\detokenize{reference/datamodel:object.__del__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_del\_\_()}}}}} メソッドが破棄しようとしているインスタンスへの新しい参照を作り、破棄を送らせることは (推奨されないものの) 可能です。 これはオブジェクトの \sphinxstyleemphasis{復活} と呼ばれます。 復活したオブジェクトが再度破棄される直前に {\hyperref[\detokenize{reference/datamodel:object.__del__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_del\_\_()}}}}} が呼び出されるかどうかは実装依存です; 現在の {\hyperref[\detokenize{glossary:term-cpython}]{\sphinxtermref{\DUrole{xref,std,std-term}{CPython}}}} の実装では最初の一回しか呼び出されません。 インタプリタが終了したときに、残存しているオブジェクトの {\hyperref[\detokenize{reference/datamodel:object.__del__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_del\_\_()}}}}} メソッドが呼び出される保証はありません。 \begin{sphinxadmonition}{note}{注釈:} \sphinxcode{\sphinxupquote{del x}} は直接 \sphinxcode{\sphinxupquote{x.\_\_del\_\_()}} を呼び出しません \sphinxhyphen{}\sphinxhyphen{}\sphinxhyphen{} 前者は \sphinxcode{\sphinxupquote{x}} の参照カウントを 1 つ減らし、後者は \sphinxcode{\sphinxupquote{x}} の参照カウントが 0 まで落ちたときのみ呼び出されます。 \end{sphinxadmonition} \sphinxstylestrong{CPython implementation detail:} It is possible for a reference cycle to prevent the reference count of an object from going to zero. In this case, the cycle will be later detected and deleted by the {\hyperref[\detokenize{glossary:term-garbage-collection}]{\sphinxtermref{\DUrole{xref,std,std-term}{cyclic garbage collector}}}}. A common cause of reference cycles is when an exception has been caught in a local variable. The frame's locals then reference the exception, which references its own traceback, which references the locals of all frames caught in the traceback. \sphinxstrong{参考:} \sphinxcode{\sphinxupquote{gc}} モジュールのドキュメント。 \begin{sphinxadmonition}{warning}{警告:} メソッド {\hyperref[\detokenize{reference/datamodel:object.__del__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_del\_\_()}}}}} は不安定な状況で呼び出されるため、実行中に発生した例外は無視され、代わりに \sphinxcode{\sphinxupquote{sys.stderr}} に警告が表示されます。特に: \begin{itemize} \item {} {\hyperref[\detokenize{reference/datamodel:object.__del__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_del\_\_()}}}}} は、任意のコードが実行されているときに、任意のスレッドから呼び出せます。 {\hyperref[\detokenize{reference/datamodel:object.__del__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_del\_\_()}}}}} で、ロックを取ったり、ブロックするリソースを呼び出したりする必要がある場合、 {\hyperref[\detokenize{reference/datamodel:object.__del__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_del\_\_()}}}}} の実行により中断されたコードにより、そのリソースが既に取得されていて、デッドロックが起きるかもしれません。 \item {} {\hyperref[\detokenize{reference/datamodel:object.__del__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_del\_\_()}}}}} は、インタプリタのシャットダウン中に実行できます。 従って、(他のモジュールも含めた) アクセスする必要があるグローバル変数はすでに削除されているか、 \sphinxcode{\sphinxupquote{None}} に設定されているかもしれません。 Python は、単一のアンダースコアで始まる名前のグローバルオブジェクトは、他のグローバル変数が削除される前にモジュールから削除されることを保証します; そのようなグローバル変数への他からの参照が存在しない場合、{\hyperref[\detokenize{reference/datamodel:object.__del__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_del\_\_()}}}}} メソッドが呼ばれた時点で、インポートされたモジュールがまだ利用可能であることを保証するのに役立つかもしれません。 \end{itemize} \end{sphinxadmonition} \index{repr() (built\sphinxhyphen{}in function)@\spxentry{repr()}\spxextra{built\sphinxhyphen{}in function}!\_\_repr\_\_() (object method)@\spxentry{\_\_repr\_\_()}\spxextra{object method}}\ignorespaces \end{fulllineitems} \index{\_\_repr\_\_() (object のメソッド)@\spxentry{\_\_repr\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__repr__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_repr\_\_}}}{\emph{self}}{} \sphinxcode{\sphinxupquote{repr()}} 組み込み関数によって呼び出され、オブジェクトを表す「公式の (official)」文字列を計算します。可能なら、これは (適切な環境が与えられれば) 同じ値のオブジェクトを再生成するのに使える、有効な Python 式のようなものであるべきです。できないなら、 \sphinxcode{\sphinxupquote{<...some useful description...>}} 形式の文字列が返されるべきです。戻り値は文字列オブジェクトでなければなりません。クラスが {\hyperref[\detokenize{reference/datamodel:object.__repr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_repr\_\_()}}}}} を定義していて {\hyperref[\detokenize{reference/datamodel:object.__str__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_str\_\_()}}}}} は定義していなければ、そのクラスのインスタンスの「非公式の (informal)」文字列表現が要求されたときにも {\hyperref[\detokenize{reference/datamodel:object.__repr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_repr\_\_()}}}}} が使われます。 この関数はデバッグの際によく用いられるので、たくさんの情報を含み、あいまいでないような表記にすることが重要です。 \index{string@\spxentry{string}!\_\_str\_\_() (object method)@\spxentry{\_\_str\_\_()}\spxextra{object method}}\index{format() (built\sphinxhyphen{}in function)@\spxentry{format()}\spxextra{built\sphinxhyphen{}in function}!\_\_str\_\_() (object method)@\spxentry{\_\_str\_\_()}\spxextra{object method}}\index{print() (built\sphinxhyphen{}in function)@\spxentry{print()}\spxextra{built\sphinxhyphen{}in function}!\_\_str\_\_() (object method)@\spxentry{\_\_str\_\_()}\spxextra{object method}}\ignorespaces \end{fulllineitems} \index{\_\_str\_\_() (object のメソッド)@\spxentry{\_\_str\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__str__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_str\_\_}}}{\emph{self}}{} オブジェクトの「非公式の (informal)」あるいは表示に適した文字列表現を計算するために、 \sphinxcode{\sphinxupquote{str(object)}} と組み込み関数 \sphinxcode{\sphinxupquote{format()}}, \sphinxcode{\sphinxupquote{print()}} によって呼ばれます。戻り値は \DUrole{xref,std,std-ref}{string} オブジェクトでなければなりません。 {\hyperref[\detokenize{reference/datamodel:object.__str__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_str\_\_()}}}}} が有効な Python 表現を返すことが期待されないという点で、このメソッドは {\hyperref[\detokenize{reference/datamodel:object.__repr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{object.\_\_repr\_\_()}}}}} とは異なります: より便利な、または簡潔な表現を使用することができます。 組み込み型 \sphinxcode{\sphinxupquote{object}} によって定義されたデフォルト実装は、 {\hyperref[\detokenize{reference/datamodel:object.__repr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{object.\_\_repr\_\_()}}}}} を呼び出します。 \end{fulllineitems} \index{\_\_bytes\_\_() (object のメソッド)@\spxentry{\_\_bytes\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__bytes__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_bytes\_\_}}}{\emph{self}}{}~ \index{組み込み関数@\spxentry{組み込み関数}!bytes@\spxentry{bytes}}\index{bytes@\spxentry{bytes}!組み込み関数@\spxentry{組み込み関数}}\ignorespaces \DUrole{xref,std,std-ref}{bytes} によって呼び出され、オブジェクトのバイト文字列表現を計算します。これは \sphinxcode{\sphinxupquote{bytes}} オブジェクトを返すべきです。 \index{string@\spxentry{string}!\_\_format\_\_() (object method)@\spxentry{\_\_format\_\_()}\spxextra{object method}}\index{string@\spxentry{string}!conversion@\spxentry{conversion}}\index{conversion@\spxentry{conversion}!string@\spxentry{string}}\index{組み込み関数@\spxentry{組み込み関数}!print@\spxentry{print}}\index{print@\spxentry{print}!組み込み関数@\spxentry{組み込み関数}}\ignorespaces \end{fulllineitems} \index{\_\_format\_\_() (object のメソッド)@\spxentry{\_\_format\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__format__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_format\_\_}}}{\emph{self}, \emph{format\_spec}}{} \sphinxcode{\sphinxupquote{format()}} 組み込み関数、さらには {\hyperref[\detokenize{reference/lexical_analysis:f-strings}]{\sphinxcrossref{\DUrole{std,std-ref}{フォーマット済み文字列リテラル}}}} の評価、 \sphinxcode{\sphinxupquote{str.format()}} メソッドによって呼び出され、オブジェクトの "フォーマット化された (formatted)" 文字列表現を作ります。 \sphinxstyleemphasis{format\_spec} 引数は、 必要なフォーマット化オプションの記述を含む文字列です。 \sphinxstyleemphasis{format\_spec} 引数の解釈は、 {\hyperref[\detokenize{reference/datamodel:object.__format__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_format\_\_()}}}}} を実装する型によりますが、 ほとんどのクラスは組み込み型のいずれかにフォーマット化を委譲したり、 同じようなフォーマット化オプション構文を使います。 標準のフォーマット構文の解説は、 \DUrole{xref,std,std-ref}{formatspec} を参照してください。 戻り値は文字列オブジェクトでなければなりません。 \DUrole{versionmodified,changed}{バージョン 3.4 で変更: }空でない文字列が渡された場合 \sphinxcode{\sphinxupquote{object}} 自身の \_\_format\_\_ メソッドは \sphinxcode{\sphinxupquote{TypeError}} を送出します。 \DUrole{versionmodified,changed}{バージョン 3.7 で変更: }\sphinxcode{\sphinxupquote{object.\_\_format\_\_(x, '')}} は \sphinxcode{\sphinxupquote{format(str(x), '')}} ではなく \sphinxcode{\sphinxupquote{str(x)}} と等価になりました。 \end{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:richcmpfuncs}}\index{\_\_lt\_\_() (object のメソッド)@\spxentry{\_\_lt\_\_()}\spxextra{object のメソッド}}\index{\_\_le\_\_() (object のメソッド)@\spxentry{\_\_le\_\_()}\spxextra{object のメソッド}}\index{\_\_eq\_\_() (object のメソッド)@\spxentry{\_\_eq\_\_()}\spxextra{object のメソッド}}\index{\_\_ne\_\_() (object のメソッド)@\spxentry{\_\_ne\_\_()}\spxextra{object のメソッド}}\index{\_\_gt\_\_() (object のメソッド)@\spxentry{\_\_gt\_\_()}\spxextra{object のメソッド}}\index{\_\_ge\_\_() (object のメソッド)@\spxentry{\_\_ge\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__lt__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_lt\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__le__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_le\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__eq__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_eq\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__ne__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_ne\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__gt__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_gt\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__ge__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_ge\_\_}}}{\emph{self}, \emph{other}}{}~ \index{comparisons@\spxentry{comparisons}}\ignorespaces これらはいわゆる "拡張比較 (rich comparison)" メソッドです。演算子シンボルとメソッド名の対応は以下の通りです: \sphinxcode{\sphinxupquote{xy}} は \sphinxcode{\sphinxupquote{x.\_\_gt\_\_(y)}} を呼び出します; \sphinxcode{\sphinxupquote{x>=y}} は \sphinxcode{\sphinxupquote{x.\_\_ge\_\_(y)}} を呼び出します。 拡張比較メソッドは与えられた引数のペアに対する演算を実装していないときに、 シングルトン \sphinxcode{\sphinxupquote{NotImplemented}} を返すかもしれません。 慣例として、正常に比較が行われたときには \sphinxcode{\sphinxupquote{False}} か \sphinxcode{\sphinxupquote{True}} を返します。 しかし、これらのメソッドは任意の値を返すことができるので、比較演算子がブール値のコンテキスト (たとえば \sphinxcode{\sphinxupquote{if}} 文の条件部分) で使われた場合、 Python はその値に対して \sphinxcode{\sphinxupquote{bool()}} を呼び出して結果の真偽を判断します。 \sphinxcode{\sphinxupquote{is}} から利用される \sphinxcode{\sphinxupquote{object}} の {\hyperref[\detokenize{reference/datamodel:object.__eq__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_eq\_\_()}}}}} メソッドのデフォルト実装では、比較して偽となる場合に、次のコードのように \sphinxcode{\sphinxupquote{NotImplemented}} を返します: \sphinxcode{\sphinxupquote{True if x is y else NotImplemented}} 。 {\hyperref[\detokenize{reference/datamodel:object.__ne__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_ne\_\_()}}}}} メソッドは {\hyperref[\detokenize{reference/datamodel:object.__eq__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_eq\_\_()}}}}} に処理を委譲し、 \sphinxcode{\sphinxupquote{NotImplemented}} でない場合に結果を反転させます。他の比較演算子やデフォルトの実装には暗黙の関係はありません。例えば \sphinxcode{\sphinxupquote{(x.\_\_hash\_\_}} を設定することで、それをインタプリタに伝えなければなりません。 {\hyperref[\detokenize{reference/datamodel:object.__eq__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_eq\_\_()}}}}} をオーバーライドしていないクラスがハッシュサポートを抑制したい場合、クラス定義に \sphinxcode{\sphinxupquote{\_\_hash\_\_ = None}} を含めてください。クラス自身で明示的に \sphinxcode{\sphinxupquote{TypeError}} を送出する {\hyperref[\detokenize{reference/datamodel:object.__hash__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_hash\_\_()}}}}} を定義すると、 \sphinxcode{\sphinxupquote{isinstance(obj, collections.abc.Hashable)}} 呼び出しで誤ってハッシュ可能と識別されるでしょう。 \begin{sphinxadmonition}{note}{注釈:} デフォルトでは、文字列とバイト列の {\hyperref[\detokenize{reference/datamodel:object.__hash__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_hash\_\_()}}}}} 値は予測不可能なランダム値で "ソルト" されます。 ハッシュ値は単独の Python プロセス内では定数であり続けますが、Python を繰り返し起動する毎に、予測できなくなります。 This is intended to provide protection against a denial\sphinxhyphen{}of\sphinxhyphen{}service caused by carefully\sphinxhyphen{}chosen inputs that exploit the worst case performance of a dict insertion, O(n$^{\text{2}}$) complexity. See \sphinxurl{http://www.ocert.org/advisories/ocert-2011-003.html} for details. ハッシュ値の変更は、集合のイテレーション順序に影響します。Python はこの順序付けを保証していません (そして通常 32\sphinxhyphen{}bit と 64\sphinxhyphen{}bit の間でも異なります)。 \index{PYTHONHASHSEED@\spxentry{PYTHONHASHSEED}}\index{環境変数@\spxentry{環境変数}!PYTHONHASHSEED@\spxentry{PYTHONHASHSEED}}\sphinxcode{\sphinxupquote{PYTHONHASHSEED}} も参照してください。 \end{sphinxadmonition} \DUrole{versionmodified,changed}{バージョン 3.3 で変更: }ハッシュのランダム化がデフォルトで有効になりました。 \end{fulllineitems} \index{\_\_bool\_\_() (object のメソッド)@\spxentry{\_\_bool\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__bool__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_bool\_\_}}}{\emph{self}}{}~ \index{\_\_len\_\_() (mapping object method)@\spxentry{\_\_len\_\_()}\spxextra{mapping object method}}\ignorespaces 真理値テストや組み込み演算 \sphinxcode{\sphinxupquote{bool()}} を実装するために呼び出されます; \sphinxcode{\sphinxupquote{False}} または \sphinxcode{\sphinxupquote{True}} を返さなければなりません。このメソッドが定義されていないとき、 {\hyperref[\detokenize{reference/datamodel:object.__len__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_len\_\_()}}}}} が定義されていれば呼び出され、その結果が非 0 であれば真とみなされます。クラスが {\hyperref[\detokenize{reference/datamodel:object.__len__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_len\_\_()}}}}} も {\hyperref[\detokenize{reference/datamodel:object.__bool__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_bool\_\_()}}}}} も定義していないければ、そのクラスのインスタンスはすべて真とみなされます。 \end{fulllineitems} \subsection{属性値アクセスをカスタマイズする} \label{\detokenize{reference/datamodel:customizing-attribute-access}}\label{\detokenize{reference/datamodel:attribute-access}} 以下のメソッドを定義して、クラスインスタンスへの属性値アクセス ( 属性値の使用、属性値への代入、 \sphinxcode{\sphinxupquote{x.name}} の削除) の意味をカスタマイズすることができます。 \index{\_\_getattr\_\_() (object のメソッド)@\spxentry{\_\_getattr\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__getattr__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_getattr\_\_}}}{\emph{self}, \emph{name}}{} デフォルトの属性アクセスが \sphinxcode{\sphinxupquote{AttributeError}} で失敗したとき (\sphinxstyleemphasis{name} がインスタンスの属性または \sphinxcode{\sphinxupquote{self}} のクラスツリーの属性でないために {\hyperref[\detokenize{reference/datamodel:object.__getattribute__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getattribute\_\_()}}}}} が \sphinxcode{\sphinxupquote{AttributeError}} を送出したか、 \sphinxstyleemphasis{name} プロパティの {\hyperref[\detokenize{reference/datamodel:object.__get__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_get\_\_()}}}}} が \sphinxcode{\sphinxupquote{AttributeError}} を送出したとき) に呼び出されます。 このメソッドは (計算された) 属性値を返すか、 \sphinxcode{\sphinxupquote{AttributeError}} 例外を送出しなければなりません。 なお、通常の過程で属性が見つかれば、 {\hyperref[\detokenize{reference/datamodel:object.__getattr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getattr\_\_()}}}}} は呼び出されません。(これは、 {\hyperref[\detokenize{reference/datamodel:object.__getattr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getattr\_\_()}}}}} と {\hyperref[\detokenize{reference/datamodel:object.__setattr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_setattr\_\_()}}}}} が意図的に非対称にされている点です。) これは、効率のためと、こうしないと {\hyperref[\detokenize{reference/datamodel:object.__getattr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getattr\_\_()}}}}} がインスタンスの他の属性値にアクセスする方法がなくなるためです。また、少なくともインスタンス変数に対しては、値をインスタンスの属性値辞書に挿入しないことで (代わりに他のオブジェクトに挿入することで)、属性値を完全に制御しているふりができます。実際に属性アクセスを完全に制御する方法は、以下の {\hyperref[\detokenize{reference/datamodel:object.__getattribute__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getattribute\_\_()}}}}} メソッドを参照してください。 \end{fulllineitems} \index{\_\_getattribute\_\_() (object のメソッド)@\spxentry{\_\_getattribute\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__getattribute__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_getattribute\_\_}}}{\emph{self}, \emph{name}}{} クラスのインスタンスに対する属性アクセスを実装するために、無条件に呼び出されます。クラスが {\hyperref[\detokenize{reference/datamodel:object.__getattr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getattr\_\_()}}}}} も定義している場合、 {\hyperref[\detokenize{reference/datamodel:object.__getattr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getattr\_\_()}}}}} は、 {\hyperref[\detokenize{reference/datamodel:object.__getattribute__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getattribute\_\_()}}}}} で明示的に呼び出すか、 \sphinxcode{\sphinxupquote{AttributeError}} 例外を送出しない限り呼ばれません。このメソッドは (計算された) 属性値を返すか、 \sphinxcode{\sphinxupquote{AttributeError}} 例外を送出します。このメソッドが再帰的に際限なく呼び出されてしまうのを防ぐため、実装の際には常に、必要な属性全てへのアクセスで、例えば \sphinxcode{\sphinxupquote{object.\_\_getattribute\_\_(self, name)}} のように基底クラスのメソッドを同じ属性名を使って呼び出さなければなりません。 \begin{sphinxadmonition}{note}{注釈:} 言語構文や組み込み関数から暗黙に呼び出された特殊メソッドの検索では、このメソッドも回避されることがあります。 {\hyperref[\detokenize{reference/datamodel:special-lookup}]{\sphinxcrossref{\DUrole{std,std-ref}{特殊メソッド検索}}}} を参照してください。 \end{sphinxadmonition} \sphinxcode{\sphinxupquote{object.\_\_getattr\_\_}} に \sphinxcode{\sphinxupquote{obj}} と \sphinxcode{\sphinxupquote{name}} を渡して実行すると、 \DUrole{xref,std,std-ref}{監査イベント} を送出します。 \end{fulllineitems} \index{\_\_setattr\_\_() (object のメソッド)@\spxentry{\_\_setattr\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__setattr__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_setattr\_\_}}}{\emph{self}, \emph{name}, \emph{value}}{} 属性の代入が試みられた際に呼び出されます。これは通常の代入の過程 (すなわち、インスタンス辞書への値の代入) の代わりに呼び出されます。\sphinxstyleemphasis{name} は属性名で、\sphinxstyleemphasis{value} はその属性に代入する値です。 {\hyperref[\detokenize{reference/datamodel:object.__setattr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_setattr\_\_()}}}}} の中でインスタンス属性への代入が必要なら、基底クラスのこれと同じ名前のメソッドを呼び出さなければなりません。例えば、 \sphinxcode{\sphinxupquote{object.\_\_setattr\_\_(self, name, value)}} とします。 \sphinxcode{\sphinxupquote{object.\_\_setattr\_\_}} に \sphinxcode{\sphinxupquote{obj}} と \sphinxcode{\sphinxupquote{name}} と \sphinxcode{\sphinxupquote{value}} を渡して実行すると、 \DUrole{xref,std,std-ref}{監査イベント} を送出します。 \end{fulllineitems} \index{\_\_delattr\_\_() (object のメソッド)@\spxentry{\_\_delattr\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__delattr__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_delattr\_\_}}}{\emph{self}, \emph{name}}{} {\hyperref[\detokenize{reference/datamodel:object.__setattr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_setattr\_\_()}}}}} に似ていますが、代入ではなく値の削除を行います。このメソッドを実装するのは、オブジェクトにとって \sphinxcode{\sphinxupquote{del obj.name}} が意味がある場合だけにしなければなりません。 \sphinxcode{\sphinxupquote{object.\_\_delattr\_\_}} に \sphinxcode{\sphinxupquote{obj}} と \sphinxcode{\sphinxupquote{name}} を渡して実行すると、 \DUrole{xref,std,std-ref}{監査イベント} を送出します。 \end{fulllineitems} \index{\_\_dir\_\_() (object のメソッド)@\spxentry{\_\_dir\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__dir__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_dir\_\_}}}{\emph{self}}{} オブジェクトに \sphinxcode{\sphinxupquote{dir()}} が呼び出されたときに呼び出されます。シーケンスが返されなければなりません。 \sphinxcode{\sphinxupquote{dir()}} は返されたシーケンスをリストに変換し、ソートします。 \end{fulllineitems} \subsubsection{モジュールの属性値アクセスをカスタマイズする} \label{\detokenize{reference/datamodel:customizing-module-attribute-access}} \index{\_\_getattr\_\_ (module attribute)@\spxentry{\_\_getattr\_\_}\spxextra{module attribute}}\index{\_\_dir\_\_ (module attribute)@\spxentry{\_\_dir\_\_}\spxextra{module attribute}}\index{\_\_class\_\_ (module attribute)@\spxentry{\_\_class\_\_}\spxextra{module attribute}}\ignorespaces 特殊な名前の \sphinxcode{\sphinxupquote{\_\_getattr\_\_}} と \sphinxcode{\sphinxupquote{\_\_dir\_\_}} も、モジュール属性へのアクセスをカスタマイズするのに使えます。 モジュールレベルの \sphinxcode{\sphinxupquote{\_\_getattr\_\_}} 関数は属性名である 1 引数を受け取り、計算した値を返すか \sphinxcode{\sphinxupquote{AttributeError}} を送出します。 属性がモジュールオブジェクトから、通常の検索、つまり {\hyperref[\detokenize{reference/datamodel:object.__getattribute__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{object.\_\_getattribute\_\_()}}}}} で見付からなかった場合は、 \sphinxcode{\sphinxupquote{AttributeError}} を送出する前に、モジュールの \sphinxcode{\sphinxupquote{\_\_dict\_\_}} から \sphinxcode{\sphinxupquote{\_\_getattr\_\_}} が検索されます。 見付かった場合は、その属性名で呼び出され、結果が返されます。 \sphinxcode{\sphinxupquote{\_\_dir\_\_}} 関数は引数を受け取らず、モジュールのアクセス可能な名前を表す文字列のシーケンスを返さなければなりません。存在する場合は、この関数はモジュールの標準の \sphinxcode{\sphinxupquote{dir()}} 検索を上書きします。 より細かい粒度でのモジュールの動作 (属性やプロパティの設定など) のカスタマイズのために、モジュールオブジェクトの \sphinxcode{\sphinxupquote{\_\_class\_\_}} 属性に \sphinxcode{\sphinxupquote{types.ModuleType}} のサブクラスが設定できます。 例えば次のようになります: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k+kn}{import} \PYG{n+nn}{sys} \PYG{k+kn}{from} \PYG{n+nn}{types} \PYG{k+kn}{import} \PYG{n}{ModuleType} \PYG{k}{class} \PYG{n+nc}{VerboseModule}\PYG{p}{(}\PYG{n}{ModuleType}\PYG{p}{)}\PYG{p}{:} \PYG{k}{def} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}repr\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n+nb+bp}{self}\PYG{p}{)}\PYG{p}{:} \PYG{k}{return} \PYG{l+s+sa}{f}\PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{Verbose }\PYG{l+s+si}{\PYGZob{}}\PYG{n+nb+bp}{self}\PYG{o}{.}\PYG{n+nv+vm}{\PYGZus{}\PYGZus{}name\PYGZus{}\PYGZus{}}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s1}{\PYGZsq{}} \PYG{k}{def} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}setattr\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n+nb+bp}{self}\PYG{p}{,} \PYG{n}{attr}\PYG{p}{,} \PYG{n}{value}\PYG{p}{)}\PYG{p}{:} \PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+sa}{f}\PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{Setting }\PYG{l+s+si}{\PYGZob{}}\PYG{n}{attr}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s1}{...}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{)} \PYG{n+nb}{super}\PYG{p}{(}\PYG{p}{)}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}setattr\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n}{attr}\PYG{p}{,} \PYG{n}{value}\PYG{p}{)} \PYG{n}{sys}\PYG{o}{.}\PYG{n}{modules}\PYG{p}{[}\PYG{n+nv+vm}{\PYGZus{}\PYGZus{}name\PYGZus{}\PYGZus{}}\PYG{p}{]}\PYG{o}{.}\PYG{n+nv+vm}{\PYGZus{}\PYGZus{}class\PYGZus{}\PYGZus{}} \PYG{o}{=} \PYG{n}{VerboseModule} \end{sphinxVerbatim} \begin{sphinxadmonition}{note}{注釈:} モジュールの \sphinxcode{\sphinxupquote{\_\_getattr\_\_}} を定義したり \sphinxcode{\sphinxupquote{\_\_class\_\_}} を設定したりしても、影響があるのは属性アクセスの構文が使われる検索だけです \sphinxhyphen{}\sphinxhyphen{} モジュールの globals への直接アクセスは (モジュール内のコードからとモジュールの globals のどちらでも) 影響を受けません。 \end{sphinxadmonition} \DUrole{versionmodified,changed}{バージョン 3.5 で変更: }モジュールの属性 \sphinxcode{\sphinxupquote{\_\_class\_\_}} が書き込み可能になりました。 \DUrole{versionmodified,added}{バージョン 3.7 で追加: }\sphinxcode{\sphinxupquote{\_\_getattr\_\_}} モジュール属性と \sphinxcode{\sphinxupquote{\_\_dir\_\_}} モジュール属性。 \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 562@\spxentry{PEP 562}}\sphinxhref{https://www.python.org/dev/peps/pep-0562}{\sphinxstylestrong{PEP 562}} \sphinxhyphen{} モジュールの \_\_getattr\_\_ と \_\_dir\_\_}] \leavevmode モジュールの \sphinxcode{\sphinxupquote{\_\_getattr\_\_}} 関数および \sphinxcode{\sphinxupquote{\_\_dir\_\_}} 関数の説明。 \end{description} \subsubsection{デスクリプタ (descriptor) の実装} \label{\detokenize{reference/datamodel:implementing-descriptors}}\label{\detokenize{reference/datamodel:descriptors}} 以下のメソッドは、このメソッドを持つクラス (いわゆる \sphinxstyleemphasis{デスクリプタ(descriptor)} クラス) のインスタンスが、 \sphinxstyleemphasis{オーナー (owner)} クラスに存在するときにのみ適用されます (デスクリプタは、オーナーのクラス辞書か、その親のいずれかのクラス辞書になければなりません)。 以下の例では、"属性" とは、名前がオーナークラスの \sphinxcode{\sphinxupquote{\_\_dict\_\_}} のプロパティ (porperty) のキーであるような属性を指します。 \index{\_\_get\_\_() (object のメソッド)@\spxentry{\_\_get\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__get__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_get\_\_}}}{\emph{self}, \emph{instance}, \emph{owner=None}}{} オーナークラス(クラス属性アクセスの場合)や、クラスのインスタンス(インスタンス属性アクセスの場合)の属性取得時に呼び出されます。 \sphinxstyleemphasis{instance} を通じて属性をアクセスする時に、オプションの \sphinxstyleemphasis{owner} 引数はオーナークラスです。 \sphinxstyleemphasis{owner} を通じて属性アクセスするときは \sphinxcode{\sphinxupquote{None}} です。 このメソッドは、算出された属性値を返すか、 \sphinxcode{\sphinxupquote{AttributeError}} 例外を送出します。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 252@\spxentry{PEP 252}}\sphinxhref{https://www.python.org/dev/peps/pep-0252}{\sphinxstylestrong{PEP 252}} は {\hyperref[\detokenize{reference/datamodel:object.__get__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_get\_\_()}}}}} は1つや2つの引数を持つ呼び出し可能オブジェクトであると定義しています。Pythonの組み込みのデスクリプタはこの仕様をサポートしていますが、サードパーティ製のツールの中には両方の引数を必要とするものもあります。Pythonの {\hyperref[\detokenize{reference/datamodel:object.__getattribute__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getattribute\_\_()}}}}} 実装は必要かどうかに関わらず、両方の引数を常に渡します。 \end{fulllineitems} \index{\_\_set\_\_() (object のメソッド)@\spxentry{\_\_set\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__set__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_set\_\_}}}{\emph{self}, \emph{instance}, \emph{value}}{} オーナークラスのインスタンス \sphinxstyleemphasis{instance} 上の属性を新たな値 \sphinxstyleemphasis{value} に設定する際に呼び出されます。 {\hyperref[\detokenize{reference/datamodel:object.__set__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_set\_\_()}}}}} あるいは {\hyperref[\detokenize{reference/datamodel:object.__delete__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_delete\_\_()}}}}} を追加すると、デスクリプタは「データデスクリプタ」に変わります。詳細は {\hyperref[\detokenize{reference/datamodel:descriptor-invocation}]{\sphinxcrossref{\DUrole{std,std-ref}{デスクリプタの呼び出し}}}} を参照してください。 \end{fulllineitems} \index{\_\_delete\_\_() (object のメソッド)@\spxentry{\_\_delete\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__delete__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_delete\_\_}}}{\emph{self}, \emph{instance}}{} オーナークラスのインスタンス \sphinxstyleemphasis{instance} 上の属性を削除する際に呼び出されます。 \end{fulllineitems} \index{\_\_set\_name\_\_() (object のメソッド)@\spxentry{\_\_set\_name\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__set_name__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_set\_name\_\_}}}{\emph{self}, \emph{owner}, \emph{name}}{} オーナーとなるクラス \sphinxstyleemphasis{owner} が作成された時点で呼び出されます。 ディスクリプタは \sphinxstyleemphasis{name} に割り当てられます。 \begin{sphinxadmonition}{note}{注釈:} {\hyperref[\detokenize{reference/datamodel:object.__set_name__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_set\_name\_\_()}}}}} is only called implicitly as part of the \sphinxcode{\sphinxupquote{type}} constructor, so it will need to be called explicitly with the appropriate parameters when a descriptor is added to a class after initial creation: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{class} \PYG{n+nc}{A}\PYG{p}{:} \PYG{k}{pass} \PYG{n}{descr} \PYG{o}{=} \PYG{n}{custom\PYGZus{}descriptor}\PYG{p}{(}\PYG{p}{)} \PYG{n}{A}\PYG{o}{.}\PYG{n}{attr} \PYG{o}{=} \PYG{n}{descr} \PYG{n}{descr}\PYG{o}{.}\PYG{n}{\PYGZus{}\PYGZus{}set\PYGZus{}name\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n}{A}\PYG{p}{,} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{attr}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{)} \end{sphinxVerbatim} 詳細は {\hyperref[\detokenize{reference/datamodel:class-object-creation}]{\sphinxcrossref{\DUrole{std,std-ref}{クラスオブジェクトの作成}}}} を参照してください。 \end{sphinxadmonition} \DUrole{versionmodified,added}{バージョン 3.6 で追加.} \end{fulllineitems} \sphinxcode{\sphinxupquote{\_\_objclass\_\_}} 属性は \sphinxcode{\sphinxupquote{inspect}} モジュールによって解釈され、このオブジェクトが定義されたクラスを特定するのに使われます (この属性を適切に設定しておくと、動的なクラスの属性を実行時に調べる助けになります)。 呼び出される側にとっては、この属性で指定されたクラス (もしくはそのサブクラス) のインスタンスが1番目の位置引数として期待もしくは要求されていることが示せます (例えば、 CPython は束縛されていない C で実行されたメソッドにこの属性を設定します)。 \subsubsection{デスクリプタの呼び出し} \label{\detokenize{reference/datamodel:invoking-descriptors}}\label{\detokenize{reference/datamodel:descriptor-invocation}} In general, a descriptor is an object attribute with "binding behavior", one whose attribute access has been overridden by methods in the descriptor protocol: {\hyperref[\detokenize{reference/datamodel:object.__get__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_get\_\_()}}}}}, {\hyperref[\detokenize{reference/datamodel:object.__set__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_set\_\_()}}}}}, and {\hyperref[\detokenize{reference/datamodel:object.__delete__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_delete\_\_()}}}}}. If any of those methods are defined for an object, it is said to be a descriptor. 属性アクセスのデフォルトの動作は、オブジェクトの辞書から値を取り出したり、値を設定したり、削除したりするというものです。例えば、 \sphinxcode{\sphinxupquote{a.x}} による属性の検索では、まず \sphinxcode{\sphinxupquote{a.\_\_dict\_\_{[}'x'{]}}} 、次に \sphinxcode{\sphinxupquote{type(a).\_\_dict\_\_{[}'x'{]}}} 、そして \sphinxcode{\sphinxupquote{type(a)}} の基底クラスでメタクラスでないものに続く、といった具合に連鎖が起こります。 しかし、検索対象の値が、デスクリプタメソッドのいずれかを定義しているオブジェクトであれば、Python はデフォルトの動作をオーバーライドして、代わりにデスクリプタメソッドを呼び出します。先述の連鎖の中のどこでデスクリプタメソッドが呼び出されるかは、どのデスクリプタメソッドが定義されていて、どのように呼び出されたかに依存します。 デスクリプタ呼び出しの基点となるのは、属性名への束縛 (binding) 、すなわち \sphinxcode{\sphinxupquote{a.x}} です。引数がどのようにデスクリプタに結合されるかは \sphinxcode{\sphinxupquote{a}} に依存します: \begin{description} \item[{直接呼び出し (Direct Call)}] \leavevmode 最も単純で、かつめったに使われない呼び出し操作は、コード中で直接デスクリプタメソッドの呼び出し: \sphinxcode{\sphinxupquote{x.\_\_get\_\_(a)}} を行うというものです。 \item[{インスタンス束縛 (Instance Binding)}] \leavevmode オブジェクトインスタンスへ束縛すると、\sphinxcode{\sphinxupquote{a.x}} は呼び出し \sphinxcode{\sphinxupquote{type(a).\_\_dict\_\_{[}'x'{]}.\_\_get\_\_(a, type(a))}} に変換されます。 \item[{クラス束縛 (Class Binding)}] \leavevmode クラスへ束縛すると、\sphinxcode{\sphinxupquote{A.x}} は呼び出し \sphinxcode{\sphinxupquote{A.\_\_dict\_\_{[}'x'{]}.\_\_get\_\_(None, A)}} に変換されます。 \item[{super 束縛 (Super Binding)}] \leavevmode If \sphinxcode{\sphinxupquote{a}} is an instance of \sphinxcode{\sphinxupquote{super}}, then the binding \sphinxcode{\sphinxupquote{super(B, obj).m()}} searches \sphinxcode{\sphinxupquote{obj.\_\_class\_\_.\_\_mro\_\_}} for the base class \sphinxcode{\sphinxupquote{A}} immediately following \sphinxcode{\sphinxupquote{B}} and then invokes the descriptor with the call: \sphinxcode{\sphinxupquote{A.\_\_dict\_\_{[}'m'{]}.\_\_get\_\_(obj, obj.\_\_class\_\_)}}. \end{description} For instance bindings, the precedence of descriptor invocation depends on which descriptor methods are defined. A descriptor can define any combination of {\hyperref[\detokenize{reference/datamodel:object.__get__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_get\_\_()}}}}}, {\hyperref[\detokenize{reference/datamodel:object.__set__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_set\_\_()}}}}} and {\hyperref[\detokenize{reference/datamodel:object.__delete__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_delete\_\_()}}}}}. If it does not define {\hyperref[\detokenize{reference/datamodel:object.__get__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_get\_\_()}}}}}, then accessing the attribute will return the descriptor object itself unless there is a value in the object's instance dictionary. If the descriptor defines {\hyperref[\detokenize{reference/datamodel:object.__set__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_set\_\_()}}}}} and/or {\hyperref[\detokenize{reference/datamodel:object.__delete__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_delete\_\_()}}}}}, it is a data descriptor; if it defines neither, it is a non\sphinxhyphen{}data descriptor. Normally, data descriptors define both {\hyperref[\detokenize{reference/datamodel:object.__get__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_get\_\_()}}}}} and {\hyperref[\detokenize{reference/datamodel:object.__set__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_set\_\_()}}}}}, while non\sphinxhyphen{}data descriptors have just the {\hyperref[\detokenize{reference/datamodel:object.__get__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_get\_\_()}}}}} method. Data descriptors with {\hyperref[\detokenize{reference/datamodel:object.__get__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_get\_\_()}}}}} and {\hyperref[\detokenize{reference/datamodel:object.__set__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_set\_\_()}}}}} (and/or {\hyperref[\detokenize{reference/datamodel:object.__delete__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_delete\_\_()}}}}}) defined always override a redefinition in an instance dictionary. In contrast, non\sphinxhyphen{}data descriptors can be overridden by instances. Python methods (including those decorated with \sphinxcode{\sphinxupquote{@staticmethod}} and \sphinxcode{\sphinxupquote{@classmethod}}) are implemented as non\sphinxhyphen{}data descriptors. Accordingly, instances can redefine and override methods. This allows individual instances to acquire behaviors that differ from other instances of the same class. \sphinxcode{\sphinxupquote{property()}} 関数はデータデスクリプタとして実装されています。従って、インスタンスはあるプロパティの動作をオーバーライドすることができません。 \subsubsection{\_\_slots\_\_} \label{\detokenize{reference/datamodel:slots}}\label{\detokenize{reference/datamodel:id3}} \sphinxstyleemphasis{\_\_slots\_\_} allow us to explicitly declare data members (like properties) and deny the creation of \sphinxcode{\sphinxupquote{\_\_dict\_\_}} and \sphinxstyleemphasis{\_\_weakref\_\_} (unless explicitly declared in \sphinxstyleemphasis{\_\_slots\_\_} or available in a parent.) The space saved over using \sphinxcode{\sphinxupquote{\_\_dict\_\_}} can be significant. Attribute lookup speed can be significantly improved as well. \index{object.\_\_slots\_\_ (組み込み変数)@\spxentry{object.\_\_slots\_\_}\spxextra{組み込み変数}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__slots__}}\pysigline{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_slots\_\_}}} This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. \sphinxstyleemphasis{\_\_slots\_\_} reserves space for the declared variables and prevents the automatic creation of \sphinxcode{\sphinxupquote{\_\_dict\_\_}} and \sphinxstyleemphasis{\_\_weakref\_\_} for each instance. \end{fulllineitems} \paragraph{\sphinxstyleemphasis{\_\_slots\_\_} を利用する際の注意} \label{\detokenize{reference/datamodel:notes-on-using-slots}}\begin{itemize} \item {} When inheriting from a class without \sphinxstyleemphasis{\_\_slots\_\_}, the \sphinxcode{\sphinxupquote{\_\_dict\_\_}} and \sphinxstyleemphasis{\_\_weakref\_\_} attribute of the instances will always be accessible. \item {} Without a \sphinxcode{\sphinxupquote{\_\_dict\_\_}} variable, instances cannot be assigned new variables not listed in the \sphinxstyleemphasis{\_\_slots\_\_} definition. Attempts to assign to an unlisted variable name raises \sphinxcode{\sphinxupquote{AttributeError}}. If dynamic assignment of new variables is desired, then add \sphinxcode{\sphinxupquote{'\_\_dict\_\_'}} to the sequence of strings in the \sphinxstyleemphasis{\_\_slots\_\_} declaration. \item {} Without a \sphinxstyleemphasis{\_\_weakref\_\_} variable for each instance, classes defining \sphinxstyleemphasis{\_\_slots\_\_} do not support \sphinxcode{\sphinxupquote{weak references}} to its instances. If weak reference support is needed, then add \sphinxcode{\sphinxupquote{'\_\_weakref\_\_'}} to the sequence of strings in the \sphinxstyleemphasis{\_\_slots\_\_} declaration. \item {} \sphinxstyleemphasis{\_\_slots\_\_} are implemented at the class level by creating {\hyperref[\detokenize{reference/datamodel:descriptors}]{\sphinxcrossref{\DUrole{std,std-ref}{descriptors}}}} for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by \sphinxstyleemphasis{\_\_slots\_\_}; otherwise, the class attribute would overwrite the descriptor assignment. \item {} The action of a \sphinxstyleemphasis{\_\_slots\_\_} declaration is not limited to the class where it is defined. \sphinxstyleemphasis{\_\_slots\_\_} declared in parents are available in child classes. However, child subclasses will get a \sphinxcode{\sphinxupquote{\_\_dict\_\_}} and \sphinxstyleemphasis{\_\_weakref\_\_} unless they also define \sphinxstyleemphasis{\_\_slots\_\_} (which should only contain names of any \sphinxstyleemphasis{additional} slots). \item {} あるクラスで、基底クラスですでに定義されているスロットを定義した場合、基底クラスのスロットで定義されているインスタンス変数は (デスクリプタを基底クラスから直接取得しない限り) アクセスできなくなります。これにより、プログラムの趣意が不定になってしまいます。将来は、この問題を避けるために何らかのチェックが追加されるかもしれません。 \item {} 空でない \sphinxstyleemphasis{\_\_slots\_\_} は、 \sphinxcode{\sphinxupquote{int}} や \sphinxcode{\sphinxupquote{bytes}} や \sphinxcode{\sphinxupquote{tuple}} のような "可変長の" 組み込み型から派生したクラスでは動作しません。 \item {} Any non\sphinxhyphen{}string {\hyperref[\detokenize{glossary:term-iterable}]{\sphinxtermref{\DUrole{xref,std,std-term}{iterable}}}} may be assigned to \sphinxstyleemphasis{\_\_slots\_\_}. \item {} If a \sphinxcode{\sphinxupquote{dictionary}} is used to assign \sphinxstyleemphasis{\_\_slots\_\_}, the dictionary keys will be used as the slot names. The values of the dictionary can be used to provide per\sphinxhyphen{}attribute docstrings that will be recognised by \sphinxcode{\sphinxupquote{inspect.getdoc()}} and displayed in the output of \sphinxcode{\sphinxupquote{help()}}. \item {} \sphinxcode{\sphinxupquote{\_\_class\_\_}} assignment works only if both classes have the same \sphinxstyleemphasis{\_\_slots\_\_}. \item {} \DUrole{xref,std,std-ref}{Multiple inheritance} with multiple slotted parent classes can be used, but only one parent is allowed to have attributes created by slots (the other bases must have empty slot layouts) \sphinxhyphen{} violations raise \sphinxcode{\sphinxupquote{TypeError}}. \item {} If an {\hyperref[\detokenize{glossary:term-iterator}]{\sphinxtermref{\DUrole{xref,std,std-term}{iterator}}}} is used for \sphinxstyleemphasis{\_\_slots\_\_} then a {\hyperref[\detokenize{glossary:term-descriptor}]{\sphinxtermref{\DUrole{xref,std,std-term}{descriptor}}}} is created for each of the iterator's values. However, the \sphinxstyleemphasis{\_\_slots\_\_} attribute will be an empty iterator. \end{itemize} \subsection{クラス生成をカスタマイズする} \label{\detokenize{reference/datamodel:customizing-class-creation}}\label{\detokenize{reference/datamodel:class-customization}} Whenever a class inherits from another class, {\hyperref[\detokenize{reference/datamodel:object.__init_subclass__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_init\_subclass\_\_()}}}}} is called on the parent class. This way, it is possible to write classes which change the behavior of subclasses. This is closely related to class decorators, but where class decorators only affect the specific class they're applied to, \sphinxcode{\sphinxupquote{\_\_init\_subclass\_\_}} solely applies to future subclasses of the class defining the method. \index{\_\_init\_subclass\_\_() (object のクラスメソッド)@\spxentry{\_\_init\_subclass\_\_()}\spxextra{object のクラスメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__init_subclass__}}\pysiglinewithargsret{\sphinxbfcode{\sphinxupquote{classmethod }}\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_init\_subclass\_\_}}}{\emph{cls}}{} このメソッドは、それが定義されたクラスが継承された際に必ず呼び出されます。\sphinxstyleemphasis{cls} は新しいサブクラスです。もし、このメソッドがインスタンスメソッドとして定義されると、暗黙的にクラスメソッドに変換されます。 新しいクラスに与えられたキーワード引数は、親のクラスの \sphinxcode{\sphinxupquote{\_\_init\_subclass\_\_}} に渡されます。 \sphinxcode{\sphinxupquote{\_\_init\_subclass\_\_}} を利用している他のクラスとの互換性のために、以下のコードのように必要なキーワード引数を取得したら、他の引数は基底クラスに引き渡すべきです: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{class} \PYG{n+nc}{Philosopher}\PYG{p}{:} \PYG{k}{def} \PYG{n+nf}{\PYGZus{}\PYGZus{}init\PYGZus{}subclass\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n+nb+bp}{cls}\PYG{p}{,} \PYG{o}{/}\PYG{p}{,} \PYG{n}{default\PYGZus{}name}\PYG{p}{,} \PYG{o}{*}\PYG{o}{*}\PYG{n}{kwargs}\PYG{p}{)}\PYG{p}{:} \PYG{n+nb}{super}\PYG{p}{(}\PYG{p}{)}\PYG{o}{.}\PYG{n}{\PYGZus{}\PYGZus{}init\PYGZus{}subclass\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{o}{*}\PYG{o}{*}\PYG{n}{kwargs}\PYG{p}{)} \PYG{n+nb+bp}{cls}\PYG{o}{.}\PYG{n}{default\PYGZus{}name} \PYG{o}{=} \PYG{n}{default\PYGZus{}name} \PYG{k}{class} \PYG{n+nc}{AustralianPhilosopher}\PYG{p}{(}\PYG{n}{Philosopher}\PYG{p}{,} \PYG{n}{default\PYGZus{}name}\PYG{o}{=}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{Bruce}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)}\PYG{p}{:} \PYG{k}{pass} \end{sphinxVerbatim} \sphinxcode{\sphinxupquote{object.\_\_init\_subclass\_\_}} のデフォルト実装は何も行いませんが、何らかの引数とともに呼び出された場合は、エラーを送出します。 \begin{sphinxadmonition}{note}{注釈:} メタクラスのヒント \sphinxcode{\sphinxupquote{metaclass}} は残りの型機構によって消費され、 \sphinxcode{\sphinxupquote{\_\_init\_subclass\_\_}} 実装に渡されることはありません。 実際のメタクラス (明示的なヒントではなく) は、 \sphinxcode{\sphinxupquote{type(cls)}} としてアクセスできます。 \end{sphinxadmonition} \DUrole{versionmodified,added}{バージョン 3.6 で追加.} \end{fulllineitems} \subsubsection{メタクラス} \label{\detokenize{reference/datamodel:metaclasses}}\label{\detokenize{reference/datamodel:id4}} \index{metaclass@\spxentry{metaclass}}\index{組み込み関数@\spxentry{組み込み関数}!type@\spxentry{type}}\index{type@\spxentry{type}!組み込み関数@\spxentry{組み込み関数}}\index{= (equals)@\spxentry{=}\spxextra{equals}!class definition@\spxentry{class definition}}\ignorespaces デフォルトでは、クラスは \sphinxcode{\sphinxupquote{type()}} を使って構築されます。 クラス本体は新しい名前空間で実行され、クラス名が \sphinxcode{\sphinxupquote{type(name, bases, namespace)}} の結果にローカルに束縛されます。 クラス生成プロセスはカスタマイズできます。 そのためにはクラス定義行で \sphinxcode{\sphinxupquote{metaclass}} キーワード引数を渡すか、そのような引数を定義行に含む既存のクラスを継承します。 次の例で \sphinxcode{\sphinxupquote{MyClass}} と \sphinxcode{\sphinxupquote{MySubclass}} は両方とも \sphinxcode{\sphinxupquote{Meta}} のインスタンスです: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{class} \PYG{n+nc}{Meta}\PYG{p}{(}\PYG{n+nb}{type}\PYG{p}{)}\PYG{p}{:} \PYG{k}{pass} \PYG{k}{class} \PYG{n+nc}{MyClass}\PYG{p}{(}\PYG{n}{metaclass}\PYG{o}{=}\PYG{n}{Meta}\PYG{p}{)}\PYG{p}{:} \PYG{k}{pass} \PYG{k}{class} \PYG{n+nc}{MySubclass}\PYG{p}{(}\PYG{n}{MyClass}\PYG{p}{)}\PYG{p}{:} \PYG{k}{pass} \end{sphinxVerbatim} クラス定義の中で指定された他のキーワード引数は、後述するすべてのメタクラス操作に渡されます。 クラス定義が実行される際に、以下のステップが生じます: \begin{itemize} \item {} MRO エントリの解決が行われる; \item {} 適切なメタクラスが決定される; \item {} クラスの名前空間が準備される; \item {} クラスの本体が実行される; \item {} クラスオブジェクトが作られる。 \end{itemize} \subsubsection{MRO エントリの解決} \label{\detokenize{reference/datamodel:resolving-mro-entries}} クラス定義に現れる基底が \sphinxcode{\sphinxupquote{type}} のインスタンスではない場合、そのインスタンスの \sphinxcode{\sphinxupquote{\_\_mro\_entries\_\_}} メソッドが検索されます。 見付かった場合、その基底そのものを要素に持つタプルを引数として、 \sphinxcode{\sphinxupquote{\_\_mro\_entries\_\_}} メソッドが呼び出されます。 このメソッドは、この基底の代わりに使われるクラスのタプルを返さなければなりません。 このタプルは空であることもあり、そのような場合ではその基底は無視されます。 \sphinxstrong{参考:} \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 560@\spxentry{PEP 560}}\sphinxhref{https://www.python.org/dev/peps/pep-0560}{\sphinxstylestrong{PEP 560}} \sphinxhyphen{} typing モジュールとジェネリック型に対する言語コアによるサポート \subsubsection{適切なメタクラスの決定} \label{\detokenize{reference/datamodel:determining-the-appropriate-metaclass}} \index{metaclass hint@\spxentry{metaclass hint}}\ignorespaces クラス定義に対して適切なメタクラスは、以下のように決定されます: \begin{itemize} \item {} 基底も明示的なメタクラスも与えられていない場合は、 \sphinxcode{\sphinxupquote{type()}} が使われます; \item {} 明示的なメタクラスが与えられていて、それが \sphinxcode{\sphinxupquote{type()}} のインスタンス \sphinxstyleemphasis{ではない} 場合、それをメタクラスとして直接使います; \item {} 明示的なメタクラスとして \sphinxcode{\sphinxupquote{type()}} のインスタンスが与えられたか、基底が定義されていた場合は、最も派生した (継承関係で最も下の) メタクラスが使われます。 \end{itemize} 最も派生的なメタクラスは、(もしあれば) 明示的に指定されたメタクラスと、指定されたすべてのベースクラスのメタクラスから選ばれます。最も派生的なメタクラスは、これらのメタクラス候補のすべてのサブタイプであるようなものです。メタクラス候補のどれもその基準を満たさなければ、クラス定義は \sphinxcode{\sphinxupquote{TypeError}} で失敗します。 \subsubsection{クラスの名前空間の準備} \label{\detokenize{reference/datamodel:preparing-the-class-namespace}}\label{\detokenize{reference/datamodel:prepare}} \index{\_\_prepare\_\_ (metaclass method)@\spxentry{\_\_prepare\_\_}\spxextra{metaclass method}}\ignorespaces Once the appropriate metaclass has been identified, then the class namespace is prepared. If the metaclass has a \sphinxcode{\sphinxupquote{\_\_prepare\_\_}} attribute, it is called as \sphinxcode{\sphinxupquote{namespace = metaclass.\_\_prepare\_\_(name, bases, **kwds)}} (where the additional keyword arguments, if any, come from the class definition). The \sphinxcode{\sphinxupquote{\_\_prepare\_\_}} method should be implemented as a \sphinxcode{\sphinxupquote{classmethod}}. The namespace returned by \sphinxcode{\sphinxupquote{\_\_prepare\_\_}} is passed in to \sphinxcode{\sphinxupquote{\_\_new\_\_}}, but when the final class object is created the namespace is copied into a new \sphinxcode{\sphinxupquote{dict}}. メタクラスに \sphinxcode{\sphinxupquote{\_\_prepare\_\_}} 属性がない場合、クラスの名前空間は空の 順序付きマッピングとして初期化されます。 \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 3115@\spxentry{PEP 3115}}\sphinxhref{https://www.python.org/dev/peps/pep-3115}{\sphinxstylestrong{PEP 3115}} \sphinxhyphen{} Metaclasses in Python 3000}] \leavevmode \sphinxcode{\sphinxupquote{\_\_prepare\_\_}} 名前空間フックの導入 \end{description} \subsubsection{クラス本体の実行} \label{\detokenize{reference/datamodel:executing-the-class-body}} \index{class@\spxentry{class}!body@\spxentry{body}}\ignorespaces クラス本体が (大まかには) \sphinxcode{\sphinxupquote{exec(body, globals(), namespace)}} として実行されます。通常の呼び出しと \sphinxcode{\sphinxupquote{exec()}} の重要な違いは、クラス定義が関数内部で行われる場合、レキシカルスコープによってクラス本体 (任意のメソッドを含む) が現在のスコープと外側のスコープから名前を参照できるという点です。 しかし、クラス定義が関数内部で行われる時でさえ、クラス内部で定義されたメソッドはクラススコープで定義された名前を見ることはできません。クラス変数はインスタンスメソッドかクラスメソッドの最初のパラメータからアクセスするか、次の節で説明する、暗黙的に静的スコープが切られている \sphinxcode{\sphinxupquote{\_\_class\_\_}} 参照からアクセスしなければなりません。 \subsubsection{クラスオブジェクトの作成} \label{\detokenize{reference/datamodel:creating-the-class-object}}\label{\detokenize{reference/datamodel:class-object-creation}} \index{\_\_class\_\_ (method cell)@\spxentry{\_\_class\_\_}\spxextra{method cell}}\index{\_\_classcell\_\_ (class namespace entry)@\spxentry{\_\_classcell\_\_}\spxextra{class namespace entry}}\ignorespaces クラス本体の実行によってクラスの名前空間が初期化されたら、\sphinxcode{\sphinxupquote{metaclass(name, bases, namespace, **kwds)}} を呼び出すことでクラスオブジェクトが作成されます (ここで渡される追加のキーワードは \sphinxcode{\sphinxupquote{\_\_prepare\_\_}} に渡されるものと同じです)。 このクラスオブジェクトは、 \sphinxcode{\sphinxupquote{super()}} の無引数形式によって参照されるものです。 \sphinxcode{\sphinxupquote{\_\_class\_\_}} は、クラス本体中のメソッドが \sphinxcode{\sphinxupquote{\_\_class\_\_}} または \sphinxcode{\sphinxupquote{super}} のいずれかを参照している場合に、コンパイラによって作成される暗黙のクロージャー参照です。これは、メソッドに渡された最初の引数に基づいて現在の呼び出しを行うために使用されるクラスまたはインスタンスが識別される一方、 \sphinxcode{\sphinxupquote{super()}} の無引数形式がレキシカルスコープに基づいて定義されているクラスを正確に識別することを可能にします。 \sphinxstylestrong{CPython implementation detail:} CPython 3.6 以降では、 \sphinxcode{\sphinxupquote{\_\_class\_\_}} セルは、クラス名前空間にある \sphinxcode{\sphinxupquote{\_\_classcell\_\_}} エントリーとしてメタクラスに渡されます。 \sphinxcode{\sphinxupquote{\_\_class\_\_}} セルが存在していた場合は、そのクラスが正しく初期化されるために、 \sphinxcode{\sphinxupquote{type.\_\_new\_\_}} の呼び出しに到達するまで上に伝搬されます。 失敗した場合は、Python 3.8 では \sphinxcode{\sphinxupquote{RuntimeError}} になります。 デフォルトのメタクラス \sphinxcode{\sphinxupquote{type}} や最終的には \sphinxcode{\sphinxupquote{type.\_\_new\_\_}} を呼び出すメタクラスを使っているときは、クラスオブジェクトを作成した後に次のカスタム化の手順が起動されます: \begin{itemize} \item {} 最初に、 \sphinxcode{\sphinxupquote{type.\_\_new\_\_}} が {\hyperref[\detokenize{reference/datamodel:object.__set_name__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_set\_name\_\_()}}}}} が定義されているクラスの名前空間にある全てのデスクリプタを収集します; \item {} 次に、それら全ての \sphinxcode{\sphinxupquote{\_\_set\_name\_\_}} メソッドが、そのメソッドが定義されているクラス、およびそこに属するデスクリプタに割り当てられている名前を引数として呼び出されます; \item {} 最後に、新しいクラスのメソッド解決順序ですぐ上に位置する親クラスで {\hyperref[\detokenize{reference/datamodel:object.__init_subclass__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_init\_subclass\_\_()}}}}} フックが呼び出されます。 \end{itemize} クラスオブジェクトが作成された後には、クラス定義に含まれているクラスデコレータ (もしあれば) にクラスオブジェクトが渡され、デコレータが返すオブジェクトがここで定義されたクラスとしてローカルの名前空間に束縛されます。 新しいクラスが \sphinxcode{\sphinxupquote{type.\_\_new\_\_}} で生成されたときは、名前空間引数として与えられたオブジェクトは新しい順序付きのマッピングに複製され、元のオブジェクトは破棄されます。 新しく複製したものは読み出し専用のプロキシでラップされ、クラスオブジェクトの \sphinxcode{\sphinxupquote{\_\_dict\_\_}} 属性になります。 \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 3135@\spxentry{PEP 3135}}\sphinxhref{https://www.python.org/dev/peps/pep-3135}{\sphinxstylestrong{PEP 3135}} \sphinxhyphen{} New super}] \leavevmode 暗黙の \sphinxcode{\sphinxupquote{\_\_class\_\_}} クロージャ参照について記述しています \end{description} \subsubsection{メタクラスの用途} \label{\detokenize{reference/datamodel:uses-for-metaclasses}} メタクラスは限りない潜在的利用価値を持っています。これまで試されてきたアイデアには、列挙型、ログ記録、インターフェースのチェック、 自動デリゲーション、自動プロパティ生成、プロキシ、フレームワーク、そして自動リソースロック/同期といったものがあります。 \subsection{インスタンスのカスタマイズとサブクラスチェック} \label{\detokenize{reference/datamodel:customizing-instance-and-subclass-checks}} 以下のメソッドは組み込み関数 \sphinxcode{\sphinxupquote{isinstance()}} と \sphinxcode{\sphinxupquote{issubclass()}} のデフォルトの動作を上書きするのに利用します。 特に、 \sphinxcode{\sphinxupquote{abc.ABCMeta}} メタクラスは、抽象基底クラス (ABCs) を"仮想基底クラス (virtual base classes)" として、他の ABC を含む、任意のクラスや (組み込み型を含む) 型に追加するために、これらのメソッドを実装しています。 \index{\_\_instancecheck\_\_() (class のメソッド)@\spxentry{\_\_instancecheck\_\_()}\spxextra{class のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:class.__instancecheck__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{class.}}\sphinxbfcode{\sphinxupquote{\_\_instancecheck\_\_}}}{\emph{self}, \emph{instance}}{} \sphinxstyleemphasis{instance} が (直接、または間接的に) \sphinxstyleemphasis{class} のインスタンスと考えられる場合に true を返します。定義されていれば、 \sphinxcode{\sphinxupquote{isinstance(instance, class)}} の実装のために呼び出されます。 \end{fulllineitems} \index{\_\_subclasscheck\_\_() (class のメソッド)@\spxentry{\_\_subclasscheck\_\_()}\spxextra{class のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:class.__subclasscheck__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{class.}}\sphinxbfcode{\sphinxupquote{\_\_subclasscheck\_\_}}}{\emph{self}, \emph{subclass}}{} \sphinxstyleemphasis{subclass} が (直接、または間接的に) \sphinxstyleemphasis{class} のサブクラスと考えられる場合に true を返します。定義されていれば、 \sphinxcode{\sphinxupquote{issubclass(subclass, class)}} の実装のために呼び出されます。 \end{fulllineitems} なお、これらのメソッドは、クラスの型 (メタクラス) 上で検索されます。実際のクラスにクラスメソッドとして定義することはできません。これは、インスタンスそれ自体がクラスであるこの場合にのみ、インスタンスに呼び出される特殊メソッドの検索と一貫しています。 \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 3119@\spxentry{PEP 3119}}\sphinxhref{https://www.python.org/dev/peps/pep-3119}{\sphinxstylestrong{PEP 3119}} \sphinxhyphen{} 抽象基底クラスの導入}] \leavevmode 抽象基底クラス (\sphinxcode{\sphinxupquote{abc}} モジュールを参照) を言語に追加する文脈においての動機から、 {\hyperref[\detokenize{reference/datamodel:class.__instancecheck__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_instancecheck\_\_()}}}}} と {\hyperref[\detokenize{reference/datamodel:class.__subclasscheck__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_subclasscheck\_\_()}}}}} を通して、 \sphinxcode{\sphinxupquote{isinstance()}} と \sphinxcode{\sphinxupquote{issubclass()}} に独自の動作をさせるための仕様の記述があります。 \end{description} \subsection{ジェネリック型をエミュレートする} \label{\detokenize{reference/datamodel:emulating-generic-types}} When using {\hyperref[\detokenize{glossary:term-annotation}]{\sphinxtermref{\DUrole{xref,std,std-term}{type annotations}}}}, it is often useful to \sphinxstyleemphasis{parameterize} a {\hyperref[\detokenize{glossary:term-generic-type}]{\sphinxtermref{\DUrole{xref,std,std-term}{generic type}}}} using Python's square\sphinxhyphen{}brackets notation. For example, the annotation \sphinxcode{\sphinxupquote{list{[}int{]}}} might be used to signify a \sphinxcode{\sphinxupquote{list}} in which all the elements are of type \sphinxcode{\sphinxupquote{int}}. \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 484@\spxentry{PEP 484}}\sphinxhref{https://www.python.org/dev/peps/pep-0484}{\sphinxstylestrong{PEP 484}} \sphinxhyphen{} Type Hints}] \leavevmode Introducing Python's framework for type annotations \item[{\DUrole{xref,std,std-ref}{Generic Alias Types}}] \leavevmode Documentation for objects representing parameterized generic classes \item[{\DUrole{xref,std,std-ref}{Generics}, \DUrole{xref,std,std-ref}{user\sphinxhyphen{}defined generics} and \sphinxcode{\sphinxupquote{typing.Generic}}}] \leavevmode Documentation on how to implement generic classes that can be parameterized at runtime and understood by static type\sphinxhyphen{}checkers. \end{description} A class can \sphinxstyleemphasis{generally} only be parameterized if it defines the special class method \sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}}. \index{\_\_class\_getitem\_\_() (object のクラスメソッド)@\spxentry{\_\_class\_getitem\_\_()}\spxextra{object のクラスメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__class_getitem__}}\pysiglinewithargsret{\sphinxbfcode{\sphinxupquote{classmethod }}\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_class\_getitem\_\_}}}{\emph{cls}, \emph{key}}{} \sphinxstyleemphasis{key} にある型引数で特殊化されたジェネリッククラスを表すオブジェクトを返します。 When defined on a class, \sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}} is automatically a class method. As such, there is no need for it to be decorated with \sphinxcode{\sphinxupquote{@classmethod}} when it is defined. \end{fulllineitems} \subsubsection{The purpose of \sphinxstyleemphasis{\_\_class\_getitem\_\_}} \label{\detokenize{reference/datamodel:the-purpose-of-class-getitem}} The purpose of {\hyperref[\detokenize{reference/datamodel:object.__class_getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}}}}} is to allow runtime parameterization of standard\sphinxhyphen{}library generic classes in order to more easily apply {\hyperref[\detokenize{glossary:term-type-hint}]{\sphinxtermref{\DUrole{xref,std,std-term}{type hints}}}} to these classes. To implement custom generic classes that can be parameterized at runtime and understood by static type\sphinxhyphen{}checkers, users should either inherit from a standard library class that already implements {\hyperref[\detokenize{reference/datamodel:object.__class_getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}}}}}, or inherit from \sphinxcode{\sphinxupquote{typing.Generic}}, which has its own implementation of \sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}}. Custom implementations of {\hyperref[\detokenize{reference/datamodel:object.__class_getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}}}}} on classes defined outside of the standard library may not be understood by third\sphinxhyphen{}party type\sphinxhyphen{}checkers such as mypy. Using \sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}} on any class for purposes other than type hinting is discouraged. \subsubsection{\sphinxstyleemphasis{\_\_class\_getitem\_\_} versus \sphinxstyleemphasis{\_\_getitem\_\_}} \label{\detokenize{reference/datamodel:class-getitem-versus-getitem}}\label{\detokenize{reference/datamodel:classgetitem-versus-getitem}} Usually, the {\hyperref[\detokenize{reference/expressions:subscriptions}]{\sphinxcrossref{\DUrole{std,std-ref}{subscription}}}} of an object using square brackets will call the {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} instance method defined on the object's class. However, if the object being subscribed is itself a class, the class method {\hyperref[\detokenize{reference/datamodel:object.__class_getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}}}}} may be called instead. \sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}} should return a \DUrole{xref,std,std-ref}{GenericAlias} object if it is properly defined. Presented with the {\hyperref[\detokenize{glossary:term-expression}]{\sphinxtermref{\DUrole{xref,std,std-term}{expression}}}} \sphinxcode{\sphinxupquote{obj{[}x{]}}}, the Python interpreter follows something like the following process to decide whether {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} or {\hyperref[\detokenize{reference/datamodel:object.__class_getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}}}}} should be called: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k+kn}{from} \PYG{n+nn}{inspect} \PYG{k+kn}{import} \PYG{n}{isclass} \PYG{k}{def} \PYG{n+nf}{subscribe}\PYG{p}{(}\PYG{n}{obj}\PYG{p}{,} \PYG{n}{x}\PYG{p}{)}\PYG{p}{:} \PYG{+w}{ }\PYG{l+s+sd}{\PYGZdq{}\PYGZdq{}\PYGZdq{}Return the result of the expression `obj[x]`\PYGZdq{}\PYGZdq{}\PYGZdq{}} \PYG{n}{class\PYGZus{}of\PYGZus{}obj} \PYG{o}{=} \PYG{n+nb}{type}\PYG{p}{(}\PYG{n}{obj}\PYG{p}{)} \PYG{c+c1}{\PYGZsh{} If the class of obj defines \PYGZus{}\PYGZus{}getitem\PYGZus{}\PYGZus{},} \PYG{c+c1}{\PYGZsh{} call class\PYGZus{}of\PYGZus{}obj.\PYGZus{}\PYGZus{}getitem\PYGZus{}\PYGZus{}(obj, x)} \PYG{k}{if} \PYG{n+nb}{hasattr}\PYG{p}{(}\PYG{n}{class\PYGZus{}of\PYGZus{}obj}\PYG{p}{,} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{\PYGZus{}\PYGZus{}getitem\PYGZus{}\PYGZus{}}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{)}\PYG{p}{:} \PYG{k}{return} \PYG{n}{class\PYGZus{}of\PYGZus{}obj}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}getitem\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n}{obj}\PYG{p}{,} \PYG{n}{x}\PYG{p}{)} \PYG{c+c1}{\PYGZsh{} Else, if obj is a class and defines \PYGZus{}\PYGZus{}class\PYGZus{}getitem\PYGZus{}\PYGZus{},} \PYG{c+c1}{\PYGZsh{} call obj.\PYGZus{}\PYGZus{}class\PYGZus{}getitem\PYGZus{}\PYGZus{}(x)} \PYG{k}{elif} \PYG{n}{isclass}\PYG{p}{(}\PYG{n}{obj}\PYG{p}{)} \PYG{o+ow}{and} \PYG{n+nb}{hasattr}\PYG{p}{(}\PYG{n}{obj}\PYG{p}{,} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{\PYGZus{}\PYGZus{}class\PYGZus{}getitem\PYGZus{}\PYGZus{}}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{)}\PYG{p}{:} \PYG{k}{return} \PYG{n}{obj}\PYG{o}{.}\PYG{n}{\PYGZus{}\PYGZus{}class\PYGZus{}getitem\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)} \PYG{c+c1}{\PYGZsh{} Else, raise an exception} \PYG{k}{else}\PYG{p}{:} \PYG{k}{raise} \PYG{n+ne}{TypeError}\PYG{p}{(} \PYG{l+s+sa}{f}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{\PYGZsq{}}\PYG{l+s+si}{\PYGZob{}}\PYG{n}{class\PYGZus{}of\PYGZus{}obj}\PYG{o}{.}\PYG{n+nv+vm}{\PYGZus{}\PYGZus{}name\PYGZus{}\PYGZus{}}\PYG{l+s+si}{\PYGZcb{}}\PYG{l+s+s2}{\PYGZsq{}}\PYG{l+s+s2}{ object is not subscriptable}\PYG{l+s+s2}{\PYGZdq{}} \PYG{p}{)} \end{sphinxVerbatim} In Python, all classes are themselves instances of other classes. The class of a class is known as that class's {\hyperref[\detokenize{glossary:term-metaclass}]{\sphinxtermref{\DUrole{xref,std,std-term}{metaclass}}}}, and most classes have the \sphinxcode{\sphinxupquote{type}} class as their metaclass. \sphinxcode{\sphinxupquote{type}} does not define {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}}, meaning that expressions such as \sphinxcode{\sphinxupquote{list{[}int{]}}}, \sphinxcode{\sphinxupquote{dict{[}str, float{]}}} and \sphinxcode{\sphinxupquote{tuple{[}str, bytes{]}}} all result in {\hyperref[\detokenize{reference/datamodel:object.__class_getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}}}}} being called: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{c+c1}{\PYGZsh{} list has class \PYGZdq{}type\PYGZdq{} as its metaclass, like most classes:} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{type}\PYG{p}{(}\PYG{n+nb}{list}\PYG{p}{)} \PYG{g+go}{\PYGZlt{}class \PYGZsq{}type\PYGZsq{}\PYGZgt{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{type}\PYG{p}{(}\PYG{n+nb}{dict}\PYG{p}{)} \PYG{o}{==} \PYG{n+nb}{type}\PYG{p}{(}\PYG{n+nb}{list}\PYG{p}{)} \PYG{o}{==} \PYG{n+nb}{type}\PYG{p}{(}\PYG{n+nb}{tuple}\PYG{p}{)} \PYG{o}{==} \PYG{n+nb}{type}\PYG{p}{(}\PYG{n+nb}{str}\PYG{p}{)} \PYG{o}{==} \PYG{n+nb}{type}\PYG{p}{(}\PYG{n+nb}{bytes}\PYG{p}{)} \PYG{g+go}{True} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{c+c1}{\PYGZsh{} \PYGZdq{}list[int]\PYGZdq{} calls \PYGZdq{}list.\PYGZus{}\PYGZus{}class\PYGZus{}getitem\PYGZus{}\PYGZus{}(int)\PYGZdq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{list}\PYG{p}{[}\PYG{n+nb}{int}\PYG{p}{]} \PYG{g+go}{list[int]} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{c+c1}{\PYGZsh{} list.\PYGZus{}\PYGZus{}class\PYGZus{}getitem\PYGZus{}\PYGZus{} returns a GenericAlias object:} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{type}\PYG{p}{(}\PYG{n+nb}{list}\PYG{p}{[}\PYG{n+nb}{int}\PYG{p}{]}\PYG{p}{)} \PYG{g+go}{\PYGZlt{}class \PYGZsq{}types.GenericAlias\PYGZsq{}\PYGZgt{}} \end{sphinxVerbatim} However, if a class has a custom metaclass that defines {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}}, subscribing the class may result in different behaviour. An example of this can be found in the \sphinxcode{\sphinxupquote{enum}} module: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k+kn}{from} \PYG{n+nn}{enum} \PYG{k+kn}{import} \PYG{n}{Enum} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k}{class} \PYG{n+nc}{Menu}\PYG{p}{(}\PYG{n}{Enum}\PYG{p}{)}\PYG{p}{:} \PYG{g+gp}{... }\PYG{+w}{ }\PYG{l+s+sd}{\PYGZdq{}\PYGZdq{}\PYGZdq{}A breakfast menu\PYGZdq{}\PYGZdq{}\PYGZdq{}} \PYG{g+gp}{... } \PYG{n}{SPAM} \PYG{o}{=} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{spam}\PYG{l+s+s1}{\PYGZsq{}} \PYG{g+gp}{... } \PYG{n}{BACON} \PYG{o}{=} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{bacon}\PYG{l+s+s1}{\PYGZsq{}} \PYG{g+gp}{...} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{c+c1}{\PYGZsh{} Enum classes have a custom metaclass:} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{type}\PYG{p}{(}\PYG{n}{Menu}\PYG{p}{)} \PYG{g+go}{\PYGZlt{}class \PYGZsq{}enum.EnumMeta\PYGZsq{}\PYGZgt{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{c+c1}{\PYGZsh{} EnumMeta defines \PYGZus{}\PYGZus{}getitem\PYGZus{}\PYGZus{},} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{c+c1}{\PYGZsh{} so \PYGZus{}\PYGZus{}class\PYGZus{}getitem\PYGZus{}\PYGZus{} is not called,} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{c+c1}{\PYGZsh{} and the result is not a GenericAlias object:} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{Menu}\PYG{p}{[}\PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{SPAM}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{]} \PYG{g+go}{\PYGZlt{}Menu.SPAM: \PYGZsq{}spam\PYGZsq{}\PYGZgt{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{type}\PYG{p}{(}\PYG{n}{Menu}\PYG{p}{[}\PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{SPAM}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{]}\PYG{p}{)} \PYG{g+go}{\PYGZlt{}enum \PYGZsq{}Menu\PYGZsq{}\PYGZgt{}} \end{sphinxVerbatim} \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 560@\spxentry{PEP 560}}\sphinxhref{https://www.python.org/dev/peps/pep-0560}{\sphinxstylestrong{PEP 560}} \sphinxhyphen{} Core Support for typing module and generic types}] \leavevmode Introducing {\hyperref[\detokenize{reference/datamodel:object.__class_getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}}}}}, and outlining when a {\hyperref[\detokenize{reference/expressions:subscriptions}]{\sphinxcrossref{\DUrole{std,std-ref}{subscription}}}} results in \sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}} being called instead of {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} \end{description} \subsection{呼び出し可能オブジェクトをエミュレートする} \label{\detokenize{reference/datamodel:emulating-callable-objects}}\label{\detokenize{reference/datamodel:callable-types}}\index{\_\_call\_\_() (object のメソッド)@\spxentry{\_\_call\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__call__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_call\_\_}}}{\emph{self}\sphinxoptional{, \emph{args...}}}{}~ \index{call@\spxentry{call}!instance@\spxentry{instance}}\index{instance@\spxentry{instance}!call@\spxentry{call}}\ignorespaces インスタンスがカンストして "呼ばれた" 際に呼び出されます。このメソッドが \sphinxcode{\sphinxupquote{x(arg1, arg2, ...)}} 定義されている場合、これは大まかには \sphinxcode{\sphinxupquote{type(x).\_\_call\_\_(x, arg1, ...)}} に変換されます。 \end{fulllineitems} \subsection{コンテナをエミュレートする} \label{\detokenize{reference/datamodel:emulating-container-types}}\label{\detokenize{reference/datamodel:sequence-types}} The following methods can be defined to implement container objects. Containers usually are {\hyperref[\detokenize{glossary:term-sequence}]{\sphinxtermref{\DUrole{xref,std,std-term}{sequences}}}} (such as \sphinxcode{\sphinxupquote{lists}} or \sphinxcode{\sphinxupquote{tuples}}) or {\hyperref[\detokenize{glossary:term-mapping}]{\sphinxtermref{\DUrole{xref,std,std-term}{mappings}}}} (like \sphinxcode{\sphinxupquote{dictionaries}}), but can represent other containers as well. The first set of methods is used either to emulate a sequence or to emulate a mapping; the difference is that for a sequence, the allowable keys should be the integers \sphinxstyleemphasis{k} for which \sphinxcode{\sphinxupquote{0 <= k < N}} where \sphinxstyleemphasis{N} is the length of the sequence, or \sphinxcode{\sphinxupquote{slice}} objects, which define a range of items. It is also recommended that mappings provide the methods \sphinxcode{\sphinxupquote{keys()}}, \sphinxcode{\sphinxupquote{values()}}, \sphinxcode{\sphinxupquote{items()}}, \sphinxcode{\sphinxupquote{get()}}, \sphinxcode{\sphinxupquote{clear()}}, \sphinxcode{\sphinxupquote{setdefault()}}, \sphinxcode{\sphinxupquote{pop()}}, \sphinxcode{\sphinxupquote{popitem()}}, \sphinxcode{\sphinxupquote{copy()}}, and \sphinxcode{\sphinxupquote{update()}} behaving similar to those for Python's standard \sphinxcode{\sphinxupquote{dictionary}} objects. The \sphinxcode{\sphinxupquote{collections.abc}} module provides a \sphinxcode{\sphinxupquote{MutableMapping}} {\hyperref[\detokenize{glossary:term-abstract-base-class}]{\sphinxtermref{\DUrole{xref,std,std-term}{abstract base class}}}} to help create those methods from a base set of {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}}, {\hyperref[\detokenize{reference/datamodel:object.__setitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_setitem\_\_()}}}}}, {\hyperref[\detokenize{reference/datamodel:object.__delitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_delitem\_\_()}}}}}, and \sphinxcode{\sphinxupquote{keys()}}. Mutable sequences should provide methods \sphinxcode{\sphinxupquote{append()}}, \sphinxcode{\sphinxupquote{count()}}, \sphinxcode{\sphinxupquote{index()}}, \sphinxcode{\sphinxupquote{extend()}}, \sphinxcode{\sphinxupquote{insert()}}, \sphinxcode{\sphinxupquote{pop()}}, \sphinxcode{\sphinxupquote{remove()}}, \sphinxcode{\sphinxupquote{reverse()}} and \sphinxcode{\sphinxupquote{sort()}}, like Python standard \sphinxcode{\sphinxupquote{list}} objects. Finally, sequence types should implement addition (meaning concatenation) and multiplication (meaning repetition) by defining the methods {\hyperref[\detokenize{reference/datamodel:object.__add__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_add\_\_()}}}}}, {\hyperref[\detokenize{reference/datamodel:object.__radd__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_radd\_\_()}}}}}, {\hyperref[\detokenize{reference/datamodel:object.__iadd__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_iadd\_\_()}}}}}, {\hyperref[\detokenize{reference/datamodel:object.__mul__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_mul\_\_()}}}}}, {\hyperref[\detokenize{reference/datamodel:object.__rmul__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_rmul\_\_()}}}}} and {\hyperref[\detokenize{reference/datamodel:object.__imul__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_imul\_\_()}}}}} described below; they should not define other numerical operators. It is recommended that both mappings and sequences implement the {\hyperref[\detokenize{reference/datamodel:object.__contains__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_contains\_\_()}}}}} method to allow efficient use of the \sphinxcode{\sphinxupquote{in}} operator; for mappings, \sphinxcode{\sphinxupquote{in}} should search the mapping's keys; for sequences, it should search through the values. It is further recommended that both mappings and sequences implement the {\hyperref[\detokenize{reference/datamodel:object.__iter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_iter\_\_()}}}}} method to allow efficient iteration through the container; for mappings, {\hyperref[\detokenize{reference/datamodel:object.__iter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_iter\_\_()}}}}} should iterate through the object's keys; for sequences, it should iterate through the values. \index{\_\_len\_\_() (object のメソッド)@\spxentry{\_\_len\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__len__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_len\_\_}}}{\emph{self}}{}~ \index{組み込み関数@\spxentry{組み込み関数}!len@\spxentry{len}}\index{len@\spxentry{len}!組み込み関数@\spxentry{組み込み関数}}\index{\_\_bool\_\_() (object method)@\spxentry{\_\_bool\_\_()}\spxextra{object method}}\ignorespaces 呼び出して組み込み関数 \sphinxcode{\sphinxupquote{len()}} を実装します。 オブジェクトの長さを 0 以上の整数で返さなければなりません。 また、 {\hyperref[\detokenize{reference/datamodel:object.__bool__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_bool\_\_()}}}}} メソッドを定義しておらず、 {\hyperref[\detokenize{reference/datamodel:object.__len__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_len\_\_()}}}}} メソッドが 0 を返すようなオブジェクトは、ブール演算コンテキストでは偽とみなされます。 \sphinxstylestrong{CPython implementation detail:} CPython では、オブジェクトの長さは最大でも \sphinxcode{\sphinxupquote{sys.maxsize}} であることが要求されます。 長さが \sphinxcode{\sphinxupquote{sys.maxsize}} を越える場合、(\sphinxcode{\sphinxupquote{len()}} のような) いくつかの機能は \sphinxcode{\sphinxupquote{OverflowError}} を送出するでしょう。 真偽値としての判定で \sphinxcode{\sphinxupquote{OverflowError}} を送出しないようにするには、オブジェクトは meth:\sphinxtitleref{\_\_bool\_\_} メソッドを定義していなければなりません。 \end{fulllineitems} \index{\_\_length\_hint\_\_() (object のメソッド)@\spxentry{\_\_length\_hint\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__length_hint__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_length\_hint\_\_}}}{\emph{self}}{} 呼び出して \sphinxcode{\sphinxupquote{operator.length\_hint()}} を実装します。オブジェクトの推定される長さ (実際のものより長かったり短かったりするかもしれません) を返さなければなりません。長さは 0 以上の整数でなければなりません。返り値は \sphinxcode{\sphinxupquote{NotImplemented}} となる場合もありますが、その場合は \sphinxcode{\sphinxupquote{\_\_length\_hint\_\_}} メソッドがなかった場合と同じと扱われます。このメソッドは純粋に最適化であり、正確性は必要ではありません。 \DUrole{versionmodified,added}{バージョン 3.4 で追加.} \end{fulllineitems} \index{オブジェクト@\spxentry{オブジェクト}!slice@\spxentry{slice}}\index{slice@\spxentry{slice}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces \begin{sphinxadmonition}{note}{注釈:} スライシングは、以下の 3 メソッドによって排他的に行われます。次のような呼び出しは \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{a}\PYG{p}{[}\PYG{l+m+mi}{1}\PYG{p}{:}\PYG{l+m+mi}{2}\PYG{p}{]} \PYG{o}{=} \PYG{n}{b} \end{sphinxVerbatim} 次のように翻訳され \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{a}\PYG{p}{[}\PYG{n+nb}{slice}\PYG{p}{(}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{2}\PYG{p}{,} \PYG{k+kc}{None}\PYG{p}{)}\PYG{p}{]} \PYG{o}{=} \PYG{n}{b} \end{sphinxVerbatim} 以下も同様です。存在しないスライスの要素は \sphinxcode{\sphinxupquote{None}} で埋められます。 \end{sphinxadmonition} \index{\_\_getitem\_\_() (object のメソッド)@\spxentry{\_\_getitem\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__getitem__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_getitem\_\_}}}{\emph{self}, \emph{key}}{} Called to implement evaluation of \sphinxcode{\sphinxupquote{self{[}key{]}}}. For {\hyperref[\detokenize{glossary:term-sequence}]{\sphinxtermref{\DUrole{xref,std,std-term}{sequence}}}} types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a {\hyperref[\detokenize{glossary:term-sequence}]{\sphinxtermref{\DUrole{xref,std,std-term}{sequence}}}} type) is up to the {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} method. If \sphinxstyleemphasis{key} is of an inappropriate type, \sphinxcode{\sphinxupquote{TypeError}} may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), \sphinxcode{\sphinxupquote{IndexError}} should be raised. For {\hyperref[\detokenize{glossary:term-mapping}]{\sphinxtermref{\DUrole{xref,std,std-term}{mapping}}}} types, if \sphinxstyleemphasis{key} is missing (not in the container), \sphinxcode{\sphinxupquote{KeyError}} should be raised. \begin{sphinxadmonition}{note}{注釈:} {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} ループでは、シーケンスの終端を正しく検出できるようにするために、不正なインデクスに対して \sphinxcode{\sphinxupquote{IndexError}} が送出されるものと期待しています。 \end{sphinxadmonition} \begin{sphinxadmonition}{note}{注釈:} When {\hyperref[\detokenize{reference/expressions:subscriptions}]{\sphinxcrossref{\DUrole{std,std-ref}{subscripting}}}} a \sphinxstyleemphasis{class}, the special class method {\hyperref[\detokenize{reference/datamodel:object.__class_getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}}}}} may be called instead of \sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}. See {\hyperref[\detokenize{reference/datamodel:classgetitem-versus-getitem}]{\sphinxcrossref{\DUrole{std,std-ref}{\_\_class\_getitem\_\_ versus \_\_getitem\_\_}}}} for more details. \end{sphinxadmonition} \end{fulllineitems} \index{\_\_setitem\_\_() (object のメソッド)@\spxentry{\_\_setitem\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__setitem__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_setitem\_\_}}}{\emph{self}, \emph{key}, \emph{value}}{} \sphinxcode{\sphinxupquote{self{[}key{]}}} に対する代入を実装するために呼び出されます。 {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} と同じ注意事項があてはまります。このメソッドを実装できるのは、あるキーに対する値の変更をサポートしているか、新たなキーを追加できるようなマップの場合と、ある要素を置き換えることができるシーケンスの場合だけです。不正な \sphinxstyleemphasis{key} に対しては、 {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} メソッドと同様の例外の送出を行わなければなりません。 \end{fulllineitems} \index{\_\_delitem\_\_() (object のメソッド)@\spxentry{\_\_delitem\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__delitem__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_delitem\_\_}}}{\emph{self}, \emph{key}}{} \sphinxcode{\sphinxupquote{self{[}key{]}}} の削除を実装するために呼び出されます。 {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} と同じ注意事項があてはまります。このメソッドを実装できるのは、キーの削除をサポートしているマップの場合と、要素を削除できるシーケンスの場合だけです。不正な \sphinxstyleemphasis{key} に対しては、 {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} メソッドと同様の例外の送出を行わなければなりません。 \end{fulllineitems} \index{\_\_missing\_\_() (object のメソッド)@\spxentry{\_\_missing\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__missing__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_missing\_\_}}}{\emph{self}, \emph{key}}{} \sphinxcode{\sphinxupquote{self{[}key{]}}} の実装において辞書内にキーが存在しなかった場合に、 dict のサブクラスのために \sphinxcode{\sphinxupquote{dict}}.{\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} によって呼び出されます。 \end{fulllineitems} \index{\_\_iter\_\_() (object のメソッド)@\spxentry{\_\_iter\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__iter__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_iter\_\_}}}{\emph{self}}{} このメソッドは、コンテナに対してイテレータが要求された際に呼び出されます。このメソッドは、コンテナ内の全てのオブジェクトに渡って反復処理できるような、新たなイテレータオブジェクトを返さなければなりません。マッピングでは、コンテナ内のキーに渡って反復処理しなければなりません。 イテレータオブジェクトでもこのメソッドを実装する必要があります; イテレータの場合、自分自身を返さなければなりません。イテレータオブジェクトに関するより詳細な情報は、 \DUrole{xref,std,std-ref}{typeiter} を参照してください。 \end{fulllineitems} \index{\_\_reversed\_\_() (object のメソッド)@\spxentry{\_\_reversed\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__reversed__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_reversed\_\_}}}{\emph{self}}{} \sphinxcode{\sphinxupquote{reversed()}} 組み込み関数が逆方向イテレーションを実装するために、(存在すれば)呼び出します。コンテナ内の全要素を逆順にイテレートする、新しいイテレータを返すべきです。 {\hyperref[\detokenize{reference/datamodel:object.__reversed__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_reversed\_\_()}}}}} メソッドが定義されていない場合、 \sphinxcode{\sphinxupquote{reversed()}} 組込み関数は sequence プロトコル ({\hyperref[\detokenize{reference/datamodel:object.__len__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_len\_\_()}}}}} と {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}}) を使った方法にフォールバックします。 sequence プロトコルをサポートしたオブジェクトは、 \sphinxcode{\sphinxupquote{reversed()}} よりも効率のいい実装を提供できる場合にのみ {\hyperref[\detokenize{reference/datamodel:object.__reversed__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_reversed\_\_()}}}}} を定義するべきです。 \end{fulllineitems} 帰属テスト演算子 ({\hyperref[\detokenize{reference/expressions:in}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{in}}}}} および {\hyperref[\detokenize{reference/expressions:not-in}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{not in}}}}}) は通常、コンテナの要素に対する反復処理のように実装されます。しかし、コンテナオブジェクトで以下の特殊メソッドを定義して、より効率的な実装を行ったり、オブジェクトがイテラブルでなくてもよいようにできます。 \index{\_\_contains\_\_() (object のメソッド)@\spxentry{\_\_contains\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__contains__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_contains\_\_}}}{\emph{self}, \emph{item}}{} 帰属テスト演算を実装するために呼び出されます。 \sphinxstyleemphasis{item} が \sphinxstyleemphasis{self} 内に存在する場合には真を、そうでない場合には偽を返さなければなりません。マップオブジェクトの場合、値やキーと値の組ではなく、キーに対する帰属テストを考えなければなりません。 {\hyperref[\detokenize{reference/datamodel:object.__contains__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_contains\_\_()}}}}} を定義しないオブジェクトに対しては、メンバシップテストはまず、 {\hyperref[\detokenize{reference/datamodel:object.__iter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_iter\_\_()}}}}} を使った反復を試みます、次に古いシーケンス反復プロトコル {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} を使います、 {\hyperref[\detokenize{reference/expressions:membership-test-details}]{\sphinxcrossref{\DUrole{std,std-ref}{言語レファレンスのこの節}}}} を参照して下さい。 \end{fulllineitems} \subsection{数値型をエミュレートする} \label{\detokenize{reference/datamodel:emulating-numeric-types}}\label{\detokenize{reference/datamodel:numeric-types}} 以下のメソッドを定義して、数値型オブジェクトをエミュレートすることができます。特定の種類の数値型ではサポートされていないような演算に対応するメソッド (非整数の数値に対するビット単位演算など) は、未定義のままにしておかなければなりません。 \index{\_\_add\_\_() (object のメソッド)@\spxentry{\_\_add\_\_()}\spxextra{object のメソッド}}\index{\_\_sub\_\_() (object のメソッド)@\spxentry{\_\_sub\_\_()}\spxextra{object のメソッド}}\index{\_\_mul\_\_() (object のメソッド)@\spxentry{\_\_mul\_\_()}\spxextra{object のメソッド}}\index{\_\_matmul\_\_() (object のメソッド)@\spxentry{\_\_matmul\_\_()}\spxextra{object のメソッド}}\index{\_\_truediv\_\_() (object のメソッド)@\spxentry{\_\_truediv\_\_()}\spxextra{object のメソッド}}\index{\_\_floordiv\_\_() (object のメソッド)@\spxentry{\_\_floordiv\_\_()}\spxextra{object のメソッド}}\index{\_\_mod\_\_() (object のメソッド)@\spxentry{\_\_mod\_\_()}\spxextra{object のメソッド}}\index{\_\_divmod\_\_() (object のメソッド)@\spxentry{\_\_divmod\_\_()}\spxextra{object のメソッド}}\index{\_\_pow\_\_() (object のメソッド)@\spxentry{\_\_pow\_\_()}\spxextra{object のメソッド}}\index{\_\_lshift\_\_() (object のメソッド)@\spxentry{\_\_lshift\_\_()}\spxextra{object のメソッド}}\index{\_\_rshift\_\_() (object のメソッド)@\spxentry{\_\_rshift\_\_()}\spxextra{object のメソッド}}\index{\_\_and\_\_() (object のメソッド)@\spxentry{\_\_and\_\_()}\spxextra{object のメソッド}}\index{\_\_xor\_\_() (object のメソッド)@\spxentry{\_\_xor\_\_()}\spxextra{object のメソッド}}\index{\_\_or\_\_() (object のメソッド)@\spxentry{\_\_or\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__add__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_add\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__sub__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_sub\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__mul__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_mul\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__matmul__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_matmul\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__truediv__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_truediv\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__floordiv__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_floordiv\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__mod__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_mod\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__divmod__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_divmod\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__pow__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_pow\_\_}}}{\emph{self}, \emph{other}\sphinxoptional{, \emph{modulo}}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__lshift__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_lshift\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__rshift__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_rshift\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__and__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_and\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__xor__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_xor\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__or__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_or\_\_}}}{\emph{self}, \emph{other}}{}~ \index{組み込み関数@\spxentry{組み込み関数}!divmod@\spxentry{divmod}}\index{divmod@\spxentry{divmod}!組み込み関数@\spxentry{組み込み関数}}\index{組み込み関数@\spxentry{組み込み関数}!pow@\spxentry{pow}}\index{pow@\spxentry{pow}!組み込み関数@\spxentry{組み込み関数}}\index{組み込み関数@\spxentry{組み込み関数}!pow@\spxentry{pow}}\index{pow@\spxentry{pow}!組み込み関数@\spxentry{組み込み関数}}\ignorespaces これらのメソッドを呼んで二項算術演算子 (\sphinxcode{\sphinxupquote{+}}, \sphinxcode{\sphinxupquote{\sphinxhyphen{}}}, \sphinxcode{\sphinxupquote{*}}, \sphinxcode{\sphinxupquote{@}}, \sphinxcode{\sphinxupquote{/}}, \sphinxcode{\sphinxupquote{//}}, \sphinxcode{\sphinxupquote{\%}}, \sphinxcode{\sphinxupquote{divmod()}}, \sphinxcode{\sphinxupquote{pow()}}, \sphinxcode{\sphinxupquote{**}}, \sphinxcode{\sphinxupquote{<<}}, \sphinxcode{\sphinxupquote{>>}}, \sphinxcode{\sphinxupquote{\&}}, \sphinxcode{\sphinxupquote{\textasciicircum{}}}, \sphinxcode{\sphinxupquote{|}}) を実装します。 例えば \sphinxstyleemphasis{x} が {\hyperref[\detokenize{reference/datamodel:object.__add__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_add\_\_()}}}}} メソッドのあるクラスのインスタンスである場合、式 \sphinxcode{\sphinxupquote{x + y}} を評価すると \sphinxcode{\sphinxupquote{x.\_\_add\_\_(y)}} が呼ばれます。 {\hyperref[\detokenize{reference/datamodel:object.__divmod__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_divmod\_\_()}}}}} メソッドは {\hyperref[\detokenize{reference/datamodel:object.__floordiv__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_floordiv\_\_()}}}}} と {\hyperref[\detokenize{reference/datamodel:object.__mod__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_mod\_\_()}}}}} を使用するのと等価でなければなりません。 {\hyperref[\detokenize{reference/datamodel:object.__truediv__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_truediv\_\_()}}}}} と関連してはなりません。 組み込みの \sphinxcode{\sphinxupquote{pow()}} 関数の三項のものがサポートされていなければならない場合、 {\hyperref[\detokenize{reference/datamodel:object.__pow__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_pow\_\_()}}}}} はオプションの第三引数を受け取るものとして定義されなければなりません。 これらのメソッドのいずれかが渡された引数に対する操作を提供していない場合、 \sphinxcode{\sphinxupquote{NotImplemented}} を返すべきです。 \end{fulllineitems} \index{\_\_radd\_\_() (object のメソッド)@\spxentry{\_\_radd\_\_()}\spxextra{object のメソッド}}\index{\_\_rsub\_\_() (object のメソッド)@\spxentry{\_\_rsub\_\_()}\spxextra{object のメソッド}}\index{\_\_rmul\_\_() (object のメソッド)@\spxentry{\_\_rmul\_\_()}\spxextra{object のメソッド}}\index{\_\_rmatmul\_\_() (object のメソッド)@\spxentry{\_\_rmatmul\_\_()}\spxextra{object のメソッド}}\index{\_\_rtruediv\_\_() (object のメソッド)@\spxentry{\_\_rtruediv\_\_()}\spxextra{object のメソッド}}\index{\_\_rfloordiv\_\_() (object のメソッド)@\spxentry{\_\_rfloordiv\_\_()}\spxextra{object のメソッド}}\index{\_\_rmod\_\_() (object のメソッド)@\spxentry{\_\_rmod\_\_()}\spxextra{object のメソッド}}\index{\_\_rdivmod\_\_() (object のメソッド)@\spxentry{\_\_rdivmod\_\_()}\spxextra{object のメソッド}}\index{\_\_rpow\_\_() (object のメソッド)@\spxentry{\_\_rpow\_\_()}\spxextra{object のメソッド}}\index{\_\_rlshift\_\_() (object のメソッド)@\spxentry{\_\_rlshift\_\_()}\spxextra{object のメソッド}}\index{\_\_rrshift\_\_() (object のメソッド)@\spxentry{\_\_rrshift\_\_()}\spxextra{object のメソッド}}\index{\_\_rand\_\_() (object のメソッド)@\spxentry{\_\_rand\_\_()}\spxextra{object のメソッド}}\index{\_\_rxor\_\_() (object のメソッド)@\spxentry{\_\_rxor\_\_()}\spxextra{object のメソッド}}\index{\_\_ror\_\_() (object のメソッド)@\spxentry{\_\_ror\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__radd__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_radd\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__rsub__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_rsub\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__rmul__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_rmul\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__rmatmul__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_rmatmul\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__rtruediv__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_rtruediv\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__rfloordiv__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_rfloordiv\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__rmod__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_rmod\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__rdivmod__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_rdivmod\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__rpow__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_rpow\_\_}}}{\emph{self}, \emph{other}\sphinxoptional{, \emph{modulo}}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__rlshift__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_rlshift\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__rrshift__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_rrshift\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__rand__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_rand\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__rxor__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_rxor\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__ror__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_ror\_\_}}}{\emph{self}, \emph{other}}{}~ \index{組み込み関数@\spxentry{組み込み関数}!divmod@\spxentry{divmod}}\index{divmod@\spxentry{divmod}!組み込み関数@\spxentry{組み込み関数}}\index{組み込み関数@\spxentry{組み込み関数}!pow@\spxentry{pow}}\index{pow@\spxentry{pow}!組み込み関数@\spxentry{組み込み関数}}\ignorespaces これらのメソッドを呼んで二項算術演算 (\sphinxcode{\sphinxupquote{+}}, \sphinxcode{\sphinxupquote{\sphinxhyphen{}}}, \sphinxcode{\sphinxupquote{*}}, \sphinxcode{\sphinxupquote{@}}, \sphinxcode{\sphinxupquote{/}}, \sphinxcode{\sphinxupquote{//}}, \sphinxcode{\sphinxupquote{\%}}, \sphinxcode{\sphinxupquote{divmod()}}, \sphinxcode{\sphinxupquote{pow()}}, \sphinxcode{\sphinxupquote{**}}, \sphinxcode{\sphinxupquote{<<}}, \sphinxcode{\sphinxupquote{>>}}, \sphinxcode{\sphinxupquote{\&}}, \sphinxcode{\sphinxupquote{\textasciicircum{}}}, \sphinxcode{\sphinxupquote{|}}) の、被演算子が反射した (入れ替えられた) ものを実装します。 これらの関数は、左側の被演算子が対応する演算をサポートしておらず % \begin{footnote}[3]\sphinxAtStartFootnote ここでの "サポートしていない" というのは、クラスがそのメソッドを持っていないか、そのメソッドが \sphinxcode{\sphinxupquote{NotImplemented}} を返すという意味です。 右の被演算子の対をなすメソッドへ処理を回したい場合には、メソッドに \sphinxcode{\sphinxupquote{None}} を設定してはいけません—こうするとむしろ、処理を回すのを明示的に \sphinxstyleemphasis{妨げる} という正反対の効果を生みます。 % \end{footnote} 、非演算子が異なる型の場合にのみ呼び出されます。 % \begin{footnote}[4]\sphinxAtStartFootnote For operands of the same type, it is assumed that if the non\sphinxhyphen{}reflected method \sphinxhyphen{}\sphinxhyphen{} such as {\hyperref[\detokenize{reference/datamodel:object.__add__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_add\_\_()}}}}} \sphinxhyphen{}\sphinxhyphen{} fails then the overall operation is not supported, which is why the reflected method is not called. % \end{footnote} 例えば、 \sphinxstyleemphasis{y} が {\hyperref[\detokenize{reference/datamodel:object.__rsub__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_rsub\_\_()}}}}} メソッドのあるクラスのインスタンスである場合、 式 \sphinxcode{\sphinxupquote{x \sphinxhyphen{} y}} を評価すると \sphinxcode{\sphinxupquote{x.\_\_sub\_\_(y)}} が \sphinxstyleemphasis{NotImplemented} を返すときは \sphinxcode{\sphinxupquote{y.\_\_rsub\_\_(x)}} が呼ばれます。 \index{組み込み関数@\spxentry{組み込み関数}!pow@\spxentry{pow}}\index{pow@\spxentry{pow}!組み込み関数@\spxentry{組み込み関数}}\ignorespaces ただし、三項演算子 \sphinxcode{\sphinxupquote{pow()}} が {\hyperref[\detokenize{reference/datamodel:object.__rpow__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_rpow\_\_()}}}}} を呼ぶことはないので注意してください (型強制の規則が非常に難解になるからです)。 \begin{sphinxadmonition}{note}{注釈:} 右側の被演算子の型が左側の被演算子の型のサブクラスであり、このサブクラスであるメソッドに対する反射メソッドと異なる実装が定義されている場合には、左側の被演算子の非反射メソッドが呼ばれる前に、このメソッドが呼ばれます。この振る舞いにより、サブクラスが親の演算をオーバーライドすることが可能になります。 \end{sphinxadmonition} \end{fulllineitems} \index{\_\_iadd\_\_() (object のメソッド)@\spxentry{\_\_iadd\_\_()}\spxextra{object のメソッド}}\index{\_\_isub\_\_() (object のメソッド)@\spxentry{\_\_isub\_\_()}\spxextra{object のメソッド}}\index{\_\_imul\_\_() (object のメソッド)@\spxentry{\_\_imul\_\_()}\spxextra{object のメソッド}}\index{\_\_imatmul\_\_() (object のメソッド)@\spxentry{\_\_imatmul\_\_()}\spxextra{object のメソッド}}\index{\_\_itruediv\_\_() (object のメソッド)@\spxentry{\_\_itruediv\_\_()}\spxextra{object のメソッド}}\index{\_\_ifloordiv\_\_() (object のメソッド)@\spxentry{\_\_ifloordiv\_\_()}\spxextra{object のメソッド}}\index{\_\_imod\_\_() (object のメソッド)@\spxentry{\_\_imod\_\_()}\spxextra{object のメソッド}}\index{\_\_ipow\_\_() (object のメソッド)@\spxentry{\_\_ipow\_\_()}\spxextra{object のメソッド}}\index{\_\_ilshift\_\_() (object のメソッド)@\spxentry{\_\_ilshift\_\_()}\spxextra{object のメソッド}}\index{\_\_irshift\_\_() (object のメソッド)@\spxentry{\_\_irshift\_\_()}\spxextra{object のメソッド}}\index{\_\_iand\_\_() (object のメソッド)@\spxentry{\_\_iand\_\_()}\spxextra{object のメソッド}}\index{\_\_ixor\_\_() (object のメソッド)@\spxentry{\_\_ixor\_\_()}\spxextra{object のメソッド}}\index{\_\_ior\_\_() (object のメソッド)@\spxentry{\_\_ior\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__iadd__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_iadd\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__isub__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_isub\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__imul__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_imul\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__imatmul__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_imatmul\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__itruediv__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_itruediv\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__ifloordiv__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_ifloordiv\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__imod__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_imod\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__ipow__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_ipow\_\_}}}{\emph{self}, \emph{other}\sphinxoptional{, \emph{modulo}}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__ilshift__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_ilshift\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__irshift__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_irshift\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__iand__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_iand\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__ixor__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_ixor\_\_}}}{\emph{self}, \emph{other}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__ior__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_ior\_\_}}}{\emph{self}, \emph{other}}{} これらのメソッドを呼び出して累算算術代入 (\sphinxcode{\sphinxupquote{+=}}, \sphinxcode{\sphinxupquote{\sphinxhyphen{}=}}, \sphinxcode{\sphinxupquote{*=}}, \sphinxcode{\sphinxupquote{@=}}, \sphinxcode{\sphinxupquote{/=}}, \sphinxcode{\sphinxupquote{//=}}, \sphinxcode{\sphinxupquote{\%=}}, \sphinxcode{\sphinxupquote{**=}}, \sphinxcode{\sphinxupquote{<<=}}, \sphinxcode{\sphinxupquote{>>=}}, \sphinxcode{\sphinxupquote{\&=}}, \sphinxcode{\sphinxupquote{\textasciicircum{}=}}, \sphinxcode{\sphinxupquote{|=}}) を実装します。 これらのメソッドは演算をインプレースで (\sphinxstyleemphasis{self} を変更する) 行うよう試み、その結果 (その必要はありませんが \sphinxstyleemphasis{self} でも構いません) を返さなければなりません。 特定のメソッドが定義されていない場合、その累算算術演算は通常のメソッドにフォールバックされます。 例えば \sphinxstyleemphasis{x} が {\hyperref[\detokenize{reference/datamodel:object.__iadd__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_iadd\_\_()}}}}} メソッドを持つクラスのインスタンスである場合、\sphinxcode{\sphinxupquote{x += y}} は \sphinxcode{\sphinxupquote{x = x.\_\_iadd\_\_(y)}} と等価です。 そうでない場合、\sphinxcode{\sphinxupquote{x + y}} の評価と同様に \sphinxcode{\sphinxupquote{x.\_\_add\_\_(y)}} と \sphinxcode{\sphinxupquote{y.\_\_radd\_\_(x)}} が考慮されます。 特定の状況では、累算代入は予期しないエラーに終わるかもしれません (\DUrole{xref,std,std-ref}{faq\sphinxhyphen{}augmented\sphinxhyphen{}assignment\sphinxhyphen{}tuple\sphinxhyphen{}error} を参照してください) が、この挙動は実際はデータモデルの挙動の一部です。 \begin{sphinxadmonition}{note}{注釈:} Due to a bug in the dispatching mechanism for \sphinxcode{\sphinxupquote{**=}}, a class that defines {\hyperref[\detokenize{reference/datamodel:object.__ipow__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_ipow\_\_()}}}}} but returns \sphinxcode{\sphinxupquote{NotImplemented}} would fail to fall back to \sphinxcode{\sphinxupquote{x.\_\_pow\_\_(y)}} and \sphinxcode{\sphinxupquote{y.\_\_rpow\_\_(x)}}. This bug is fixed in Python 3.10. \end{sphinxadmonition} \end{fulllineitems} \index{\_\_neg\_\_() (object のメソッド)@\spxentry{\_\_neg\_\_()}\spxextra{object のメソッド}}\index{\_\_pos\_\_() (object のメソッド)@\spxentry{\_\_pos\_\_()}\spxextra{object のメソッド}}\index{\_\_abs\_\_() (object のメソッド)@\spxentry{\_\_abs\_\_()}\spxextra{object のメソッド}}\index{\_\_invert\_\_() (object のメソッド)@\spxentry{\_\_invert\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__neg__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_neg\_\_}}}{\emph{self}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__pos__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_pos\_\_}}}{\emph{self}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__abs__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_abs\_\_}}}{\emph{self}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__invert__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_invert\_\_}}}{\emph{self}}{}~ \index{組み込み関数@\spxentry{組み込み関数}!abs@\spxentry{abs}}\index{abs@\spxentry{abs}!組み込み関数@\spxentry{組み込み関数}}\ignorespaces 呼び出して単項算術演算 (\sphinxcode{\sphinxupquote{\sphinxhyphen{}}}, \sphinxcode{\sphinxupquote{+}}, \sphinxcode{\sphinxupquote{abs()}} および \sphinxcode{\sphinxupquote{\textasciitilde{}}}) を実装します。 \end{fulllineitems} \index{\_\_complex\_\_() (object のメソッド)@\spxentry{\_\_complex\_\_()}\spxextra{object のメソッド}}\index{\_\_int\_\_() (object のメソッド)@\spxentry{\_\_int\_\_()}\spxextra{object のメソッド}}\index{\_\_float\_\_() (object のメソッド)@\spxentry{\_\_float\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__complex__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_complex\_\_}}}{\emph{self}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__int__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_int\_\_}}}{\emph{self}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__float__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_float\_\_}}}{\emph{self}}{}~ \index{組み込み関数@\spxentry{組み込み関数}!complex@\spxentry{complex}}\index{complex@\spxentry{complex}!組み込み関数@\spxentry{組み込み関数}}\index{組み込み関数@\spxentry{組み込み関数}!int@\spxentry{int}}\index{int@\spxentry{int}!組み込み関数@\spxentry{組み込み関数}}\index{組み込み関数@\spxentry{組み込み関数}!float@\spxentry{float}}\index{float@\spxentry{float}!組み込み関数@\spxentry{組み込み関数}}\ignorespaces 組み込み関数の \sphinxcode{\sphinxupquote{complex()}}, \sphinxcode{\sphinxupquote{int()}}, \sphinxcode{\sphinxupquote{float()}} の実装から呼び出されます。 適切な型の値を返さなければなりません。 \end{fulllineitems} \index{\_\_index\_\_() (object のメソッド)@\spxentry{\_\_index\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__index__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_index\_\_}}}{\emph{self}}{} 呼び出して \sphinxcode{\sphinxupquote{operator.index()}} を実装します。 Python が数値オブジェクトを整数オブジェクトに損失なく変換する必要がある場合 (たとえばスライシングや、組み込みの \sphinxcode{\sphinxupquote{bin()}} 、 \sphinxcode{\sphinxupquote{hex()}} 、 \sphinxcode{\sphinxupquote{oct()}} 関数) は常に呼び出されます。 このメソッドがあるとその数値オブジェクトが整数型であることが示唆されます。 整数を返さなければなりません。 もし {\hyperref[\detokenize{reference/datamodel:object.__int__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_int\_\_()}}}}}, {\hyperref[\detokenize{reference/datamodel:object.__float__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_float\_\_()}}}}}, {\hyperref[\detokenize{reference/datamodel:object.__complex__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_complex\_\_()}}}}} が定義されていない場合、組み込み関数の \sphinxcode{\sphinxupquote{int()}}, \sphinxcode{\sphinxupquote{float()}}, \sphinxcode{\sphinxupquote{complex()}} は {\hyperref[\detokenize{reference/datamodel:object.__index__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_index\_\_()}}}}} にフォールバックします。 \end{fulllineitems} \index{\_\_round\_\_() (object のメソッド)@\spxentry{\_\_round\_\_()}\spxextra{object のメソッド}}\index{\_\_trunc\_\_() (object のメソッド)@\spxentry{\_\_trunc\_\_()}\spxextra{object のメソッド}}\index{\_\_floor\_\_() (object のメソッド)@\spxentry{\_\_floor\_\_()}\spxextra{object のメソッド}}\index{\_\_ceil\_\_() (object のメソッド)@\spxentry{\_\_ceil\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__round__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_round\_\_}}}{\emph{self}\sphinxoptional{, \emph{ndigits}}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__trunc__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_trunc\_\_}}}{\emph{self}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__floor__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_floor\_\_}}}{\emph{self}}{}\phantomsection\label{\detokenize{reference/datamodel:object.__ceil__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_ceil\_\_}}}{\emph{self}}{}~ \index{組み込み関数@\spxentry{組み込み関数}!round@\spxentry{round}}\index{round@\spxentry{round}!組み込み関数@\spxentry{組み込み関数}}\ignorespaces 組み込み関数の \sphinxcode{\sphinxupquote{round()}} と \sphinxcode{\sphinxupquote{math}} モジュール関数の \sphinxcode{\sphinxupquote{trunc()}}, \sphinxcode{\sphinxupquote{floor()}}, \sphinxcode{\sphinxupquote{ceil()}} の実装から呼び出されます。 \sphinxstyleemphasis{ndigits} が \sphinxcode{\sphinxupquote{\_\_round\_\_()}} に渡されない限りは、これらの全てのメソッドは \sphinxcode{\sphinxupquote{Integral}} (たいていは \sphinxcode{\sphinxupquote{int}}) に切り詰められたオブジェクトの値を返すべきです。 The built\sphinxhyphen{}in function \sphinxcode{\sphinxupquote{int()}} falls back to {\hyperref[\detokenize{reference/datamodel:object.__trunc__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_trunc\_\_()}}}}} if neither {\hyperref[\detokenize{reference/datamodel:object.__int__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_int\_\_()}}}}} nor {\hyperref[\detokenize{reference/datamodel:object.__index__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_index\_\_()}}}}} is defined. \end{fulllineitems} \subsection{with文とコンテキストマネージャ} \label{\detokenize{reference/datamodel:with-statement-context-managers}}\label{\detokenize{reference/datamodel:context-managers}} コンテキストマネージャ(\sphinxstyleemphasis{context manager}) とは、 {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}} 文の実行時にランタイムコンテキストを定義するオブジェクトです。コンテキストマネージャは、コードブロックを実行するために必要な入り口および出口の処理を扱います。コンテキストマネージャは通常、 \sphinxcode{\sphinxupquote{with}} 文( {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\DUrole{std,std-ref}{with 文}}}} の章を参照)により起動されますが、これらのメソッドを直接呼び出すことで起動することもできます。 \index{文@\spxentry{文}!with@\spxentry{with}}\index{with@\spxentry{with}!文@\spxentry{文}}\index{context manager@\spxentry{context manager}}\ignorespaces コンテキストマネージャの代表的な使い方としては、様々なグローバル情報の保存および更新、リソースのロックとアンロック、ファイルのオープンとクローズなどが挙げられます。 コンテキストマネージャについてのさらなる情報については、 \DUrole{xref,std,std-ref}{typecontextmanager} を参照してください。 \index{\_\_enter\_\_() (object のメソッド)@\spxentry{\_\_enter\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__enter__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_enter\_\_}}}{\emph{self}}{} コンテキストマネージャのの入り口で実行される処理です。 {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}} 文は、文の \sphinxcode{\sphinxupquote{as}} 節で規定された値を返すこのメソッドを呼び出します。 \end{fulllineitems} \index{\_\_exit\_\_() (object のメソッド)@\spxentry{\_\_exit\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__exit__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_exit\_\_}}}{\emph{self}, \emph{exc\_type}, \emph{exc\_value}, \emph{traceback}}{} コンテキストマネージャの出口で実行される処理です。パラメータは、コンテキストが終了した原因となった例外について説明しています。コンテキストが例外を送出せず終了した場合は、全ての引き数に \sphinxcode{\sphinxupquote{None}} が設定されます。 もし、例外が送出され、かつメソッドが例外を抑制したい場合(すなわち、例外が伝播されるのを防ぎたい場合)、このメソッドは True を返す必要があります。そうでなければ、このメソッドの終了後、例外は通常通り伝播することになります。 {\hyperref[\detokenize{reference/datamodel:object.__exit__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_exit\_\_()}}}}} メソッドは受け取った例外を再度送出すべきではありません。これは、呼び出し側の責任でおこなってください。 \end{fulllineitems} \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 343@\spxentry{PEP 343}}\sphinxhref{https://www.python.org/dev/peps/pep-0343}{\sphinxstylestrong{PEP 343}} \sphinxhyphen{} "with" ステートメント}] \leavevmode Python の {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}} 文の仕様、背景、および例が記載されています。 \end{description} \subsection{特殊メソッド検索} \label{\detokenize{reference/datamodel:special-method-lookup}}\label{\detokenize{reference/datamodel:special-lookup}} カスタムクラスでは、特殊メソッドの暗黙の呼び出しは、オブジェクトのインスタンス辞書ではなく、オブジェクトの型で定義されているときにのみ正しく動作することが保証されます。この動作のため、以下のコードは例外を送出します: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k}{class} \PYG{n+nc}{C}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{pass} \PYG{g+gp}{...} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{c} \PYG{o}{=} \PYG{n}{C}\PYG{p}{(}\PYG{p}{)} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{c}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}len\PYGZus{}\PYGZus{}} \PYG{o}{=} \PYG{k}{lambda}\PYG{p}{:} \PYG{l+m+mi}{5} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{len}\PYG{p}{(}\PYG{n}{c}\PYG{p}{)} \PYG{g+gt}{Traceback (most recent call last):} File \PYG{n+nb}{\PYGZdq{}\PYGZlt{}stdin\PYGZgt{}\PYGZdq{}}, line \PYG{l+m}{1}, in \PYG{n}{\PYGZlt{}module\PYGZgt{}} \PYG{g+gr}{TypeError}: \PYG{n}{object of type \PYGZsq{}C\PYGZsq{} has no len()} \end{sphinxVerbatim} The rationale behind this behaviour lies with a number of special methods such as {\hyperref[\detokenize{reference/datamodel:object.__hash__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_hash\_\_()}}}}} and {\hyperref[\detokenize{reference/datamodel:object.__repr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_repr\_\_()}}}}} that are implemented by all objects, including type objects. If the implicit lookup of these methods used the conventional lookup process, they would fail when invoked on the type object itself: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{l+m+mi}{1} \PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}hash\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{p}{)} \PYG{o}{==} \PYG{n+nb}{hash}\PYG{p}{(}\PYG{l+m+mi}{1}\PYG{p}{)} \PYG{g+go}{True} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{int}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}hash\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{p}{)} \PYG{o}{==} \PYG{n+nb}{hash}\PYG{p}{(}\PYG{n+nb}{int}\PYG{p}{)} \PYG{g+gt}{Traceback (most recent call last):} File \PYG{n+nb}{\PYGZdq{}\PYGZlt{}stdin\PYGZgt{}\PYGZdq{}}, line \PYG{l+m}{1}, in \PYG{n}{\PYGZlt{}module\PYGZgt{}} \PYG{g+gr}{TypeError}: \PYG{n}{descriptor \PYGZsq{}\PYGZus{}\PYGZus{}hash\PYGZus{}\PYGZus{}\PYGZsq{} of \PYGZsq{}int\PYGZsq{} object needs an argument} \end{sphinxVerbatim} クラスの非結合メソッドをこのようにして実行しようとすることは、'metaclass confusion' と呼ばれることもあり、特殊メソッドを検索するときはインスタンスをバイパスすることで回避されます: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{type}\PYG{p}{(}\PYG{l+m+mi}{1}\PYG{p}{)}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}hash\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{l+m+mi}{1}\PYG{p}{)} \PYG{o}{==} \PYG{n+nb}{hash}\PYG{p}{(}\PYG{l+m+mi}{1}\PYG{p}{)} \PYG{g+go}{True} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{type}\PYG{p}{(}\PYG{n+nb}{int}\PYG{p}{)}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}hash\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n+nb}{int}\PYG{p}{)} \PYG{o}{==} \PYG{n+nb}{hash}\PYG{p}{(}\PYG{n+nb}{int}\PYG{p}{)} \PYG{g+go}{True} \end{sphinxVerbatim} In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the {\hyperref[\detokenize{reference/datamodel:object.__getattribute__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getattribute\_\_()}}}}} method even of the object's metaclass: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k}{class} \PYG{n+nc}{Meta}\PYG{p}{(}\PYG{n+nb}{type}\PYG{p}{)}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{def} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}getattribute\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{o}{*}\PYG{n}{args}\PYG{p}{)}\PYG{p}{:} \PYG{g+gp}{... } \PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{Metaclass getattribute invoked}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} \PYG{g+gp}{... } \PYG{k}{return} \PYG{n+nb}{type}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}getattribute\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{o}{*}\PYG{n}{args}\PYG{p}{)} \PYG{g+gp}{...} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k}{class} \PYG{n+nc}{C}\PYG{p}{(}\PYG{n+nb}{object}\PYG{p}{,} \PYG{n}{metaclass}\PYG{o}{=}\PYG{n}{Meta}\PYG{p}{)}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{def} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}len\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n+nb+bp}{self}\PYG{p}{)}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{return} \PYG{l+m+mi}{10} \PYG{g+gp}{... } \PYG{k}{def} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}getattribute\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{o}{*}\PYG{n}{args}\PYG{p}{)}\PYG{p}{:} \PYG{g+gp}{... } \PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{Class getattribute invoked}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} \PYG{g+gp}{... } \PYG{k}{return} \PYG{n+nb}{object}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}getattribute\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{o}{*}\PYG{n}{args}\PYG{p}{)} \PYG{g+gp}{...} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{c} \PYG{o}{=} \PYG{n}{C}\PYG{p}{(}\PYG{p}{)} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{c}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}len\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{p}{)} \PYG{c+c1}{\PYGZsh{} Explicit lookup via instance} \PYG{g+go}{Class getattribute invoked} \PYG{g+go}{10} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{type}\PYG{p}{(}\PYG{n}{c}\PYG{p}{)}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}len\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n}{c}\PYG{p}{)} \PYG{c+c1}{\PYGZsh{} Explicit lookup via type} \PYG{g+go}{Metaclass getattribute invoked} \PYG{g+go}{10} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{len}\PYG{p}{(}\PYG{n}{c}\PYG{p}{)} \PYG{c+c1}{\PYGZsh{} Implicit lookup} \PYG{g+go}{10} \end{sphinxVerbatim} Bypassing the {\hyperref[\detokenize{reference/datamodel:object.__getattribute__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getattribute\_\_()}}}}} machinery in this fashion provides significant scope for speed optimisations within the interpreter, at the cost of some flexibility in the handling of special methods (the special method \sphinxstyleemphasis{must} be set on the class object itself in order to be consistently invoked by the interpreter). \index{coroutine@\spxentry{coroutine}}\ignorespaces \section{コルーチン} \label{\detokenize{reference/datamodel:coroutines}}\label{\detokenize{reference/datamodel:index-104}} \subsection{待機可能オブジェクト (Awaitable Object)} \label{\detokenize{reference/datamodel:awaitable-objects}} An {\hyperref[\detokenize{glossary:term-awaitable}]{\sphinxtermref{\DUrole{xref,std,std-term}{awaitable}}}} object generally implements an {\hyperref[\detokenize{reference/datamodel:object.__await__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_await\_\_()}}}}} method. {\hyperref[\detokenize{glossary:term-coroutine}]{\sphinxtermref{\DUrole{xref,std,std-term}{Coroutine objects}}}} returned from {\hyperref[\detokenize{reference/compound_stmts:async-def}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async def}}}}} functions are awaitable. \begin{sphinxadmonition}{note}{注釈:} The {\hyperref[\detokenize{glossary:term-generator-iterator}]{\sphinxtermref{\DUrole{xref,std,std-term}{generator iterator}}}} objects returned from generators decorated with \sphinxcode{\sphinxupquote{types.coroutine()}} or \sphinxcode{\sphinxupquote{asyncio.coroutine()}} are also awaitable, but they do not implement {\hyperref[\detokenize{reference/datamodel:object.__await__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_await\_\_()}}}}}. \end{sphinxadmonition} \index{\_\_await\_\_() (object のメソッド)@\spxentry{\_\_await\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__await__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_await\_\_}}}{\emph{self}}{} {\hyperref[\detokenize{glossary:term-iterator}]{\sphinxtermref{\DUrole{xref,std,std-term}{iterator}}}} を返さなければなりません。 このメソッドは {\hyperref[\detokenize{glossary:term-awaitable}]{\sphinxtermref{\DUrole{xref,std,std-term}{awaitable}}}} オブジェクトを実装するのに使われるべきです。 簡単のために、 \sphinxcode{\sphinxupquote{asyncio.Future}} にはこのメソッドが実装され、 {\hyperref[\detokenize{reference/expressions:await}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{await}}}}} 式と互換性を持つようになっています。 \end{fulllineitems} \DUrole{versionmodified,added}{バージョン 3.5 で追加.} \sphinxstrong{参考:} 待機可能オブジェクトについてより詳しくは \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 492@\spxentry{PEP 492}}\sphinxhref{https://www.python.org/dev/peps/pep-0492}{\sphinxstylestrong{PEP 492}} を参照してください。 \subsection{コルーチンオブジェクト} \label{\detokenize{reference/datamodel:coroutine-objects}}\label{\detokenize{reference/datamodel:id7}} {\hyperref[\detokenize{glossary:term-coroutine}]{\sphinxtermref{\DUrole{xref,std,std-term}{Coroutine objects}}}} are {\hyperref[\detokenize{glossary:term-awaitable}]{\sphinxtermref{\DUrole{xref,std,std-term}{awaitable}}}} objects. A coroutine's execution can be controlled by calling {\hyperref[\detokenize{reference/datamodel:object.__await__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_await\_\_()}}}}} and iterating over the result. When the coroutine has finished executing and returns, the iterator raises \sphinxcode{\sphinxupquote{StopIteration}}, and the exception's \sphinxcode{\sphinxupquote{value}} attribute holds the return value. If the coroutine raises an exception, it is propagated by the iterator. Coroutines should not directly raise unhandled \sphinxcode{\sphinxupquote{StopIteration}} exceptions. コルーチンには以下に挙げるメソッドもあり、これらはジェネレータのメソッドからの類似です ({\hyperref[\detokenize{reference/expressions:generator-methods}]{\sphinxcrossref{\DUrole{std,std-ref}{ジェネレータ\sphinxhyphen{}イテレータメソッド}}}} を参照してください)。 ただし、ジェネレータと違って、コルーチンは反復処理を直接はサポートしていません。 \DUrole{versionmodified,changed}{バージョン 3.5.2 で変更: }コルーチンで2回以上待機 (await) すると \sphinxcode{\sphinxupquote{RuntimeError}} となります。 \index{send() (coroutine のメソッド)@\spxentry{send()}\spxextra{coroutine のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:coroutine.send}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{coroutine.}}\sphinxbfcode{\sphinxupquote{send}}}{\emph{value}}{} Starts or resumes execution of the coroutine. If \sphinxstyleemphasis{value} is \sphinxcode{\sphinxupquote{None}}, this is equivalent to advancing the iterator returned by {\hyperref[\detokenize{reference/datamodel:object.__await__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_await\_\_()}}}}}. If \sphinxstyleemphasis{value} is not \sphinxcode{\sphinxupquote{None}}, this method delegates to the {\hyperref[\detokenize{reference/expressions:generator.send}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{send()}}}}} method of the iterator that caused the coroutine to suspend. The result (return value, \sphinxcode{\sphinxupquote{StopIteration}}, or other exception) is the same as when iterating over the {\hyperref[\detokenize{reference/datamodel:object.__await__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_await\_\_()}}}}} return value, described above. \end{fulllineitems} \index{throw() (coroutine のメソッド)@\spxentry{throw()}\spxextra{coroutine のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:coroutine.throw}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{coroutine.}}\sphinxbfcode{\sphinxupquote{throw}}}{\emph{value}}{}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{coroutine.}}\sphinxbfcode{\sphinxupquote{throw}}}{\emph{type}\sphinxoptional{, \emph{value}\sphinxoptional{, \emph{traceback}}}}{} Raises the specified exception in the coroutine. This method delegates to the {\hyperref[\detokenize{reference/expressions:generator.throw}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{throw()}}}}} method of the iterator that caused the coroutine to suspend, if it has such a method. Otherwise, the exception is raised at the suspension point. The result (return value, \sphinxcode{\sphinxupquote{StopIteration}}, or other exception) is the same as when iterating over the {\hyperref[\detokenize{reference/datamodel:object.__await__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_await\_\_()}}}}} return value, described above. If the exception is not caught in the coroutine, it propagates back to the caller. \end{fulllineitems} \index{close() (coroutine のメソッド)@\spxentry{close()}\spxextra{coroutine のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:coroutine.close}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{coroutine.}}\sphinxbfcode{\sphinxupquote{close}}}{}{} コルーチンが自分自身の後片付けをし終了します。 コルーチンが一時停止している場合は、コルーチンを一時停止させたイテレータに {\hyperref[\detokenize{reference/expressions:generator.close}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{close()}}}}} メソッドがあれば、まずはそれに処理を委任します。 そして一時停止した地点から \sphinxcode{\sphinxupquote{GeneratorExit}} が送出され、ただちにコルーチンが自分自身の後片付けを行います。 最後に、実行が開始されていなかった場合でも、コルーチンに実行が完了した印を付けます。 コルーチンオブジェクトが破棄されるときには、上記の手順を経て自動的に閉じられます。 \end{fulllineitems} \subsection{非同期イテレータ (Asynchronous Iterator)} \label{\detokenize{reference/datamodel:asynchronous-iterators}}\label{\detokenize{reference/datamodel:async-iterators}} \sphinxstyleemphasis{非同期イテレータ} の \sphinxcode{\sphinxupquote{\_\_anext\_\_}} メソッドからは非同期のコードが呼べます。 非同期イテレータは {\hyperref[\detokenize{reference/compound_stmts:async-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async for}}}}} 文の中で使えます。 \index{\_\_aiter\_\_() (object のメソッド)@\spxentry{\_\_aiter\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__aiter__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_aiter\_\_}}}{\emph{self}}{} \sphinxstyleemphasis{非同期イテレータ} オブジェクトを返さなくてはなりません。 \end{fulllineitems} \index{\_\_anext\_\_() (object のメソッド)@\spxentry{\_\_anext\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__anext__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_anext\_\_}}}{\emph{self}}{} イテレータの次の値を返す \sphinxstyleemphasis{待機可能オブジェクト} を返さなければなりません。 反復処理が終了したときには \sphinxcode{\sphinxupquote{StopAsyncIteration}} エラーを送出すべきです。 \end{fulllineitems} 非同期イテラブルオブジェクトの例: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{class} \PYG{n+nc}{Reader}\PYG{p}{:} \PYG{k}{async} \PYG{k}{def} \PYG{n+nf}{readline}\PYG{p}{(}\PYG{n+nb+bp}{self}\PYG{p}{)}\PYG{p}{:} \PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \PYG{k}{def} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}aiter\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n+nb+bp}{self}\PYG{p}{)}\PYG{p}{:} \PYG{k}{return} \PYG{n+nb+bp}{self} \PYG{k}{async} \PYG{k}{def} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}anext\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n+nb+bp}{self}\PYG{p}{)}\PYG{p}{:} \PYG{n}{val} \PYG{o}{=} \PYG{k}{await} \PYG{n+nb+bp}{self}\PYG{o}{.}\PYG{n}{readline}\PYG{p}{(}\PYG{p}{)} \PYG{k}{if} \PYG{n}{val} \PYG{o}{==} \PYG{l+s+sa}{b}\PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{:} \PYG{k}{raise} \PYG{n+ne}{StopAsyncIteration} \PYG{k}{return} \PYG{n}{val} \end{sphinxVerbatim} \DUrole{versionmodified,added}{バージョン 3.5 で追加.} \DUrole{versionmodified,changed}{バージョン 3.7 で変更: }Prior to Python 3.7, {\hyperref[\detokenize{reference/datamodel:object.__aiter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_aiter\_\_()}}}}} could return an \sphinxstyleemphasis{awaitable} that would resolve to an {\hyperref[\detokenize{glossary:term-asynchronous-iterator}]{\sphinxtermref{\DUrole{xref,std,std-term}{asynchronous iterator}}}}. Starting with Python 3.7, {\hyperref[\detokenize{reference/datamodel:object.__aiter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_aiter\_\_()}}}}} must return an asynchronous iterator object. Returning anything else will result in a \sphinxcode{\sphinxupquote{TypeError}} error. \subsection{非同期コンテキストマネージャ (Asynchronous Context Manager)} \label{\detokenize{reference/datamodel:asynchronous-context-managers}}\label{\detokenize{reference/datamodel:async-context-managers}} \sphinxstyleemphasis{非同期コンテキストマネージャ} は、 \sphinxcode{\sphinxupquote{\_\_aenter\_\_}} メソッドと \sphinxcode{\sphinxupquote{\_\_aexit\_\_}} メソッド内部で実行を一時停止できる \sphinxstyleemphasis{コンテキストマネージャ} です。 非同期コンテキストマネージャは {\hyperref[\detokenize{reference/compound_stmts:async-with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async with}}}}} 文の中で使えます。 \index{\_\_aenter\_\_() (object のメソッド)@\spxentry{\_\_aenter\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__aenter__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_aenter\_\_}}}{\emph{self}}{} 文法的にはこのメソッドは {\hyperref[\detokenize{reference/datamodel:object.__enter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_enter\_\_()}}}}} に似ていますが、 \sphinxstyleemphasis{待機可能オブジェクト} を返さなければならないところだけが異なります。 \end{fulllineitems} \index{\_\_aexit\_\_() (object のメソッド)@\spxentry{\_\_aexit\_\_()}\spxextra{object のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/datamodel:object.__aexit__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{object.}}\sphinxbfcode{\sphinxupquote{\_\_aexit\_\_}}}{\emph{self}, \emph{exc\_type}, \emph{exc\_value}, \emph{traceback}}{} 文法的にはこのメソッドは {\hyperref[\detokenize{reference/datamodel:object.__exit__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_exit\_\_()}}}}} に似ていますが、 \sphinxstyleemphasis{待機可能オブジェクト} を返さなければならないところだけが異なります。 \end{fulllineitems} 非同期コンテキストマネージャクラスの例: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{class} \PYG{n+nc}{AsyncContextManager}\PYG{p}{:} \PYG{k}{async} \PYG{k}{def} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}aenter\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n+nb+bp}{self}\PYG{p}{)}\PYG{p}{:} \PYG{k}{await} \PYG{n}{log}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{entering context}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{)} \PYG{k}{async} \PYG{k}{def} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}aexit\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n+nb+bp}{self}\PYG{p}{,} \PYG{n}{exc\PYGZus{}type}\PYG{p}{,} \PYG{n}{exc}\PYG{p}{,} \PYG{n}{tb}\PYG{p}{)}\PYG{p}{:} \PYG{k}{await} \PYG{n}{log}\PYG{p}{(}\PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{exiting context}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{)} \end{sphinxVerbatim} \DUrole{versionmodified,added}{バージョン 3.5 で追加.} \subsubsection*{脚注} \chapter{実行モデル} \label{\detokenize{reference/executionmodel:execution-model}}\label{\detokenize{reference/executionmodel:execmodel}}\label{\detokenize{reference/executionmodel::doc}} \index{execution model@\spxentry{execution model}}\index{code@\spxentry{code}!block@\spxentry{block}}\index{block@\spxentry{block}!code@\spxentry{code}}\ignorespaces \section{プログラムの構造} \label{\detokenize{reference/executionmodel:structure-of-a-program}}\label{\detokenize{reference/executionmodel:prog-structure}}\label{\detokenize{reference/executionmodel:index-0}} \index{block@\spxentry{block}}\ignorespaces Python プログラムはコードブロックから構成されます。 ブロック (\sphinxstyleemphasis{block}) は、一つのまとまりとして実行される Python プログラムテキストの断片です。 モジュール、関数本体、そしてクラス定義はブロックであり、対話的に入力された個々のコマンドもブロックです。 スクリプトファイル (インタープリタに標準入力として与えられたり、インタープリタにコマンドライン引数として与えられたファイル) もコードブロックです。 スクリプトコマンド (インタープリタのコマンドライン上で \sphinxcode{\sphinxupquote{\sphinxhyphen{}c}} オプションで指定されたコマンド) もコードブロックです。 引数 \sphinxcode{\sphinxupquote{\sphinxhyphen{}m}} を使用して、コマンドラインからトップレベルスクリプト(すなわちモジュール \sphinxcode{\sphinxupquote{\_\_main\_\_}} )として実行されるモジュールもまたコードブロックです。組み込み関数 \sphinxcode{\sphinxupquote{eval()}} や \sphinxcode{\sphinxupquote{exec()}} に渡された文字列引数もコードブロックです。 \index{execution@\spxentry{execution}!frame@\spxentry{frame}}\index{frame@\spxentry{frame}!execution@\spxentry{execution}}\ignorespaces コードブロックは、実行フレーム (\sphinxstyleemphasis{execution frame}) 上で実行されます。実行フレームには、 (デバッグに使われる) 管理情報が収められています。また、現在のコードブロックの実行が完了した際に、どのようにプログラムの実行を継続するかを決定しています。 \section{名前づけと束縛 (naming and binding)} \label{\detokenize{reference/executionmodel:naming-and-binding}}\label{\detokenize{reference/executionmodel:naming}} \index{namespace@\spxentry{namespace}}\index{scope@\spxentry{scope}}\ignorespaces \subsection{名前の束縛} \label{\detokenize{reference/executionmodel:binding-of-names}}\label{\detokenize{reference/executionmodel:bind-names}}\label{\detokenize{reference/executionmodel:index-3}} \index{name@\spxentry{name}}\index{binding@\spxentry{binding}!name@\spxentry{name}}\index{name@\spxentry{name}!binding@\spxentry{binding}}\ignorespaces \sphinxstyleemphasis{名前 (name)} は、オブジェクトを参照します。名前を導入するには、名前への束縛 (name binding) 操作を行います。 \index{from@\spxentry{from}!import statement@\spxentry{import statement}}\ignorespaces 以下の構造で、名前が束縛されます: 関数の仮引数 (formal parameter) 指定、 {\hyperref[\detokenize{reference/simple_stmts:import}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{import}}}}} 文、クラスや関数の定義 (定義を行ったブロックで、クラスや関数名を束縛します)、代入が行われるときの代入対象の識別子、 {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} ループのヘッダ、 {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}} 文や {\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}} 節の \sphinxcode{\sphinxupquote{as}} の後ろ。 "\sphinxcode{\sphinxupquote{from ... import *}}" 形式の \sphinxcode{\sphinxupquote{import}} 文は、 import されるモジュール内で定義されている、アンダースコアから始まるもの以外の全ての名前を束縛します。 この形式はモジュールレベルでしか使えません。 {\hyperref[\detokenize{reference/simple_stmts:del}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{del}}}}} 文で指定される対象は、({\hyperref[\detokenize{reference/simple_stmts:del}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{del}}}}} の意味付けは、実際は名前の解放 (unbind) ですが) 文の目的上、束縛済みのものとみなされます。 代入文や import 文はいずれも、クラスや関数定義、モジュールレベル (トップレベルのコードブロック) 内で起こります。 \index{free@\spxentry{free}!variable@\spxentry{variable}}\index{variable@\spxentry{variable}!free@\spxentry{free}}\ignorespaces ある名前がブロック内で束縛されているなら、 {\hyperref[\detokenize{reference/simple_stmts:nonlocal}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{nonlocal}}}}} や {\hyperref[\detokenize{reference/simple_stmts:global}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{global}}}}} として宣言されていない限り、それはそのブロックのローカル変数 (local variable) です。 ある名前がモジュールレベルで束縛されているなら、その名前はグローバル変数 (global variable) です。 (モジュールコードブロックの変数は、ローカル変数でも、グローバル変数でもあります。) ある変数があるコードブロック内で使われていて、そのブロックで定義はされていないなら、それは自由変数 (\sphinxstyleemphasis{free variable}) です。 プログラムテキスト中に名前が出現するたびに、その名前が使われている最も内側の関数ブロック中で作成された \sphinxstyleemphasis{束縛 (binding)} を使って名前の参照が行われます。 \subsection{名前解決} \label{\detokenize{reference/executionmodel:resolution-of-names}}\label{\detokenize{reference/executionmodel:resolve-names}} \index{scope@\spxentry{scope}}\ignorespaces スコープ (\sphinxstyleemphasis{scope}) は、ブロック内の名前の可視性を決めます。 ローカル変数があるブロック内で定義されている場合、変数のスコープはそのブロックを含みます。 関数ブロック内で名前の定義を行った場合、その中のブロックが名前に別の束縛を行わない限り、定義ブロック内の全てのブロックを含むようにスコープが拡張されます。 \index{environment@\spxentry{environment}}\ignorespaces ある名前がコードブロック内で使われると、その名前を最も近傍から囲うようなスコープ (最内スコープ: nearest enclosing scope) を使って束縛の解決を行います。こうしたスコープからなる、あるコードブロック内で参照できるスコープ全ての集合は、ブロックの環境(\sphinxstyleemphasis{environment})と呼ばれます。 \index{NameError (built\sphinxhyphen{}in exception)@\spxentry{NameError}\spxextra{built\sphinxhyphen{}in exception}}\index{UnboundLocalError@\spxentry{UnboundLocalError}}\ignorespaces 名前が全く見付からなかったときは、 \sphinxcode{\sphinxupquote{NameError}} 例外が送出されます。 現在のスコープが関数のもので、名前が使われる場所でローカル変数がまだ値に束縛されていない場合、 \sphinxcode{\sphinxupquote{UnboundLocalError}} 例外が送出されます。 \sphinxcode{\sphinxupquote{UnboundLocalError}} は \sphinxcode{\sphinxupquote{NameError}} の子クラスです。 ある名前がコードブロック内のどこかで束縛操作されていたら、そのブロック内で使われるその名前はすべて、現在のブロックへの参照として扱われます。このため、ある名前がそのブロック内で束縛される前に使われるとエラーにつながります。この規則は敏感です。Python には宣言がなく、コードブロックのどこでも名前束縛操作ができます。あるコードブロックにおけるローカル変数は、ブロックのテキスト全体から名前束縛操作を走査することで決定されます。 If the {\hyperref[\detokenize{reference/simple_stmts:global}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{global}}}}} statement occurs within a block, all uses of the names specified in the statement refer to the bindings of those names in the top\sphinxhyphen{}level namespace. Names are resolved in the top\sphinxhyphen{}level namespace by searching the global namespace, i.e. the namespace of the module containing the code block, and the builtins namespace, the namespace of the module \sphinxcode{\sphinxupquote{builtins}}. The global namespace is searched first. If the names are not found there, the builtins namespace is searched. The \sphinxcode{\sphinxupquote{global}} statement must precede all uses of the listed names. {\hyperref[\detokenize{reference/simple_stmts:global}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{global}}}}} 文は、同じブロックの束縛操作と同じスコープを持ちます。ある自由変数の最内スコープに global 文がある場合、その自由変数はグローバル変数とみなされます。 {\hyperref[\detokenize{reference/simple_stmts:nonlocal}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{nonlocal}}}}} 文によって、対応する名前が最内関数スコープでそれ以前に束縛された変数を参照するようになります。もし名前がどの最内関数スコープにも存在しなければ、コンパイル時に \sphinxcode{\sphinxupquote{SyntaxError}} が上げられます。 \index{モジュール@\spxentry{モジュール}!\_\_main\_\_@\spxentry{\_\_main\_\_}}\index{\_\_main\_\_@\spxentry{\_\_main\_\_}!モジュール@\spxentry{モジュール}}\ignorespaces あるモジュールの名前空間は、そのモジュールが最初に import された時に自動的に作成されます。スクリプトの主モジュール (main module) は常に \sphinxcode{\sphinxupquote{\_\_main\_\_}} と呼ばれます。 クラス定義ブロックと \sphinxcode{\sphinxupquote{exec()}} や \sphinxcode{\sphinxupquote{eval()}} に対する引数は、名前解決の文脈で特別です。クラス定義は、名前を使うことと定義することができる実行可能な文です。これらの参照は、名前解決のための通常のルールに従いますが、束縛されていないローカル変数がグローバルな名前空間から検索されるという例外があります。クラス定義の名前空間はクラスの属性辞書になります。クラス内で定義された名前のスコープは、クラスのブロックに限定されます; メソッドのコードブロックには拡張されません。 \sphinxhyphen{}\sphinxhyphen{} 内包表記やジェネレータ式も関数スコープを利用して実装されているので、スコープの拡張範囲外です。つまり、次のようなコードは失敗します: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{class} \PYG{n+nc}{A}\PYG{p}{:} \PYG{n}{a} \PYG{o}{=} \PYG{l+m+mi}{42} \PYG{n}{b} \PYG{o}{=} \PYG{n+nb}{list}\PYG{p}{(}\PYG{n}{a} \PYG{o}{+} \PYG{n}{i} \PYG{k}{for} \PYG{n}{i} \PYG{o+ow}{in} \PYG{n+nb}{range}\PYG{p}{(}\PYG{l+m+mi}{10}\PYG{p}{)}\PYG{p}{)} \end{sphinxVerbatim} \subsection{組み込みと制限付きの実行} \label{\detokenize{reference/executionmodel:builtins-and-restricted-execution}}\label{\detokenize{reference/executionmodel:restrict-exec}} \index{restricted@\spxentry{restricted}!execution@\spxentry{execution}}\index{execution@\spxentry{execution}!restricted@\spxentry{restricted}}\ignorespaces \sphinxstylestrong{CPython implementation detail:} ユーザは \sphinxcode{\sphinxupquote{\_\_builtins\_\_}} に触れるべきではありません; これは厳密に実装の詳細です。組み込みの名前空間の中の値をオーバーライドしたいユーザは、 \sphinxcode{\sphinxupquote{builtins}} モジュールを {\hyperref[\detokenize{reference/simple_stmts:import}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{import}}}}} して、その属性を適切に変更するべきです。 あるコードブロックの実行に関連する組み込み名前空間は、実際にはコードブロックのグローバル名前空間から名前 \sphinxcode{\sphinxupquote{\_\_builtins\_\_}} を検索することで見つかります; \sphinxcode{\sphinxupquote{\_\_builtins\_\_}} は辞書かモジュールでなければなりません (後者の場合はモジュールの辞書が使われます)。デフォルトでは、 \sphinxcode{\sphinxupquote{\_\_main\_\_}} モジュール中においては、 \sphinxcode{\sphinxupquote{\_\_builtins\_\_}} は組み込みモジュール \sphinxcode{\sphinxupquote{builtins}} です; それ以外の任意のモジュールにおいては、 \sphinxcode{\sphinxupquote{\_\_builtins\_\_}} は \sphinxcode{\sphinxupquote{builtins}} モジュール自身の辞書のエイリアスです。 \subsection{動的な機能とのやりとり} \label{\detokenize{reference/executionmodel:interaction-with-dynamic-features}}\label{\detokenize{reference/executionmodel:dynamic-features}} 自由変数の名前解決はコンパイル時でなく実行時に行われます。つまり、以下のコードは42を出力します: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{i} \PYG{o}{=} \PYG{l+m+mi}{10} \PYG{k}{def} \PYG{n+nf}{f}\PYG{p}{(}\PYG{p}{)}\PYG{p}{:} \PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{i}\PYG{p}{)} \PYG{n}{i} \PYG{o}{=} \PYG{l+m+mi}{42} \PYG{n}{f}\PYG{p}{(}\PYG{p}{)} \end{sphinxVerbatim} \sphinxcode{\sphinxupquote{eval()}} と \sphinxcode{\sphinxupquote{exec()}} 関数は、名前の解決に、現在の環境の全てを使えるわけではありません。名前は呼び出し側のローカルやグローバル名前空間で解決できます。自由変数は最内名前空間ではなく、グローバル名前空間から解決されます。 % \begin{footnote}[1]\sphinxAtStartFootnote この制限は、上記の操作によって実行されるコードが、モジュールをコンパイルしたときには利用できないために起こります。 % \end{footnote} \sphinxcode{\sphinxupquote{exec()}} と \sphinxcode{\sphinxupquote{eval()}} 関数にはオプションの引数があり、グローバルとローカル名前空間をオーバライドできます。名前空間が一つしか指定されなければ、両方の名前空間として使われます。 \section{例外} \label{\detokenize{reference/executionmodel:exceptions}}\label{\detokenize{reference/executionmodel:id2}} \index{exception@\spxentry{exception}}\ignorespaces \index{raise an exception@\spxentry{raise an exception}}\index{handle an exception@\spxentry{handle an exception}}\index{exception handler@\spxentry{exception handler}}\index{errors@\spxentry{errors}}\index{error handling@\spxentry{error handling}}\ignorespaces 例外とは、コードブロックの通常の制御フローを中断して、エラーやその他の例外的な状況を処理できるようにするための手段です。例外はエラーが検出された時点で \sphinxstyleemphasis{送出 (raise)} されます; 例外は、エラーが発生部の周辺のコードブロックか、エラーが発生したコードブロック直接または間接的に呼び出しているコードブロックで \sphinxstyleemphasis{処理 (handle)} することができます。 Python インタプリタは、ランタイムエラー (ゼロ除算など) が検出されると例外を送出します。Python プログラムから、 {\hyperref[\detokenize{reference/simple_stmts:raise}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{raise}}}}} 文を使って明示的に例外を送出することもできます。例外ハンドラ (exception handler) は、 {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} ... {\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}} 文で指定することができます。 {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} 文の {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節を使うとクリーンアップコード (cleanup code) を指定できます。このコードは例外は処理しませんが、先行するコードブロックで例外が起きても起きなくても実行されます。 \index{termination model@\spxentry{termination model}}\ignorespaces Python は、エラー処理に "プログラムの終了 (termination)" モデルを用いています: 例外ハンドラは、プログラムに何が発生したかを把握することができ、ハンドラの外側のレベルに処理を継続することはできますが、(問題のあったコード部分を最初から実行しなおすのでない限り) エラーの原因を修復したり、実行に失敗した操作をやり直すことはできません。 \index{SystemExit (built\sphinxhyphen{}in exception)@\spxentry{SystemExit}\spxextra{built\sphinxhyphen{}in exception}}\ignorespaces 例外が全く処理されないとき、インタプリタはプログラムの実行を終了させるか、対話メインループに処理を戻します。 どちらの場合も、例外が \sphinxcode{\sphinxupquote{SystemExit}} でなければ、スタックのトレースバックを出力します。 Exceptions are identified by class instances. The {\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}} clause is selected depending on the class of the instance: it must reference the class of the instance or a {\hyperref[\detokenize{glossary:term-abstract-base-class}]{\sphinxtermref{\DUrole{xref,std,std-term}{non\sphinxhyphen{}virtual base class}}}} thereof. The instance can be received by the handler and can carry additional information about the exceptional condition. \begin{sphinxadmonition}{note}{注釈:} 例外のメッセージは、Python API 仕様には含まれていません。メッセージの内容は、ある Python のバージョンと次のバージョンの間で警告なしに変更される可能性があるので、複数バージョンのインタプリタで動作するようなコードは、例外メッセージの内容に依存させるべきではありません。 \end{sphinxadmonition} {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} 文については、 {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\DUrole{std,std-ref}{try 文}}}} 節、 {\hyperref[\detokenize{reference/simple_stmts:raise}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{raise}}}}} 文については {\hyperref[\detokenize{reference/simple_stmts:raise}]{\sphinxcrossref{\DUrole{std,std-ref}{raise 文}}}} 節も参照してください。 \subsubsection*{脚注} \chapter{インポートシステム} \label{\detokenize{reference/import:the-import-system}}\label{\detokenize{reference/import:importsystem}}\label{\detokenize{reference/import::doc}} \index{import machinery@\spxentry{import machinery}}\ignorespaces ある 1 つの {\hyperref[\detokenize{glossary:term-module}]{\sphinxtermref{\DUrole{xref,std,std-term}{module}}}} にある Python コードから他のモジュールを {\hyperref[\detokenize{glossary:term-importing}]{\sphinxtermref{\DUrole{xref,std,std-term}{インポート}}}} することで、そこにあるコードへアクセスできるようになります。 {\hyperref[\detokenize{reference/simple_stmts:import}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{import}}}}} 文はインポート機構を動かす最も一般的な方法ですが、それが唯一の方法ではありません。 \sphinxcode{\sphinxupquote{importlib.import\_module()}} や組み込みの \sphinxcode{\sphinxupquote{\_\_import\_\_()}} といった関数を使っても、インポート機構を動かすことができます。 {\hyperref[\detokenize{reference/simple_stmts:import}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{import}}}}} 文は 2 つの処理を連続して行っています; ある名前のモジュールを探し、その検索結果をローカルスコープの名前に束縛します。 \sphinxcode{\sphinxupquote{import}} 文の検索処理は、適切な引数で \sphinxcode{\sphinxupquote{\_\_import\_\_()}} 関数を呼び出すこととして定義されています。 \sphinxcode{\sphinxupquote{\_\_import\_\_()}} の戻り値は \sphinxcode{\sphinxupquote{import}} 文の名前束縛処理の実行で使われます。名前束縛処理の厳密な詳細は \sphinxcode{\sphinxupquote{import}} 文を参照してください。 \sphinxcode{\sphinxupquote{\_\_import\_\_()}} を直接呼び出すとモジュールの検索のみが行われ、見つかった場合、モジュールの作成処理が行われます。親パッケージのインポートや (\sphinxcode{\sphinxupquote{sys.modules}} を含む) 様々なキャッシュの更新などの副作用は起きるかもしれませんが、 {\hyperref[\detokenize{reference/simple_stmts:import}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{import}}}}} 文のみが名前束縛処理を行います。 {\hyperref[\detokenize{reference/simple_stmts:import}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{import}}}}} 文が実行されるときには、標準の組み込み関数 \sphinxcode{\sphinxupquote{\_\_import\_\_()}} が呼ばれます。インポートシステムを呼び出すその他の (\sphinxcode{\sphinxupquote{importlib.import\_module()}} 関数のような) メカニズムは、\sphinxcode{\sphinxupquote{\_\_import\_\_()}} の呼び出しをバイパスして独自のインポート・セマンティクスを実装している可能性があります。 モジュールが初めてインポートされるとき、 Python はそのモジュールを検索し、見付かった場合、モジュールオブジェクトを作成し、初期化します % \begin{footnote}[1]\sphinxAtStartFootnote \sphinxcode{\sphinxupquote{types.ModuleType}} を参照してください。 % \end{footnote} 。その名前のモジュールが見付からなかった場合、 \sphinxcode{\sphinxupquote{ModuleNotFoundError}} が送出されます。 Python には、インポート機構が実行されたときに名前からモジュールを検索する様々な戦略が実装されています。これらの戦略は、これ以降の節で解説される様々なフックを使って、修正したり拡張したりできます。 \DUrole{versionmodified,changed}{バージョン 3.3 で変更: }インポートシステムが \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 302@\spxentry{PEP 302}}\sphinxhref{https://www.python.org/dev/peps/pep-0302}{\sphinxstylestrong{PEP 302}} の第 2 フェーズの完全な実装へ更新されました。もはや暗黙的なインポート機構はありません \sphinxhyphen{} インポート機構全体は \sphinxcode{\sphinxupquote{sys.meta\_path}} を通して公開されています。加えて、ネイティブの名前空間パッケージのサポートは実装されています (\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 420@\spxentry{PEP 420}}\sphinxhref{https://www.python.org/dev/peps/pep-0420}{\sphinxstylestrong{PEP 420}} を参照) 。 \section{\sphinxstyleliteralintitle{\sphinxupquote{importlib}}} \label{\detokenize{reference/import:importlib}} \sphinxcode{\sphinxupquote{importlib}} モジュールはインポート機構とやり取りするための便利な API を提供します。例えば \sphinxcode{\sphinxupquote{importlib.import\_module()}} は、インポート機構を実行するための組み込みの \sphinxcode{\sphinxupquote{\_\_import\_\_()}} よりもシンプルで推奨される API を提供します。より詳細なことは \sphinxcode{\sphinxupquote{importlib}} ライブラリのドキュメントを参照してください。 \section{パッケージ} \label{\detokenize{reference/import:packages}} \index{package@\spxentry{package}}\ignorespaces Python にはモジュールオブジェクトの種類は 1 種類しかなく、 Python 、 C 、それ以外のもののどれで実装されているかに関係なく、すべてのモジュールはこの種類になります。モジュールの組織化を助け、名前階層を提供するために、 Python には {\hyperref[\detokenize{glossary:term-package}]{\sphinxtermref{\DUrole{xref,std,std-term}{パッケージ}}}} という概念があります。 パッケージはファイルシステムのディレクトリ、モジュールはディレクトリにあるファイルと考えることができますが、パッケージやモジュールはファイルシステムから生まれる必要はないので、この比喩を額面通りに受け取ってはいけません。この文書の目的のために、ディレクトリとファイルという便利な比喩を使うことにします。ファイルシステムのディレクトリのように、パッケージは階層構造を成し、通常のモジュールだけでなく、サブパッケージを含むこともあります。 すべてのパッケージはモジュールですが、すべてのモジュールがパッケージとは限らないことを心に留めておくのが重要です。もしくは他の言い方をすると、パッケージは単なる特別な種類のモジュールであると言えます。特に、\sphinxcode{\sphinxupquote{\_\_path\_\_}} 属性を持つ任意のモジュールはパッケージと見なされます。 All modules have a name. Subpackage names are separated from their parent package name by a dot, akin to Python's standard attribute access syntax. Thus you might have a package called \sphinxcode{\sphinxupquote{email}}, which in turn has a subpackage called \sphinxcode{\sphinxupquote{email.mime}} and a module within that subpackage called \sphinxcode{\sphinxupquote{email.mime.text}}. \subsection{通常のパッケージ} \label{\detokenize{reference/import:regular-packages}} \index{package@\spxentry{package}!regular@\spxentry{regular}}\index{regular@\spxentry{regular}!package@\spxentry{package}}\ignorespaces Python では、 {\hyperref[\detokenize{glossary:term-regular-package}]{\sphinxtermref{\DUrole{xref,std,std-term}{通常のパッケージ}}}} と {\hyperref[\detokenize{glossary:term-namespace-package}]{\sphinxtermref{\DUrole{xref,std,std-term}{名前空間パッケージ}}}} の 2 種類のパッケージが定義されています。通常のパッケージは Python 3.2 以前から存在する伝統的なパッケージです。典型的な通常のパッケージは \sphinxcode{\sphinxupquote{\_\_init\_\_.py}} ファイルを含むディレクトリとして実装されます。通常のパッケージがインポートされたとき、この \sphinxcode{\sphinxupquote{\_\_init\_\_.py}} ファイルが暗黙的に実行され、それで定義しているオブジェクトがパッケージ名前空間にある名前に束縛されます。 \sphinxcode{\sphinxupquote{\_\_init\_\_.py}} ファイルは、他のモジュールに書ける Python コードと同じものを含むことができ、モジュールがインポートされたときに Python はモジュールに属性を追加したりします。 例えば、以下のようなファイルシステム配置は、3 つのサブパッケージを持つ最上位の \sphinxcode{\sphinxupquote{parent}} パッケージを定義します: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{parent}\PYG{o}{/} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}init\PYGZus{}\PYGZus{}}\PYG{o}{.}\PYG{n}{py} \PYG{n}{one}\PYG{o}{/} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}init\PYGZus{}\PYGZus{}}\PYG{o}{.}\PYG{n}{py} \PYG{n}{two}\PYG{o}{/} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}init\PYGZus{}\PYGZus{}}\PYG{o}{.}\PYG{n}{py} \PYG{n}{three}\PYG{o}{/} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}init\PYGZus{}\PYGZus{}}\PYG{o}{.}\PYG{n}{py} \end{sphinxVerbatim} \sphinxcode{\sphinxupquote{parent.one}} をインポートすると暗黙的に \sphinxcode{\sphinxupquote{parent/\_\_init\_\_.py}} と \sphinxcode{\sphinxupquote{parent/one/\_\_init\_\_.py}} が実行されます。その後に \sphinxcode{\sphinxupquote{parent.two}} もしくは \sphinxcode{\sphinxupquote{parent.three}} をインポートすると、それぞれ \sphinxcode{\sphinxupquote{parent/two/\_\_init\_\_.py}} や \sphinxcode{\sphinxupquote{parent/three/\_\_init\_\_.py}} が実行されます。 \subsection{名前空間パッケージ} \label{\detokenize{reference/import:namespace-packages}} \index{package@\spxentry{package}!namespace@\spxentry{namespace}}\index{namespace@\spxentry{namespace}!package@\spxentry{package}}\index{package@\spxentry{package}!portion@\spxentry{portion}}\index{portion@\spxentry{portion}!package@\spxentry{package}}\ignorespaces 名前空間パッケージは様々な {\hyperref[\detokenize{glossary:term-portion}]{\sphinxtermref{\DUrole{xref,std,std-term}{ポーション}}}} を寄せ集めたもので、それぞれのポーションはサブパッケージを親パッケージに提供します。ポーションはファイルシステムの別々の場所にあることもあります。ポーションは、 zip ファイルの中やネットワーク上や、それ以外のインポート時に Python が探すどこかの場所で見つかることもあります。名前空間パッケージはファイルシステム上のオブジェクトに対応することもあるし、そうでないこともあります; それらは実際の実体のない仮想モジュールです。 名前空間パッケージは、 \sphinxcode{\sphinxupquote{\_\_path\_\_}} 属性に普通のリストは使いません。その代わりに独自の iterable 型を使っていて、ポーションの親パッケージのパス (もしくは最上位パッケージのための \sphinxcode{\sphinxupquote{sys.path}}) が変わった場合、そのパッケージでの次のインポートの際に、新たに自動でパッケージポーションを検索します。 名前空間パッケージには \sphinxcode{\sphinxupquote{parent/\_\_init\_\_.py}} ファイルはありません。それどころか、異なるポーションがそれぞれ提供する複数の \sphinxcode{\sphinxupquote{parent}} ディレクトリがインポート検索の際に見つかることもあります。したがって \sphinxcode{\sphinxupquote{parent/one}} は物理的に \sphinxcode{\sphinxupquote{parent/two}} の隣りにあるとは限りません。その場合、そのパッケージかサブパッケージのうち 1 つがインポートされたとき、Python は最上位の \sphinxcode{\sphinxupquote{parent}} パッケージのための名前空間パッケージを作成します。 名前空間パッケージの仕様については \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 420@\spxentry{PEP 420}}\sphinxhref{https://www.python.org/dev/peps/pep-0420}{\sphinxstylestrong{PEP 420}} も参照してください。 \section{検索} \label{\detokenize{reference/import:searching}} 検索を始めるためには、 Python はインポートされるモジュール (もしくはパッケージですが、ここでの議論の目的においてはささいな違いです) の {\hyperref[\detokenize{glossary:term-qualified-name}]{\sphinxtermref{\DUrole{xref,std,std-term}{完全修飾}}}} 名を必要とします。この名前は、 {\hyperref[\detokenize{reference/simple_stmts:import}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{import}}}}} 文の様々な引数や \sphinxcode{\sphinxupquote{importlib.import\_module()}} および \sphinxcode{\sphinxupquote{\_\_import\_\_()}} 関数のパラメータから得られます。 この名前はインポート検索の様々なフェーズで使われ、これは例えば \sphinxcode{\sphinxupquote{foo.bar.baz}} のようなドットで区切られたサブモジュールへのパスだったりします。この場合、 Python は最初に \sphinxcode{\sphinxupquote{foo}} を、次に \sphinxcode{\sphinxupquote{foo.bar}} 、そして最後に \sphinxcode{\sphinxupquote{foo.bar.baz}} をインポートしようとします。中間のいずれかのインポートに失敗した場合は、 \sphinxcode{\sphinxupquote{ModuleNotFoundError}} が送出されます。 \subsection{モジュールキャッシュ} \label{\detokenize{reference/import:the-module-cache}} \index{sys.modules@\spxentry{sys.modules}}\ignorespaces インポート検索で最初に調べる場所は \sphinxcode{\sphinxupquote{sys.modules}} です。このマッピングは、中間のパスを含む、これまでにインポートされたすべてのモジュールのキャッシュを提供します。なので \sphinxcode{\sphinxupquote{foo.bar.baz}} がインポート済みの場合、 \sphinxcode{\sphinxupquote{sys.modules}} は \sphinxcode{\sphinxupquote{foo}} 、 \sphinxcode{\sphinxupquote{foo.bar}} 、 \sphinxcode{\sphinxupquote{foo.bar.baz}} のエントリーを含みます。それぞれのキーはその値として対応するモジュールオブジェクトを持ちます。 インポートではモジュール名は \sphinxcode{\sphinxupquote{sys.modules}} から探され、存在した場合は、対応する値がインポートされるべきモジュールであり、この処理は完了します。しかし値が \sphinxcode{\sphinxupquote{None}} だった場合、 \sphinxcode{\sphinxupquote{ModuleNotFoundError}} が送出されます。モジュール名が見付からなかった場合は、 Python はモジュールの検索を続けます。 \sphinxcode{\sphinxupquote{sys.modules}} は書き込み可能です。キーの削除は対応するモジュールを破壊しない (他のモジュールがそのモジュールへの参照を持っている) かもしれませんが、指定されたモジュールのキャッシュされたエントリーを無効にし、それが次にインポートされたとき Python にそのモジュールを改めて検索させることになります。キーを \sphinxcode{\sphinxupquote{None}} に対応付けることもできますが、次にそのモジュールがインポートされるときに \sphinxcode{\sphinxupquote{ModuleNotFoundError}} となってしまいます。 たとえモジュールオブジェクトへの参照を保持しておいて、 \sphinxcode{\sphinxupquote{sys.modules}} にキャッシュされたエントリーを無効にし、その指定したモジュールを再インポートしたとしても、 2 つのモジュールオブジェクトは同じでは \sphinxstyleemphasis{ない} ことに注意してください。それとは対照的に、 \sphinxcode{\sphinxupquote{importlib.reload()}} は \sphinxstyleemphasis{同じ} モジュールオブジェクトを再利用し、モジュールのコードを再実行することで単にモジュールの内容を再初期化するだけです。 \subsection{ファインダーとローダー} \label{\detokenize{reference/import:finders-and-loaders}}\label{\detokenize{reference/import:id2}} \index{finder@\spxentry{finder}}\index{loader@\spxentry{loader}}\index{module spec@\spxentry{module spec}}\ignorespaces \sphinxcode{\sphinxupquote{sys.modules}} に指定されたモジュールが見つからなかった場合は、 Python のインポートプロトコルが起動され、モジュールを見つけロードします。このプロトコルは 2 つの概念的なオブジェクト、 {\hyperref[\detokenize{glossary:term-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{ファインダー}}}} と {\hyperref[\detokenize{glossary:term-loader}]{\sphinxtermref{\DUrole{xref,std,std-term}{ローダー}}}} から成ります。ファインダーの仕事は、知っている戦略を使って指定されたモジュールを見つけられるかどうか判断することです。両方のインターフェースを実装しているオブジェクトは {\hyperref[\detokenize{glossary:term-importer}]{\sphinxtermref{\DUrole{xref,std,std-term}{インポーター}}}} と呼ばれます \sphinxhyphen{} インポーターは要求されたモジュールがロードできると分かったとき、自分自身を返します。 Python にはデフォルトのファインダーとインポーターがいくつかあります。 1 つ目のものは組み込みモジュールの見つけ方を知っていて、 2 つ目のものは凍結されたモジュール (訳注: freeze ツールで処理されたモジュールのこと。 \DUrole{xref,std,std-doc}{プログラミング FAQ} の「どうしたら Python スクリプトからスタンドアロンバイナリを作れますか?」の項目を参照) の見つけ方を知っています。 3 つ目のものは {\hyperref[\detokenize{glossary:term-import-path}]{\sphinxtermref{\DUrole{xref,std,std-term}{インポートパス}}}} からモジュールを探します。 {\hyperref[\detokenize{glossary:term-import-path}]{\sphinxtermref{\DUrole{xref,std,std-term}{インポートパス}}}} はファイルシステムのパスや zip ファイルの位置を示すリストです。このリストは、 URL で特定できるもののような、位置を示すことのできる任意のリソースの検索にまで拡張することもできます。 インポート機構は拡張可能なので、モジュール検索の範囲とスコープを拡張するために新しいファインダーを付け加えることができます。 ファインダーは実際にはモジュールをロードしません。指定されたモジュールが見つかった場合、ファインダーは \sphinxstyleemphasis{module spec} (モジュール仕様)、すなわちモジュールのインポート関連の情報をカプセル化したものを返します。モジュールのロード時にインポート機構はそれを利用します。 次の節では、インポート機構を拡張するための新しいファインダーやローダーの作成と登録を含め、ファインダーとローダーのプロトコルについてより詳しく解説します。 \DUrole{versionmodified,changed}{バージョン 3.4 で変更: }Python の以前のバージョンでは、ファインダーは直接 {\hyperref[\detokenize{glossary:term-loader}]{\sphinxtermref{\DUrole{xref,std,std-term}{ローダー}}}} を返していましたが、現在はローダーを \sphinxstyleemphasis{含む} モジュール仕様を返します。ローダーはインポート中はまだ使われていますが、責任は減りました。 \subsection{インポートフック} \label{\detokenize{reference/import:import-hooks}} \index{import hooks@\spxentry{import hooks}}\index{meta hooks@\spxentry{meta hooks}}\index{path hooks@\spxentry{path hooks}}\index{hooks@\spxentry{hooks}!import@\spxentry{import}}\index{import@\spxentry{import}!hooks@\spxentry{hooks}}\index{hooks@\spxentry{hooks}!meta@\spxentry{meta}}\index{meta@\spxentry{meta}!hooks@\spxentry{hooks}}\index{hooks@\spxentry{hooks}!path@\spxentry{path}}\index{path@\spxentry{path}!hooks@\spxentry{hooks}}\ignorespaces インポート機構は拡張可能なように設計されています; その主となる仕組みは \sphinxstyleemphasis{インポートフック} です。インポートフックには 2 種類あります: \sphinxstyleemphasis{メタフック} と \sphinxstyleemphasis{インポートパスフック} です。 メタフックはインポート処理の最初、 \sphinxcode{\sphinxupquote{sys.modules}} キャッシュの検索以外のインポート処理より前に呼び出されます。これにより、 \sphinxcode{\sphinxupquote{sys.path}} の処理や凍結されたモジュールや組み込みのモジュールでさえも、メタフックで上書きすることができます。メタフックは以下で解説するように、 \sphinxcode{\sphinxupquote{sys.meta\_path}} に新しいファインダーオブジェクトを追加することで登録されます。 インポートパスフックは、 \sphinxcode{\sphinxupquote{sys.path}} (もしくは \sphinxcode{\sphinxupquote{package.\_\_path\_\_}}) の処理の一部として、対応するパス要素を取り扱うところで呼び出されます。インポートパスフックは以下で解説するように、新しい呼び出し可能オブジェクトを \sphinxcode{\sphinxupquote{sys.path\_hooks}} に追加することで登録されます。 \subsection{メタパス} \label{\detokenize{reference/import:the-meta-path}} \index{sys.meta\_path@\spxentry{sys.meta\_path}}\index{finder@\spxentry{finder}!find\_spec@\spxentry{find\_spec}}\index{find\_spec@\spxentry{find\_spec}!finder@\spxentry{finder}}\ignorespaces 指定されたモジュールが \sphinxcode{\sphinxupquote{sys.modules}} に見つからなかったとき、 Python は次にメタパス・ファインダー・オブジェクトが格納されている \sphinxcode{\sphinxupquote{sys.meta\_path}} を検索します。指定されたモジュールを扱うことができるかどうかを調べるために、各ファインダーに問い合わせを行います。メタパス・ファインダーには、名前とインポートパスと (オプションの) ターゲットモジュールの 3 つの引数を取る \sphinxcode{\sphinxupquote{find\_spec()}} という名前のメソッドが実装されていなければいけません。メタパス・ファインダーでは、指定されたモジュールを扱えるかどうかを判定するための戦略は任意のものを使って構いません。 meta path finder が指定されたモジュールの扱い方を知っている場合は、ファインダは spec オブジェクトを返します。指定されたモジュールを扱えない場合は \sphinxcode{\sphinxupquote{None}} を返します。 \sphinxcode{\sphinxupquote{sys.meta\_path}} に対する処理が spec を返さずにリストの末尾に到達してしまった場合は、 \sphinxcode{\sphinxupquote{ModuleNotFoundError}} を送出します。その他の送出された例外はそのまま呼び出し元に伝播され、インポート処理を異常終了させます。 メタパス・ファインダーの \sphinxcode{\sphinxupquote{find\_spec()}} メソッドは 2 つまたは 3 つの引数を渡して呼び出します。1 つ目の引数はインポートされるモジュールの完全修飾名で、例えば \sphinxcode{\sphinxupquote{foo.bar.baz}} などです。2 つ目の引数はモジュールの検索で使われるパスです。最上位のモジュールでは 2 つ目の引数は \sphinxcode{\sphinxupquote{None}} にしますが、サブモジュールやサブパッケージでは 2 つ目の引数は親パッケージの \sphinxcode{\sphinxupquote{\_\_path\_\_}} 属性の値です。適切な \sphinxcode{\sphinxupquote{\_\_path\_\_}} 属性にアクセスできなかった場合は、 \sphinxcode{\sphinxupquote{ModuleNotFoundError}} が送出されます。3 つ目の引数は、あとでロードされるターゲットとなる既存のモジュールオブジェクトです。インポートシステムはリロードの間だけターゲットモジュール をセットします。 メタパスは、1 回のインポート要求で複数回走査される可能性があります。例えば、関係するモジュールがどれもまだキャッシュされていないとしたときに \sphinxcode{\sphinxupquote{foo.bar.baz}} をインポートすると、最初は各メタパス・ファインダー (\sphinxcode{\sphinxupquote{mpf}}) に対して \sphinxcode{\sphinxupquote{mpf.find\_spec("foo", None, None)}} を呼び出して、最上位のインポート処理を行います。\sphinxcode{\sphinxupquote{foo}} がインポートされた後に、\sphinxcode{\sphinxupquote{mpf.find\_spec("foo.bar", foo.\_\_path\_\_, None)}} を呼び出していく 2 回目のメタパスの走査が行われ、\sphinxcode{\sphinxupquote{foo.bar}} がインポートされます。\sphinxcode{\sphinxupquote{foo.bar}} のインポートまで行われたら、最後の走査で \sphinxcode{\sphinxupquote{mpf.find\_spec("foo.bar.baz", foo.bar.\_\_path\_\_, None)}} を呼び出していきます。 あるメタパス・ファインダーは最上位のインポートのみサポートしています。これらのインポーターは、2 つ目の引数に \sphinxcode{\sphinxupquote{None}} 以外のものが渡されたとき、常に \sphinxcode{\sphinxupquote{None}} を返します。 Python のデフォルトの \sphinxcode{\sphinxupquote{sys.meta\_path}} は 3 つのパスファインダーを持っています。組み込みモジュールのインポートの方法を知っているもの、凍結されたモジュールのインポートの方法を知っているもの、 {\hyperref[\detokenize{glossary:term-import-path}]{\sphinxtermref{\DUrole{xref,std,std-term}{インポートパス}}}} からのモジュールのインポートの方法を知っているもの (つまり {\hyperref[\detokenize{glossary:term-path-based-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスベース・ファインダー}}}}) があります。 \DUrole{versionmodified,changed}{バージョン 3.4 で変更: }メタパス・ファインダーの \sphinxcode{\sphinxupquote{find\_module()}} メソッドは \sphinxcode{\sphinxupquote{find\_spec()}} に置き換えられました。 \sphinxcode{\sphinxupquote{find\_module()}} メソッドは非推奨 (deprecated) です。前者のメソッドは今でも変更なしに動きますが、インポート機構はファインダーが \sphinxcode{\sphinxupquote{find\_spec()}} を実装していない場合にのみそれを試します。 \section{ロード} \label{\detokenize{reference/import:loading}} モジュール仕様が見つかった場合、インポート機構はモジュールをロードする時にそれ (およびそれに含まれるローダー) を使います。これは、インポートのロード部分で起こることの近似です: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{module} \PYG{o}{=} \PYG{k+kc}{None} \PYG{k}{if} \PYG{n}{spec}\PYG{o}{.}\PYG{n}{loader} \PYG{o+ow}{is} \PYG{o+ow}{not} \PYG{k+kc}{None} \PYG{o+ow}{and} \PYG{n+nb}{hasattr}\PYG{p}{(}\PYG{n}{spec}\PYG{o}{.}\PYG{n}{loader}\PYG{p}{,} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{create\PYGZus{}module}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{)}\PYG{p}{:} \PYG{c+c1}{\PYGZsh{} It is assumed \PYGZsq{}exec\PYGZus{}module\PYGZsq{} will also be defined on the loader.} \PYG{n}{module} \PYG{o}{=} \PYG{n}{spec}\PYG{o}{.}\PYG{n}{loader}\PYG{o}{.}\PYG{n}{create\PYGZus{}module}\PYG{p}{(}\PYG{n}{spec}\PYG{p}{)} \PYG{k}{if} \PYG{n}{module} \PYG{o+ow}{is} \PYG{k+kc}{None}\PYG{p}{:} \PYG{n}{module} \PYG{o}{=} \PYG{n}{ModuleType}\PYG{p}{(}\PYG{n}{spec}\PYG{o}{.}\PYG{n}{name}\PYG{p}{)} \PYG{c+c1}{\PYGZsh{} The import\PYGZhy{}related module attributes get set here:} \PYG{n}{\PYGZus{}init\PYGZus{}module\PYGZus{}attrs}\PYG{p}{(}\PYG{n}{spec}\PYG{p}{,} \PYG{n}{module}\PYG{p}{)} \PYG{k}{if} \PYG{n}{spec}\PYG{o}{.}\PYG{n}{loader} \PYG{o+ow}{is} \PYG{k+kc}{None}\PYG{p}{:} \PYG{c+c1}{\PYGZsh{} unsupported} \PYG{k}{raise} \PYG{n+ne}{ImportError} \PYG{k}{if} \PYG{n}{spec}\PYG{o}{.}\PYG{n}{origin} \PYG{o+ow}{is} \PYG{k+kc}{None} \PYG{o+ow}{and} \PYG{n}{spec}\PYG{o}{.}\PYG{n}{submodule\PYGZus{}search\PYGZus{}locations} \PYG{o+ow}{is} \PYG{o+ow}{not} \PYG{k+kc}{None}\PYG{p}{:} \PYG{c+c1}{\PYGZsh{} namespace package} \PYG{n}{sys}\PYG{o}{.}\PYG{n}{modules}\PYG{p}{[}\PYG{n}{spec}\PYG{o}{.}\PYG{n}{name}\PYG{p}{]} \PYG{o}{=} \PYG{n}{module} \PYG{k}{elif} \PYG{o+ow}{not} \PYG{n+nb}{hasattr}\PYG{p}{(}\PYG{n}{spec}\PYG{o}{.}\PYG{n}{loader}\PYG{p}{,} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{exec\PYGZus{}module}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{)}\PYG{p}{:} \PYG{n}{module} \PYG{o}{=} \PYG{n}{spec}\PYG{o}{.}\PYG{n}{loader}\PYG{o}{.}\PYG{n}{load\PYGZus{}module}\PYG{p}{(}\PYG{n}{spec}\PYG{o}{.}\PYG{n}{name}\PYG{p}{)} \PYG{c+c1}{\PYGZsh{} Set \PYGZus{}\PYGZus{}loader\PYGZus{}\PYGZus{} and \PYGZus{}\PYGZus{}package\PYGZus{}\PYGZus{} if missing.} \PYG{k}{else}\PYG{p}{:} \PYG{n}{sys}\PYG{o}{.}\PYG{n}{modules}\PYG{p}{[}\PYG{n}{spec}\PYG{o}{.}\PYG{n}{name}\PYG{p}{]} \PYG{o}{=} \PYG{n}{module} \PYG{k}{try}\PYG{p}{:} \PYG{n}{spec}\PYG{o}{.}\PYG{n}{loader}\PYG{o}{.}\PYG{n}{exec\PYGZus{}module}\PYG{p}{(}\PYG{n}{module}\PYG{p}{)} \PYG{k}{except} \PYG{n+ne}{BaseException}\PYG{p}{:} \PYG{k}{try}\PYG{p}{:} \PYG{k}{del} \PYG{n}{sys}\PYG{o}{.}\PYG{n}{modules}\PYG{p}{[}\PYG{n}{spec}\PYG{o}{.}\PYG{n}{name}\PYG{p}{]} \PYG{k}{except} \PYG{n+ne}{KeyError}\PYG{p}{:} \PYG{k}{pass} \PYG{k}{raise} \PYG{k}{return} \PYG{n}{sys}\PYG{o}{.}\PYG{n}{modules}\PYG{p}{[}\PYG{n}{spec}\PYG{o}{.}\PYG{n}{name}\PYG{p}{]} \end{sphinxVerbatim} 以下の詳細に注意してください: \begin{itemize} \item {} \sphinxcode{\sphinxupquote{sys.modules}} の中に与えられた名前を持つ既存のモジュールオブジェクトがあるなら、 import は既にそれを返しているでしょう。 \item {} モジュールは、ローダーがモジュールコードを実行する前に \sphinxcode{\sphinxupquote{sys.modules}} に存在しています。 モジュールコードが (直接的または間接的に) 自分自身をインポートする可能性があるので、これは重要です; モジュールを \sphinxcode{\sphinxupquote{sys.modules}} に追加することで、最悪のケースでは無限の再帰が、そして最良のケースでは複数回のロードが、前もって防止されます。 \item {} ロード処理に失敗した場合、その失敗したモジュールは \sphinxhyphen{}\sphinxhyphen{} そして、そのモジュールだけが \sphinxhyphen{}\sphinxhyphen{} \sphinxcode{\sphinxupquote{sys.modules}} から取り除かれます。 \sphinxcode{\sphinxupquote{sys.modules}} キャッシュに既に含まれていたすべてのモジュールと、副作用としてロードに成功したすべてのモジュールは、常にキャッシュに残されます。これはリロードとは対照的で、リロードの場合は失敗したモジュールも \sphinxcode{\sphinxupquote{sys.modules}} に残されます。 \item {} {\hyperref[\detokenize{reference/import:import-mod-attrs}]{\sphinxcrossref{\DUrole{std,std-ref}{後のセクション}}}} で要約されるように、モジュールが作られてから実行されるまでの間にインポート機構はインポート関連のモジュール属性を設定します (上記擬似コード例の "\_init\_module\_attrs")。 \item {} モジュール実行はモジュールの名前空間が構築されるロードの重要な瞬間です。実行はローダーに完全に委任され、ローダーは何をどのように構築するかを決定することになります。 \item {} ロードの間に作成されて exec\_module() に渡されたモジュールは、インポートの終わりに返されるものとは異なるかもしれません % \begin{footnote}[2]\sphinxAtStartFootnote importlib の実装は、戻り値を直接使うことは避けています。その代わりに、モジュール名を調べて \sphinxcode{\sphinxupquote{sys.modules}} からモジュールオブジェクトを得ます。こうすることの間接的な効果は、インポートされたモジュールが \sphinxcode{\sphinxupquote{sys.modules}} にいる自分自身を置き換えることがあるということです。これは実装依存の動作であり、他の Python 実装では保証されていない動作です。 % \end{footnote}。 \end{itemize} \DUrole{versionmodified,changed}{バージョン 3.4 で変更: }インポートシステムはローダーの定型的な責任を引き継ぎました。これらは以前は \sphinxcode{\sphinxupquote{importlib.abc.Loader.load\_module()}} メソッドによって実行されました。 \subsection{ローダー} \label{\detokenize{reference/import:loaders}} モジュールローダーは、ロードの重要な機能であるモジュール実行機能を提供します。インポート機構は、実行しようとするモジュールオブジェクトを単一の引数として \sphinxcode{\sphinxupquote{importlib.abc.Loader.exec\_module()}} メソッドを呼び出します。 \sphinxcode{\sphinxupquote{importlib.abc.Loader.exec\_module()}} から返された任意の値は無視されます。 ローダーは以下の仕様を満たしていなければいけません: \begin{itemize} \item {} モジュールが (組み込みモジュールや動的に読み込まれる拡張モジュールではなくて) Python モジュールだった場合、ローダーはモジュールのグローバル名前空間 (\sphinxcode{\sphinxupquote{module.\_\_dict\_\_}}) で、モジュールのコードを実行すべきです。 \item {} \sphinxcode{\sphinxupquote{exec\_module()}} の呼び出し中に \sphinxcode{\sphinxupquote{ImportError}} 以外の例外が送出され、伝播されてきたとしても、モジュールをロードできない場合は \sphinxcode{\sphinxupquote{ImportError}} を送出すべきです。 \end{itemize} 多くの場合、ファインダーとローダーは同じオブジェクトで構いません; そのような場合では \sphinxcode{\sphinxupquote{find\_spec()}} メソッドは単に \sphinxcode{\sphinxupquote{self}} (訳注: オブジェクト自身) を返すだけです。 モジュールローダーは、 \sphinxcode{\sphinxupquote{create\_module()}} メソッドを実装することでロード中にモジュールオブジェクトを作成することを選択できます。このメソッドは、モジュール仕様を引数に取って、ロード中に使う新しいモジュールオブジェクトを返します。 \sphinxcode{\sphinxupquote{create\_module()}} はモジュールオブジェクトに属性を設定する必要はありません。もしこのメソッドが \sphinxcode{\sphinxupquote{None}} を返すなら、インポート機構は新しいモジュールを自身で作成します。 \DUrole{versionmodified,added}{バージョン 3.4 で追加: }ローダーの \sphinxcode{\sphinxupquote{create\_module()}} メソッド。 \DUrole{versionmodified,changed}{バージョン 3.4 で変更: }\sphinxcode{\sphinxupquote{load\_module()}} メソッドは \sphinxcode{\sphinxupquote{exec\_module()}} によって置き換えられ、インポート機構がロードのすべての定型的な処理を引き受けました。 既存のローダーとの互換性のため、もしローダーに \sphinxcode{\sphinxupquote{load\_module()}} メソッドが存在し、かつローダーが \sphinxcode{\sphinxupquote{exec\_module()}} を実装していなければ、インポート機構はローダーの \sphinxcode{\sphinxupquote{load\_module()}} メソッドを使います。しかし、 \sphinxcode{\sphinxupquote{load\_module()}} は deprecated であり、ローダーは代わりに \sphinxcode{\sphinxupquote{exec\_module()}} を実装すべきです。 \sphinxcode{\sphinxupquote{load\_module()}} メソッドは、モジュールを実行することに加えて上記で説明されたすべての定型的なロード機能を実施しなければなりません。同じ制約が適用されます。以下は追加の明確化です: \begin{itemize} \item {} \sphinxcode{\sphinxupquote{sys.modules}} に与えられた名前のモジュールが存在している場合、ローダーはその既存のモジュールを使わなければいけません。 (そうしないと \sphinxcode{\sphinxupquote{importlib.reload()}} は正しく動かないでしょう。) 指定されたモジュールが \sphinxcode{\sphinxupquote{sys.modules}} に存在しない場合、ローダーは新しいモジュールオブジェクトを作成し、 \sphinxcode{\sphinxupquote{sys.modules}} に追加しなければいけません。 \item {} 無限の再帰または複数回のロードを防止するために、ローダーがモジュールコードを実行する前にモジュールは \sphinxcode{\sphinxupquote{sys.modules}} に存在しなければなりません (\sphinxstyleemphasis{must})。 \item {} ロード処理に失敗した場合、ローダーは \sphinxcode{\sphinxupquote{sys.modules}} に追加したモジュールを取り除かなければいけませんが、それはロードに失敗したモジュール \sphinxstylestrong{のみ} を、そのモジュールがローダー自身に明示的にロードされた場合に限り、除去しなければなりません。 \end{itemize} \DUrole{versionmodified,changed}{バージョン 3.5 で変更: }\sphinxcode{\sphinxupquote{exec\_module()}} が定義されていて \sphinxcode{\sphinxupquote{create\_module()}} が定義されていない場合、 \sphinxcode{\sphinxupquote{DeprecationWarning}} が送出されるようになりました。 \DUrole{versionmodified,changed}{バージョン 3.6 で変更: }\sphinxcode{\sphinxupquote{exec\_module()}} が定義されていて \sphinxcode{\sphinxupquote{create\_module()}} が定義されていない場合、 \sphinxcode{\sphinxupquote{ImportError}} が送出されるようになりました。 \subsection{サブモジュール} \label{\detokenize{reference/import:submodules}} サブモジュールをロードするのにどのようなメカニズム (例えば、 \sphinxcode{\sphinxupquote{importlib}} API 、 \sphinxcode{\sphinxupquote{import}} または \sphinxcode{\sphinxupquote{import\sphinxhyphen{}from}} ステートメント、またはビルトイン関数の \sphinxcode{\sphinxupquote{\_\_import\_\_}}) が使われた場合でも、バインディングはサブモジュールオブジェクトを親モジュールの名前空間に配置します。例えば、もしパッケージ \sphinxcode{\sphinxupquote{spam}} がサブモジュール \sphinxcode{\sphinxupquote{foo}} を持っていた場合、 \sphinxcode{\sphinxupquote{spam.foo}} をインポートした後は \sphinxcode{\sphinxupquote{spam}} は値がサブモジュールに束縛された属性 \sphinxcode{\sphinxupquote{foo}} を持ちます。以下のディレクトリ構造を持っているとしましょう: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{spam}\PYG{o}{/} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}init\PYGZus{}\PYGZus{}}\PYG{o}{.}\PYG{n}{py} \PYG{n}{foo}\PYG{o}{.}\PYG{n}{py} \end{sphinxVerbatim} and \sphinxcode{\sphinxupquote{spam/\_\_init\_\_.py}} has the following line in it: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k+kn}{from} \PYG{n+nn}{.}\PYG{n+nn}{foo} \PYG{k+kn}{import} \PYG{n}{Foo} \end{sphinxVerbatim} then executing the following puts name bindings for \sphinxcode{\sphinxupquote{foo}} and \sphinxcode{\sphinxupquote{Foo}} in the \sphinxcode{\sphinxupquote{spam}} module: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k+kn}{import} \PYG{n+nn}{spam} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{spam}\PYG{o}{.}\PYG{n}{foo} \PYG{g+go}{\PYGZlt{}module \PYGZsq{}spam.foo\PYGZsq{} from \PYGZsq{}/tmp/imports/spam/foo.py\PYGZsq{}\PYGZgt{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{spam}\PYG{o}{.}\PYG{n}{Foo} \PYG{g+go}{\PYGZlt{}class \PYGZsq{}spam.foo.Foo\PYGZsq{}\PYGZgt{}} \end{sphinxVerbatim} Python の慣れ親しんだ名前束縛ルールからするとこれは驚きかもしれませんが、それは実際インポートシステムの基本的な機能です。不変に保たなければならないのは (上記のインポートの後などで) \sphinxcode{\sphinxupquote{sys.modules{[}'spam'{]}}} と \sphinxcode{\sphinxupquote{sys.modules{[}'spam.foo'{]}}} が存在する場合、後者が前者の \sphinxcode{\sphinxupquote{foo}} 属性として存在しなければならないということです。 \subsection{モジュール仕様} \label{\detokenize{reference/import:module-spec}} インポート機構は、インポートの間 (特にロードの前) に、個々のモジュールについてのさまざまな情報を扱います。情報のほとんどはすべてのモジュールで共通です。モジュール仕様の目的は、このインポート関連の情報をモジュールの単位でカプセル化することです。 インポートの際にモジュール仕様を使うことは、インポートシステムコンポーネント間、例えばモジュール仕様を作成するファインダーとそれを実行するローダーの間で状態を転送することを可能にします。最も重要なのは、それによってインポート機構がロードの定型的な作業を実行できるようになるということです。これに対して、モジュール仕様なしではローダがその責任を担っていました。 モジュール仕様は、モジュールオブジェクトの \sphinxcode{\sphinxupquote{\_\_spec\_\_}} 属性として公開されます。 モジュール仕様の内容の詳細については \sphinxcode{\sphinxupquote{ModuleSpec}} を参照してください。 \DUrole{versionmodified,added}{バージョン 3.4 で追加.} \subsection{インポート関連のモジュール属性} \label{\detokenize{reference/import:import-related-module-attributes}}\label{\detokenize{reference/import:import-mod-attrs}} インポート機構はロードの間、モジュールの仕様に基づいて、ローダーがモジュールが実行する前に以下の属性を書き込みます。 \index{\_\_name\_\_@\spxentry{\_\_name\_\_}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/import:__name__}}\pysigline{\sphinxbfcode{\sphinxupquote{\_\_name\_\_}}} \sphinxcode{\sphinxupquote{\_\_name\_\_}} 属性はモジュールの完全修飾名に設定されなければなりません。この名前を利用してインポートシステムでモジュールを一意に識別します。 \end{fulllineitems} \index{\_\_loader\_\_@\spxentry{\_\_loader\_\_}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/import:__loader__}}\pysigline{\sphinxbfcode{\sphinxupquote{\_\_loader\_\_}}} \sphinxcode{\sphinxupquote{\_\_loader\_\_}} 属性はモジュールロード時にインポート機構が使用したローダーオブジェクトに設定されなければなりません。この属性は普通は内省用のものですが、ローダー固有の追加機能のために用いることが出来ます。例えばローダー関連のデータの取得です。 \end{fulllineitems} \index{\_\_package\_\_@\spxentry{\_\_package\_\_}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/import:__package__}}\pysigline{\sphinxbfcode{\sphinxupquote{\_\_package\_\_}}} モジュールの \sphinxcode{\sphinxupquote{\_\_package\_\_}} 属性は設定されなければなりません。値は文字列でなければなりませんが、\sphinxcode{\sphinxupquote{\_\_name\_\_}} と同じ値でも構いません。モジュールがパッケージの場合、\sphinxcode{\sphinxupquote{\_\_package\_\_}} の値はその \sphinxcode{\sphinxupquote{\_\_name\_\_}} でなければなりません。モジュールがパッケージでない場合、トップレベルのモジュールでは \sphinxcode{\sphinxupquote{\_\_package\_\_}} は空の文字列、サブモジュールでは親のパッケージ名でなければなりません。詳細は \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 366@\spxentry{PEP 366}}\sphinxhref{https://www.python.org/dev/peps/pep-0366}{\sphinxstylestrong{PEP 366}} を参照してください。 この属性は \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 366@\spxentry{PEP 366}}\sphinxhref{https://www.python.org/dev/peps/pep-0366}{\sphinxstylestrong{PEP 366}} で定義されているように、メインモジュールからの明示的な相対インポートを計算するために、 \sphinxcode{\sphinxupquote{\_\_name\_\_}} の代わりに使用されます。 この属性は \sphinxcode{\sphinxupquote{\_\_spec\_\_.parent}} と同じ値を持つことを要求されます。 \DUrole{versionmodified,changed}{バージョン 3.6 で変更: }\sphinxcode{\sphinxupquote{\_\_package\_\_}} の値が \sphinxcode{\sphinxupquote{\_\_spec\_\_.parent}} と同じ値を持つことを要求されるようになりました。 \end{fulllineitems} \index{\_\_spec\_\_@\spxentry{\_\_spec\_\_}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/import:__spec__}}\pysigline{\sphinxbfcode{\sphinxupquote{\_\_spec\_\_}}} \sphinxcode{\sphinxupquote{\_\_spec\_\_}} 属性はモジュールロード時に使用されたモジュールスペックに設定されなければなりません。 \sphinxcode{\sphinxupquote{\_\_spec\_\_}} を適切に設定すると {\hyperref[\detokenize{reference/toplevel_components:programs}]{\sphinxcrossref{\DUrole{std,std-ref}{インタープリタ起動中に初期化されるモジュール}}}} にも同様に適用されます。 例外は \sphinxcode{\sphinxupquote{\_\_main\_\_}} で、\sphinxcode{\sphinxupquote{\_\_spec\_\_}} は {\hyperref[\detokenize{reference/import:main-spec}]{\sphinxcrossref{\DUrole{std,std-ref}{場合によっては None に設定されます}}}}。 \sphinxcode{\sphinxupquote{\_\_package\_\_}} が定義されていないときは \sphinxcode{\sphinxupquote{\_\_spec\_\_.parent}} がフォールバックとして使われます。 \DUrole{versionmodified,added}{バージョン 3.4 で追加.} \DUrole{versionmodified,changed}{バージョン 3.6 で変更: }\sphinxcode{\sphinxupquote{\_\_package\_\_}} が定義されていないときに \sphinxcode{\sphinxupquote{\_\_spec\_\_.parent}} がフォールバックとして使われるようになりました。 \end{fulllineitems} \index{\_\_path\_\_@\spxentry{\_\_path\_\_}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/import:__path__}}\pysigline{\sphinxbfcode{\sphinxupquote{\_\_path\_\_}}} モジュールが (通常のまたは名前空間) パッケージの場合、モジュールオブジェクトの \sphinxcode{\sphinxupquote{\_\_path\_\_}} 属性が設定される必要があります。値はイテレート可能でなければなりませんが、\sphinxcode{\sphinxupquote{\_\_path\_\_}} に意味がない場合は空でも構いません。\sphinxcode{\sphinxupquote{\_\_path\_\_}} が空でない場合、イテレート時に文字列を生成しなければなりません。\sphinxcode{\sphinxupquote{\_\_path\_\_}} のセマンティクスの詳細は {\hyperref[\detokenize{reference/import:package-path-rules}]{\sphinxcrossref{\DUrole{std,std-ref}{下記}}}} の通りです。 パッケージでないモジュールは \sphinxcode{\sphinxupquote{\_\_path\_\_}} 属性を持ってはいけません。 \end{fulllineitems} \index{\_\_file\_\_@\spxentry{\_\_file\_\_}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/import:__file__}}\pysigline{\sphinxbfcode{\sphinxupquote{\_\_file\_\_}}} \end{fulllineitems} \index{\_\_cached\_\_@\spxentry{\_\_cached\_\_}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/import:__cached__}}\pysigline{\sphinxbfcode{\sphinxupquote{\_\_cached\_\_}}} \sphinxcode{\sphinxupquote{\_\_file\_\_}} はオプションです。もし設定されるならば、この属性の値は文字列でなければなりません。もしそのような属性が意味を持たない場合 (例えばモジュールがデータベースからロードされた場合) インポートシステムは \sphinxcode{\sphinxupquote{\_\_file\_\_}} を未設定のままにしても構いません。 もし \sphinxcode{\sphinxupquote{\_\_file\_\_}} を設定するなら、 \sphinxcode{\sphinxupquote{\_\_cached\_\_}} 属性もコードのコンパイルされたバージョンのどれか (例えば、バイトコンパイルされたファイル) へのパスに設定することが適切でしょう。この属性を設定するにあたってファイルが存在する必要はありません; パスは、単にコンパイルされたファイルが存在するかもしれない場所を示しているだけです (\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 3147@\spxentry{PEP 3147}}\sphinxhref{https://www.python.org/dev/peps/pep-3147}{\sphinxstylestrong{PEP 3147}} を参照)。 \sphinxcode{\sphinxupquote{\_\_file\_\_}} が設定されない場合にも \sphinxcode{\sphinxupquote{\_\_cached\_\_}} を設定することは適切です。しかし、そのシナリオはかなり変則的です。究極的には、ローダーとは \sphinxcode{\sphinxupquote{\_\_file\_\_}} と \sphinxcode{\sphinxupquote{\_\_cached\_\_}} のどちらかまたは両方を利用するものです。したがって、もしローダーがキャッシュされたモジュールからロードする一方でファイルからはロードしないなら、その変則的なシナリオは適切でしょう。 \end{fulllineitems} \subsection{module.\_\_path\_\_} \label{\detokenize{reference/import:module-path}}\label{\detokenize{reference/import:package-path-rules}} 定義より、モジュールに \sphinxcode{\sphinxupquote{\_\_path\_\_}} 属性があれば、そのモジュールはパッケージとなります。 パッケージの \sphinxcode{\sphinxupquote{\_\_path\_\_}} 属性は、そのサブパッケージのインポート中に使われます。インポート機構の内部では、それは \sphinxcode{\sphinxupquote{sys.path}} とほとんど同じように機能します。つまり、インポート中にモジュールを探す場所のリストを提供します。しかし、一般的に \sphinxcode{\sphinxupquote{\_\_path\_\_}} は \sphinxcode{\sphinxupquote{sys.path}} よりも制約が強いです。 \sphinxcode{\sphinxupquote{\_\_path\_\_}} は文字列の iterable でなければいけませんが、空でも構いません。 \sphinxcode{\sphinxupquote{sys.path}} と同じ規則がパッケージの \sphinxcode{\sphinxupquote{\_\_path\_\_}} にも適用され、パッケージの \sphinxcode{\sphinxupquote{\_\_path\_\_}} を走査するときに (後で解説する) \sphinxcode{\sphinxupquote{sys.path\_hooks}} が考慮に入れられます。 パッケージの \sphinxcode{\sphinxupquote{\_\_init\_\_.py}} ファイルは、パッケージの \sphinxcode{\sphinxupquote{\_\_path\_\_}} 属性を設定もしくは変更することがあり、これが \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 420@\spxentry{PEP 420}}\sphinxhref{https://www.python.org/dev/peps/pep-0420}{\sphinxstylestrong{PEP 420}} 以前の名前空間パッケージの典型的な実装方法でした。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 420@\spxentry{PEP 420}}\sphinxhref{https://www.python.org/dev/peps/pep-0420}{\sphinxstylestrong{PEP 420}} の採択により、もはや名前空間パッケージは、 \sphinxcode{\sphinxupquote{\_\_path\_\_}} を操作するコードだけを含む \sphinxcode{\sphinxupquote{\_\_init\_\_.py}} ファイルを提供する必要がなくなりました;インポート機構は、名前空間パッケージに対し自動的に適切な \sphinxcode{\sphinxupquote{\_\_path\_\_}} をセットします。 \subsection{モジュールの repr} \label{\detokenize{reference/import:module-reprs}} デフォルトでは、すべてのモジュールは利用可能な repr を持っています。ただしこれは、これまでに説明した属性の設定内容に依存しており、モジュール仕様によってモジュールオブジェクトの repr をより明示的に制御することができます。 もしモジュールが仕様 (\sphinxcode{\sphinxupquote{\_\_spec\_\_}}) を持っていれば、インポート機構はそこから repr を生成しようとします。もしそれが失敗するか、または仕様が存在しなければ、インポートシステムはモジュールで入手可能なあらゆる情報を使ってデフォルトの repr を構築します。それは \sphinxcode{\sphinxupquote{module.\_\_name\_\_}}, \sphinxcode{\sphinxupquote{module.\_\_file\_\_}}, \sphinxcode{\sphinxupquote{module.\_\_loader\_\_}} を (足りない情報についてはデフォルト値を使って補いながら) repr への入力として使おうと試みます。 これが使われている正確な規則です: \begin{itemize} \item {} モジュールが \sphinxcode{\sphinxupquote{\_\_spec\_\_}} 属性を持っていれば、仕様に含まれる情報が repr を生成するために使われます。 "name", "loader", "origin", "has\_location" 属性が参照されます。 \item {} モジュールに \sphinxcode{\sphinxupquote{\_\_file\_\_}} 属性がある場合は、モジュールの repr の一部として使われます。 \item {} モジュールに \sphinxcode{\sphinxupquote{\_\_file\_\_}} はないが \sphinxcode{\sphinxupquote{\_\_loader\_\_}} があり、その値が \sphinxcode{\sphinxupquote{None}} ではない場合は、ローダーの repr がモジュールの repr の一部として使われます。 \item {} そうでなければ、単にモジュールの \sphinxcode{\sphinxupquote{\_\_name\_\_}} を repr の中で使います。 \end{itemize} \DUrole{versionmodified,changed}{バージョン 3.4 で変更: }\sphinxcode{\sphinxupquote{loader.module\_repr()}} の使用は非推奨 (deprecated) です。インポート機構によりモジュール仕様がモジュール repr を生成するために使用されるようになりました。 Python 3.3 との後方互換性のために、ローダーの \sphinxcode{\sphinxupquote{module\_repr()}} メソッドが定義されていたら、モジュール repr を生成するために上記のいずれかのアプローチを試す前にそのメソッドが呼ばれます。ただし、このメソッドは deprecated です。 \subsection{キャッシュされたバイトコードの無効化} \label{\detokenize{reference/import:cached-bytecode-invalidation}}\label{\detokenize{reference/import:pyc-invalidation}} Before Python loads cached bytecode from a \sphinxcode{\sphinxupquote{.pyc}} file, it checks whether the cache is up\sphinxhyphen{}to\sphinxhyphen{}date with the source \sphinxcode{\sphinxupquote{.py}} file. By default, Python does this by storing the source's last\sphinxhyphen{}modified timestamp and size in the cache file when writing it. At runtime, the import system then validates the cache file by checking the stored metadata in the cache file against the source's metadata. Python also supports "hash\sphinxhyphen{}based" cache files, which store a hash of the source file's contents rather than its metadata. There are two variants of hash\sphinxhyphen{}based \sphinxcode{\sphinxupquote{.pyc}} files: checked and unchecked. For checked hash\sphinxhyphen{}based \sphinxcode{\sphinxupquote{.pyc}} files, Python validates the cache file by hashing the source file and comparing the resulting hash with the hash in the cache file. If a checked hash\sphinxhyphen{}based cache file is found to be invalid, Python regenerates it and writes a new checked hash\sphinxhyphen{}based cache file. For unchecked hash\sphinxhyphen{}based \sphinxcode{\sphinxupquote{.pyc}} files, Python simply assumes the cache file is valid if it exists. Hash\sphinxhyphen{}based \sphinxcode{\sphinxupquote{.pyc}} files validation behavior may be overridden with the \sphinxcode{\sphinxupquote{\sphinxhyphen{}\sphinxhyphen{}check\sphinxhyphen{}hash\sphinxhyphen{}based\sphinxhyphen{}pycs}} flag. \DUrole{versionmodified,changed}{バージョン 3.7 で変更: }Added hash\sphinxhyphen{}based \sphinxcode{\sphinxupquote{.pyc}} files. Previously, Python only supported timestamp\sphinxhyphen{}based invalidation of bytecode caches. \section{パスベース・ファインダー} \label{\detokenize{reference/import:the-path-based-finder}} \index{path based finder@\spxentry{path based finder}}\ignorespaces 上で触れた通り、 Python にはいくつかのデフォルトのメタパス・ファインダーが備わっています。そのうちの 1 つは {\hyperref[\detokenize{glossary:term-path-based-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスベース・ファインダー}}}} (\sphinxcode{\sphinxupquote{PathFinder}}) と呼ばれ、 {\hyperref[\detokenize{glossary:term-path-entry}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスエントリ}}}} のリストである {\hyperref[\detokenize{glossary:term-import-path}]{\sphinxtermref{\DUrole{xref,std,std-term}{インポートパス}}}} を検索します。それぞれのパスエントリは、モジュールを探す場所を指しています。 パスベース・ファインダー自体は何かのインポート方法を知っているわけではありません。その代わりに、個々のパスエントリを走査し、それぞれに特定の種類のパスの扱いを知っているパスエントリ・ファインダーを関連付けます。 デフォルトのパスエントリ・ファインダーは、ファイルシステム上のモジュールを見つけるためのすべてのセマンティクスを実装しています。それは Python ソースコード (\sphinxcode{\sphinxupquote{.py}} ファイル) 、Python バイトコード (\sphinxcode{\sphinxupquote{.pyc}} ファイル) 、共有ライブラリ (例えば \sphinxcode{\sphinxupquote{.so}} ファイル) などの特別なファイルタイプを処理します。標準ライブラリの \sphinxcode{\sphinxupquote{zipimport}} モジュールによってサポートされる場合は、デフォルトのパスエントリ・ファインダーは (共有ライブラリ以外の) すべてのファイルタイプの zip ファイルからのロードも扱います。 パスエントリはファイルシステム上の場所に限定される必要はありません。URL やデータベースクエリやその他文字列で指定できる場所を参照することも可能です。 パスベース・ファインダーにはフックやプロトコルを追加することができ、それによって検索可能なパスエントリの種類を拡張し、カスタマイズすることができます。例えば、ネットワーク上の URL をパスエントリとしてサポートしたい場合、 web 上のモジュールを見つけるために HTTP の取り扱い方を実装したフックを書くことができます。この (呼び出し可能オブジェクトである) フックは、下で解説するプロトコルをサポートする {\hyperref[\detokenize{glossary:term-path-entry-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスエントリ・ファインダー}}}} を返します。このプロトコルは web からモジュールのローダーを取得するのに使われます。 警告の言葉: この節と前の節の両方で \sphinxstyleemphasis{ファインダー} という言葉が、 {\hyperref[\detokenize{glossary:term-meta-path-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{メタパス・ファインダー}}}} と {\hyperref[\detokenize{glossary:term-path-entry-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスエントリ・ファインダー}}}} という用語で区別されて使われています。これら 2 種類のファインダーは非常に似ており、似たプロトコルをサポートし、インポート処理で同じように機能しますが、微妙に異なっているのを心に留めておくのは重要です。特に、メタパス・ファインダーはインポート処理の開始時、 \sphinxcode{\sphinxupquote{sys.meta\_path}} の走査が動くときに動作します。 それとは対照的に、パスエントリ・ファインダーはある意味でパスベース・ファインダーの実装詳細であり、実際 \sphinxcode{\sphinxupquote{sys.meta\_path}} からパスベース・ファインダーが取り除かれた場合、パスエントリ・ファインダーの実装は何も実行されないでしょう。 \subsection{パスエントリ・ファインダー} \label{\detokenize{reference/import:path-entry-finders}} \index{sys.path@\spxentry{sys.path}}\index{sys.path\_hooks@\spxentry{sys.path\_hooks}}\index{sys.path\_importer\_cache@\spxentry{sys.path\_importer\_cache}}\index{PYTHONPATH@\spxentry{PYTHONPATH}}\ignorespaces {\hyperref[\detokenize{glossary:term-path-based-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスベース・ファインダー}}}} には、文字列 {\hyperref[\detokenize{glossary:term-path-entry}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスエントリ}}}} で指定された場所の Python モジュールや Python パッケージを見つけ、ロードする責任があります。ほとんどのパスエントリはファイルシステム上の場所を指定していますが、そこに制限される必要はありません。 メタパス・ファインダーとして、 {\hyperref[\detokenize{glossary:term-path-based-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスベース・ファインダー}}}} には前に解説した \sphinxcode{\sphinxupquote{find\_spec()}} プロトコルが実装されていますが、これに加えて {\hyperref[\detokenize{glossary:term-import-path}]{\sphinxtermref{\DUrole{xref,std,std-term}{インポートパス}}}} からモジュールを見つけ、ロードする方法をカスタマイズするために使えるフックを提供しています。 {\hyperref[\detokenize{glossary:term-path-based-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスベース・ファインダー}}}} は \sphinxcode{\sphinxupquote{sys.path}} 、 \sphinxcode{\sphinxupquote{sys.path\_hooks}} 、 \sphinxcode{\sphinxupquote{sys.path\_importer\_cache}} という 3 つの変数を使います。さらにパッケージオブジェクトの \sphinxcode{\sphinxupquote{\_\_path\_\_}} 属性も使います。これらによって、インポート処理をカスタマイズする方法が提供されます。 \sphinxcode{\sphinxupquote{sys.path}} には、モジュールとパッケージを探す場所文字列の一覧があります。これは \sphinxcode{\sphinxupquote{PYTHONPATH}} 環境変数とその他様々なインストール方法や実装に依存するデフォルト値で初期化されます。 \sphinxcode{\sphinxupquote{sys.path}} 内の要素は、ファイルシステム上のディレクトリや zip ファイルやその他モジュールを探すべき "場所" となりうるもの (\sphinxcode{\sphinxupquote{site}} モジュールを参照) を指すことができます。文字列およびバイト列のみを \sphinxcode{\sphinxupquote{sys.path}} に入れるべきです; 他のデータ型は無視されます。バイト列の要素のエンコーディングは、各 {\hyperref[\detokenize{glossary:term-path-entry-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスエントリ・ファインダー}}}} によって判別されます。 {\hyperref[\detokenize{glossary:term-path-based-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスベース・ファインダー}}}} は {\hyperref[\detokenize{glossary:term-meta-path-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{メタパス・ファインダー}}}} なので、インポート機構は、前で解説したパスベース・ファインダーの \sphinxcode{\sphinxupquote{find\_spec()}} メソッドを呼び出すことで {\hyperref[\detokenize{glossary:term-import-path}]{\sphinxtermref{\DUrole{xref,std,std-term}{インポートパス}}}} の検索を始めます。 \sphinxcode{\sphinxupquote{path}} 引数が \sphinxcode{\sphinxupquote{find\_spec()}} に渡されたときは、それは走査するパス文字列のリスト \sphinxhyphen{} 典型的にはそのパッケージの中でインポートしているパッケージの \sphinxcode{\sphinxupquote{\_\_path\_\_}} 属性になります。 \sphinxcode{\sphinxupquote{path}} 引数が \sphinxcode{\sphinxupquote{None}} だった場合、それは最上位のインポートであることを示していて、 \sphinxcode{\sphinxupquote{sys.path}} が使われます。 パスベース・ファインダーは検索パスのすべての要素について反復処理をし、それぞれのパスに対して適切な {\hyperref[\detokenize{glossary:term-path-entry-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスエントリ・ファインダー}}}} (\sphinxcode{\sphinxupquote{PathEntryFinder}}) を探します。これは時間のかかる処理 (例えば、この検索のための \sphinxtitleref{stat()} 呼び出しのオーバーヘッド) になり得るので、パスベース・ファインダーはパス要素からパスエントリ・ファインダーへの対応付けをキャッシュとして持っておきます。このキャッシュは \sphinxcode{\sphinxupquote{sys.path\_importer\_cache}} に持っています (名前に反して、このキャッシュは実際には {\hyperref[\detokenize{glossary:term-importer}]{\sphinxtermref{\DUrole{xref,std,std-term}{インポーター}}}} には制限されておらず、ファインダーオブジェクトを保持します) 。このようにして、時間のかかる特定の {\hyperref[\detokenize{glossary:term-path-entry}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスエントリ}}}} の場所のための {\hyperref[\detokenize{glossary:term-path-entry-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスエントリ・ファインダー}}}} の検索を一度だけ検索すれば良くなります。パスベース・ファインダーにパスエントリの検索を再度行わせるために、ユーザコードでは自由に \sphinxcode{\sphinxupquote{sys.path\_importer\_cache}} からキャッシュを取り除いて構いません % \begin{footnote}[3]\sphinxAtStartFootnote レガシーなコードでは、 \sphinxcode{\sphinxupquote{sys.path\_importer\_cache}} に \sphinxcode{\sphinxupquote{imp.NullImporter}} のインスタンスがいることがあります。それの代わりに \sphinxcode{\sphinxupquote{None}} を使うようにコードを変更することが推奨されます。より詳しいことは \DUrole{xref,std,std-ref}{portingpythoncode} を参照してください。 % \end{footnote} 。 path entry がキャッシュの中に無かった場合、 path based finder は \sphinxcode{\sphinxupquote{sys.path\_hooks}} の中の呼び出し可能オブジェクトを全て辿ります。 このリストのそれぞれの {\hyperref[\detokenize{glossary:term-path-entry-hook}]{\sphinxtermref{\DUrole{xref,std,std-term}{path entry フック}}}} は、検索する path entry という引数 1 つを渡して呼び出されます。 その呼び出し可能オブジェクトは path entry を扱える {\hyperref[\detokenize{glossary:term-path-entry-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{path entry finder}}}} を返すか、 \sphinxcode{\sphinxupquote{ImportError}} を送出します。 \sphinxcode{\sphinxupquote{ImportError}} は、フックが {\hyperref[\detokenize{glossary:term-path-entry}]{\sphinxtermref{\DUrole{xref,std,std-term}{path entry}}}} のための {\hyperref[\detokenize{glossary:term-path-entry-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{path entry finder}}}} を探せないことを報せるために path based finder が使います。 この例外は処理されず、 {\hyperref[\detokenize{glossary:term-import-path}]{\sphinxtermref{\DUrole{xref,std,std-term}{import path}}}} を辿っていく処理が続けられます。 フックは引数として文字列またはバイト列オブジェクトを期待します; バイト列オブジェクトのエンコーディングはフックに任されていて (例えば、ファイルシステムのエンコーディングの UTF\sphinxhyphen{}8 やそれ以外などです) 、フックが引数をデコードできなかった場合は \sphinxcode{\sphinxupquote{ImportError}} を送出すべきです。 \sphinxcode{\sphinxupquote{sys.path\_hooks}} を辿る処理が {\hyperref[\detokenize{glossary:term-path-entry-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスエントリ・ファインダー}}}} を何も返さずに終わった場合、パスベース・ファインダーの \sphinxcode{\sphinxupquote{find\_spec()}} メソッドは、 \sphinxcode{\sphinxupquote{sys.path\_importer\_cache}} に (このパスエントリに対するファインダーが存在しないことを示すために) \sphinxcode{\sphinxupquote{None}} を保存し、 {\hyperref[\detokenize{glossary:term-meta-path-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{メタパス・ファインダー}}}} はモジュールが見つからなかったことを伝えるために \sphinxcode{\sphinxupquote{None}} を返します。 \sphinxcode{\sphinxupquote{sys.path\_hooks}} 上の {\hyperref[\detokenize{glossary:term-path-entry-hook}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスエントリフック}}}} 呼び出し可能オブジェクトの戻り値のいずれかが {\hyperref[\detokenize{glossary:term-path-entry-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{パスエントリ・ファインダー}}}} \sphinxstyleemphasis{であった} 場合、後で出てくるモジュール仕様を探すためのプロトコルが使われ、それがモジュールをロードするために使われます。 (空の文字列によって表される)現在のディレクトリは、 \sphinxcode{\sphinxupquote{sys.path}} の他のエントリとは多少異なる方法で処理されます。まず、現在のディレクトリが存在しないことが判明した場合、 \sphinxcode{\sphinxupquote{sys.path\_importer\_cache}} には何も追加されません。次に、現在のディレクトリに対する値は個々のモジュールのルックアップで毎回新たに検索されます。 3番目に、 \sphinxcode{\sphinxupquote{sys.path\_importer\_cache}} に使われ、 \sphinxcode{\sphinxupquote{importlib.machinery.PathFinder.find\_spec()}} が返すパスは、実際のディレクトリであって空の文字列ではありません。 \subsection{パスエントリ・ファインダー・プロトコル} \label{\detokenize{reference/import:path-entry-finder-protocol}} モジュールと初期化されたパッケージのインポートをサポートするため、および名前空間パッケージのポーションとして提供するために、パスエントリ・ファインダーは \sphinxcode{\sphinxupquote{find\_spec()}} メソッドを実装しなければいけません。 \sphinxcode{\sphinxupquote{find\_spec()}} takes two arguments: the fully qualified name of the module being imported, and the (optional) target module. \sphinxcode{\sphinxupquote{find\_spec()}} returns a fully populated spec for the module. This spec will always have "loader" set (with one exception). To indicate to the import machinery that the spec represents a namespace {\hyperref[\detokenize{glossary:term-portion}]{\sphinxtermref{\DUrole{xref,std,std-term}{portion}}}}, the path entry finder sets "submodule\_search\_locations" to a list containing the portion. \DUrole{versionmodified,changed}{バージョン 3.4 で変更: }\sphinxcode{\sphinxupquote{find\_spec()}} は \sphinxcode{\sphinxupquote{find\_loader()}} と \sphinxcode{\sphinxupquote{find\_module()}} を置き換えました。両者は deprecated ですが、 \sphinxtitleref{find\_spec()} が定義されていなければ使われます。 古いパスエントリ・ファインダーの中には、 \sphinxcode{\sphinxupquote{find\_spec()}} の代わりにこれら 2 つの deperecated なメソッドのうちのいずれかを実装しているものがあるかもしれません。これらのメソッドは後方互換性のためにまだ考慮されています。しかし、パスエントリ・ファインダーに \sphinxcode{\sphinxupquote{find\_spec()}} が実装されていれば、古いメソッドは無視されます。 \sphinxcode{\sphinxupquote{find\_loader()}} takes one argument, the fully qualified name of the module being imported. \sphinxcode{\sphinxupquote{find\_loader()}} returns a 2\sphinxhyphen{}tuple where the first item is the loader and the second item is a namespace {\hyperref[\detokenize{glossary:term-portion}]{\sphinxtermref{\DUrole{xref,std,std-term}{portion}}}}. 他のインポート機構の実装に対する後方互換性のために、多くのパスエントリ・ファインダーは、メタパス・ファインダーがサポートするのと同じ伝統的な \sphinxcode{\sphinxupquote{find\_module()}} メソッドもサポートしています。しかし、パスエントリ・ファインダーの \sphinxcode{\sphinxupquote{find\_module()}} メソッドは、決して \sphinxcode{\sphinxupquote{path}} 引数では呼び出されません (このメソッドは、パスフックの最初の呼び出しから適切なパス情報を記録する動作が期待されています)。 パスエントリ・ファインダーの \sphinxcode{\sphinxupquote{find\_module()}} メソッドは deprecated です。なぜなら、その方法ではパスエントリ・ファインダーが名前空間パッケージに対してポーションを提供することができないからです。もし \sphinxcode{\sphinxupquote{find\_loader()}} と \sphinxcode{\sphinxupquote{find\_module()}} の両方がパスエントリ・ファインダーに存在したら、インポートシステムは常に \sphinxcode{\sphinxupquote{find\_module()}} よりも \sphinxcode{\sphinxupquote{find\_loader()}} を優先して呼び出します。 \section{標準のインポートシステムを置き換える} \label{\detokenize{reference/import:replacing-the-standard-import-system}} インポートシステム全体を置き換えるための最も信頼性のある仕組みは、 \sphinxcode{\sphinxupquote{sys.meta\_path}} のデフォルトの内容を削除し、全部をカスタムのメタパスフックで置き換えるものです。 もし、 import 文の動作だけを変更し、インポートシステムにアクセスする他の API には影響を与えなくてもよければ、組み込みの \sphinxcode{\sphinxupquote{\_\_import\_\_()}} 関数を置き換えるだけで十分です。この手法は、ある 1 つのモジュール内だけで import 文の動作を変更するのにも用いられます。 To selectively prevent the import of some modules from a hook early on the meta path (rather than disabling the standard import system entirely), it is sufficient to raise \sphinxcode{\sphinxupquote{ModuleNotFoundError}} directly from \sphinxcode{\sphinxupquote{find\_spec()}} instead of returning \sphinxcode{\sphinxupquote{None}}. The latter indicates that the meta path search should continue, while raising an exception terminates it immediately. \section{Package Relative Imports} \label{\detokenize{reference/import:package-relative-imports}}\label{\detokenize{reference/import:relativeimports}} Relative imports use leading dots. A single leading dot indicates a relative import, starting with the current package. Two or more leading dots indicate a relative import to the parent(s) of the current package, one level per dot after the first. For example, given the following package layout: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{package}\PYG{o}{/} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}init\PYGZus{}\PYGZus{}}\PYG{o}{.}\PYG{n}{py} \PYG{n}{subpackage1}\PYG{o}{/} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}init\PYGZus{}\PYGZus{}}\PYG{o}{.}\PYG{n}{py} \PYG{n}{moduleX}\PYG{o}{.}\PYG{n}{py} \PYG{n}{moduleY}\PYG{o}{.}\PYG{n}{py} \PYG{n}{subpackage2}\PYG{o}{/} \PYG{n+nf+fm}{\PYGZus{}\PYGZus{}init\PYGZus{}\PYGZus{}}\PYG{o}{.}\PYG{n}{py} \PYG{n}{moduleZ}\PYG{o}{.}\PYG{n}{py} \PYG{n}{moduleA}\PYG{o}{.}\PYG{n}{py} \end{sphinxVerbatim} In either \sphinxcode{\sphinxupquote{subpackage1/moduleX.py}} or \sphinxcode{\sphinxupquote{subpackage1/\_\_init\_\_.py}}, the following are valid relative imports: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k+kn}{from} \PYG{n+nn}{.}\PYG{n+nn}{moduleY} \PYG{k+kn}{import} \PYG{n}{spam} \PYG{k+kn}{from} \PYG{n+nn}{.}\PYG{n+nn}{moduleY} \PYG{k+kn}{import} \PYG{n}{spam} \PYG{k}{as} \PYG{n}{ham} \PYG{k+kn}{from} \PYG{n+nn}{.} \PYG{k+kn}{import} \PYG{n}{moduleY} \PYG{k+kn}{from} \PYG{n+nn}{.}\PYG{n+nn}{.}\PYG{n+nn}{subpackage1} \PYG{k+kn}{import} \PYG{n}{moduleY} \PYG{k+kn}{from} \PYG{n+nn}{.}\PYG{n+nn}{.}\PYG{n+nn}{subpackage2}\PYG{n+nn}{.}\PYG{n+nn}{moduleZ} \PYG{k+kn}{import} \PYG{n}{eggs} \PYG{k+kn}{from} \PYG{n+nn}{.}\PYG{n+nn}{.}\PYG{n+nn}{moduleA} \PYG{k+kn}{import} \PYG{n}{foo} \end{sphinxVerbatim} Absolute imports may use either the \sphinxcode{\sphinxupquote{import <>}} or \sphinxcode{\sphinxupquote{from <> import <>}} syntax, but relative imports may only use the second form; the reason for this is that: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k+kn}{import} \PYG{n+nn}{XXX}\PYG{n+nn}{.}\PYG{n+nn}{YYY}\PYG{n+nn}{.}\PYG{n+nn}{ZZZ} \end{sphinxVerbatim} should expose \sphinxcode{\sphinxupquote{XXX.YYY.ZZZ}} as a usable expression, but .moduleY is not a valid expression. \section{\_\_main\_\_ に対する特別な考慮} \label{\detokenize{reference/import:special-considerations-for-main}} \sphinxcode{\sphinxupquote{\_\_main\_\_}} モジュールは、 Python のインポートシステムに関連する特別なケースです。 {\hyperref[\detokenize{reference/toplevel_components:programs}]{\sphinxcrossref{\DUrole{std,std-ref}{他の場所}}}} で言及されているように、 \sphinxcode{\sphinxupquote{\_\_main\_\_}} モジュールは \sphinxcode{\sphinxupquote{sys}} や \sphinxcode{\sphinxupquote{builtins}} などと同様にインタプリタースタートアップで直接初期化されます。しかし、前者 2 つのモジュールと違って、 \sphinxcode{\sphinxupquote{\_\_main\_\_}} は厳密にはビルトインのモジュールとしての資格を持っていません。これは、 \sphinxcode{\sphinxupquote{\_\_main\_\_}} が初期化される方法がインタプリタが起動されるときのフラグやその他のオプションに依存するためです。 \subsection{\_\_main\_\_.\_\_spec\_\_} \label{\detokenize{reference/import:main-spec}}\label{\detokenize{reference/import:id5}} \sphinxcode{\sphinxupquote{\_\_main\_\_}} がどのように初期化されるかに依存して、 \sphinxcode{\sphinxupquote{\_\_main\_\_.\_\_spec\_\_}} は適切に設定されることもあれば \sphinxcode{\sphinxupquote{None}} になることもあります。 Python が \sphinxcode{\sphinxupquote{\sphinxhyphen{}m}} オプションを付けて実行された場合には、 \sphinxcode{\sphinxupquote{\_\_spec\_\_}} は対応するモジュールまたはパッケージのモジュール仕様に設定されます。また、ディレクトリや zip ファイル、または他の \sphinxcode{\sphinxupquote{sys.path}} エントリを実行する処理の一部として \sphinxcode{\sphinxupquote{\_\_main\_\_}} モジュールがロードされる場合にも \sphinxcode{\sphinxupquote{\_\_spec\_\_}} が生成 (populate) されます。 \DUrole{xref,std,std-ref}{それ以外のケース} では、 \sphinxcode{\sphinxupquote{\_\_main\_\_.\_\_spec\_\_}} は \sphinxcode{\sphinxupquote{None}} に設定されます。これは、 \sphinxcode{\sphinxupquote{\_\_main\_\_}} を生成 (populate) するために使われたコードがインポート可能なモジュールと直接一致していないためです: \begin{itemize} \item {} 対話プロンプト \item {} \sphinxcode{\sphinxupquote{\sphinxhyphen{}c}} オプション \item {} stdin から起動された場合 \item {} ソースファイルやバイトコードファイルから直接起動された場合 \end{itemize} 最後のケースでは、たとえ技術的にはファイルがモジュールとして直接インポートできた \sphinxstyleemphasis{としても} \sphinxcode{\sphinxupquote{\_\_main\_\_.\_\_spec\_\_}} は常に \sphinxcode{\sphinxupquote{None}} になることに注意してください。もし \sphinxcode{\sphinxupquote{\_\_main\_\_}} において有効なモジュールメタデータが必要なら \sphinxcode{\sphinxupquote{\sphinxhyphen{}m}} スイッチを使ってください。 \sphinxcode{\sphinxupquote{\_\_main\_\_}} がインポート可能なモジュールと一致し、 \sphinxcode{\sphinxupquote{\_\_main\_\_.\_\_spec\_\_}} がそれに応じて設定されていたとしても、それでもなお、この 2 つのモジュールは別物とみなされることに注意してください。これは、 \sphinxcode{\sphinxupquote{if \_\_name\_\_ == "\_\_main\_\_":}} チェックによって保証されるブロックは、 \sphinxcode{\sphinxupquote{\_\_main\_\_}} 名前空間を生成 (populate) するためにモジュールが使用される時にだけ実行され、通常のインポート時には実行されない、という事実に起因しています。 \section{取り掛かり中の問題} \label{\detokenize{reference/import:open-issues}} XXX 図があるととても良い。 XXX * (import\_machinery.rst) モジュールとパッケージの属性のみに紙面を割いた節を設けるのは何如でしょうか? もしかしたらデータモデルについての言語リファレンスのページにある関係する内容を拡張したり、置き換えるようなものになるかもしれません。 XXX ライブラリマニュアルの runpy や pkgutil の解説の先頭すべてに、"こちらも参照 (See Also)" という、この新しいインポートシステムの節へのリンクを置くべき。 XXX \sphinxcode{\sphinxupquote{\_\_main\_\_}} が初期化される様々な方法についてより多くの説明を追加する? XXX \sphinxcode{\sphinxupquote{\_\_main\_\_}} の特異性/落とし穴についてより多くの情報を追加する (つまり \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 395@\spxentry{PEP 395}}\sphinxhref{https://www.python.org/dev/peps/pep-0395}{\sphinxstylestrong{PEP 395}} からコピーする) \section{参考資料} \label{\detokenize{reference/import:references}} Python の初期の頃からすると、インポート機構は目覚ましい発展を遂げました。 一部細かいところがドキュメントが書かれたときから変わってはいますが、最初期の \sphinxhref{https://www.python.org/doc/essays/packages/}{パッケージの仕様} はまだ読むことができます。 オリジナルの \sphinxcode{\sphinxupquote{sys.meta\_path}} の仕様は \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 302@\spxentry{PEP 302}}\sphinxhref{https://www.python.org/dev/peps/pep-0302}{\sphinxstylestrong{PEP 302}} で、その後継となる拡張が \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 420@\spxentry{PEP 420}}\sphinxhref{https://www.python.org/dev/peps/pep-0420}{\sphinxstylestrong{PEP 420}} です。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 420@\spxentry{PEP 420}}\sphinxhref{https://www.python.org/dev/peps/pep-0420}{\sphinxstylestrong{PEP 420}} は Python 3.3 に {\hyperref[\detokenize{glossary:term-namespace-package}]{\sphinxtermref{\DUrole{xref,std,std-term}{名前空間パッケージ}}}} を導入しています。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 420@\spxentry{PEP 420}}\sphinxhref{https://www.python.org/dev/peps/pep-0420}{\sphinxstylestrong{PEP 420}} はまた \sphinxcode{\sphinxupquote{find\_module()}} に代わるものとして \sphinxcode{\sphinxupquote{find\_loader()}} プロトコルを導入しています。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 366@\spxentry{PEP 366}}\sphinxhref{https://www.python.org/dev/peps/pep-0366}{\sphinxstylestrong{PEP 366}} は、メインモジュールでの明示的な相対インポートのために追加した \sphinxcode{\sphinxupquote{\_\_package\_\_}} 属性の解説をしています。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 328@\spxentry{PEP 328}}\sphinxhref{https://www.python.org/dev/peps/pep-0328}{\sphinxstylestrong{PEP 328}} は絶対インポート、明示的な相対インポート、および、当初 \sphinxcode{\sphinxupquote{\_\_name\_\_}} で提案し、後に \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 366@\spxentry{PEP 366}}\sphinxhref{https://www.python.org/dev/peps/pep-0366}{\sphinxstylestrong{PEP 366}} が \sphinxcode{\sphinxupquote{\_\_package\_\_}} で定めた仕様を導入しました。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 338@\spxentry{PEP 338}}\sphinxhref{https://www.python.org/dev/peps/pep-0338}{\sphinxstylestrong{PEP 338}} はモジュールをスクリプトとして実行するときの仕様を定めています。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 451@\spxentry{PEP 451}}\sphinxhref{https://www.python.org/dev/peps/pep-0451}{\sphinxstylestrong{PEP 451}} は、モジュール仕様オブジェクトにおけるモジュール毎のインポート状態のカプセル化を追加しています。また、ローダーの定型的な責任のほとんどをインポート機構に肩代わりさせています。これらの変更により、インポートシステムのいくつかの API が deprecate され、またファインダーとローダーには新しいメソッドが追加されました。 \subsubsection*{脚注} \chapter{式 (expression)} \label{\detokenize{reference/expressions:expressions}}\label{\detokenize{reference/expressions:id1}}\label{\detokenize{reference/expressions::doc}} \index{expression@\spxentry{expression}}\index{BNF@\spxentry{BNF}}\ignorespaces この章では、Python の式における個々の要素の意味について解説します。 \sphinxstylestrong{表記法に関する注意:} この章と以降の章での拡張BNF (extended BNF) 表記は、字句解析規則ではなく、構文規則を記述するために用いられています。ある構文規則 (のある表現方法) が、以下の形式 \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-name}}\production{name}{ \sphinxcode{\sphinxupquote{othername}}} \end{productionlist} で記述されていて、この構文特有の意味付け (semantics) が記述されていない場合、 \sphinxcode{\sphinxupquote{name}} の形式をとる構文の意味付けは \sphinxcode{\sphinxupquote{othername}} の意味付けと同じになります。 \section{算術変換 (arithmetic conversion)} \label{\detokenize{reference/expressions:arithmetic-conversions}}\label{\detokenize{reference/expressions:conversions}} \index{arithmetic@\spxentry{arithmetic}!conversion@\spxentry{conversion}}\index{conversion@\spxentry{conversion}!arithmetic@\spxentry{arithmetic}}\ignorespaces 以下の算術演算子の記述で、「数値引数は共通の型に変換されます」と書かれているとき、組み込み型に対する演算子の実装は以下の通りに動作します: \begin{itemize} \item {} 片方の引数が複素数型であれば、他方は複素数型に変換されます; \item {} それ以外の場合で、片方の引数が浮動小数点数であれば、他方は浮動小数点型に変換されます; \item {} それ以外場合は、両方の引数は整数でなければならず、変換の必要はありません。 \end{itemize} 特定の演算子 ('\%' 演算子の左引数としての文字列) には、さらに別の規則が適用されます。拡張は、それ自身の型変換のふるまいを定義していなければなりません。 \section{アトム、原子的要素 (atom)} \label{\detokenize{reference/expressions:atoms}}\label{\detokenize{reference/expressions:id2}} \index{atom@\spxentry{atom}}\ignorespaces atom は、式の一番基本的な要素です。もっとも単純な atom は、識別子またはリテラルです。丸括弧、角括弧、または波括弧で囲われた形式 (form) もまた、構文上アトムに分類されます。atom の構文は以下のようになります: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-atom}}\production{atom}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-literal}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{literal}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-enclosure}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{enclosure}}}}}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-enclosure}}\production{enclosure}{ {\hyperref[\detokenize{reference/expressions:grammar-token-parenth-form}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{parenth\_form}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-list-display}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{list\_display}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-dict-display}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{dict\_display}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-set-display}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{set\_display}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/expressions:grammar-token-generator-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{generator\_expression}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-yield-atom}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield\_atom}}}}}} \end{productionlist} \subsection{識別子 (identifier、または名前 (name))} \label{\detokenize{reference/expressions:atom-identifiers}}\label{\detokenize{reference/expressions:identifiers-names}} \index{name@\spxentry{name}}\index{identifier@\spxentry{identifier}}\ignorespaces アトムの形になっている識別子 (identifier) は名前 (name) です。字句定義については {\hyperref[\detokenize{reference/lexical_analysis:identifiers}]{\sphinxcrossref{\DUrole{std,std-ref}{識別子 (identifier) およびキーワード (keyword)}}}} 節を、名前付けや束縛については {\hyperref[\detokenize{reference/executionmodel:naming}]{\sphinxcrossref{\DUrole{std,std-ref}{名前づけと束縛 (naming and binding)}}}} 節を参照してください。 \index{例外@\spxentry{例外}!NameError@\spxentry{NameError}}\index{NameError@\spxentry{NameError}!例外@\spxentry{例外}}\ignorespaces 名前があるオブジェクトに束縛されている場合、名前 atom を評価するとそのオブジェクトになります。名前が束縛されていない場合、 atom を評価しようとすると \sphinxcode{\sphinxupquote{NameError}} 例外を送出します。 \phantomsection\label{\detokenize{reference/expressions:private-name-mangling}} \index{name@\spxentry{name}!mangling@\spxentry{mangling}}\index{mangling@\spxentry{mangling}!name@\spxentry{name}}\index{private@\spxentry{private}!names@\spxentry{names}}\index{names@\spxentry{names}!private@\spxentry{private}}\ignorespaces \sphinxstylestrong{プライベートな名前のマングリング:} クラス定義内に書かれた識別子で、2つ以上のアンダースコアから始まり、末尾が2つ以上のアンダースコアで終わっていないものは、そのクラスの \sphinxstyleemphasis{プライベートな名前} とみなされます。プライベートな名前は、コードが生成される前により長い形式に変換されます。この変換によって、クラス名の先頭にアンダースコアがあれば除去し、先頭にアンダースコアを1つ付加し、名前の前に挿入されます。例えば、クラス名 \sphinxcode{\sphinxupquote{Ham}} の中の識別子 \sphinxcode{\sphinxupquote{\_\_spam}} は、\sphinxcode{\sphinxupquote{\_Ham\_\_spam}} に変換されます。変換は識別子が使用されている構文のコンテキストからは独立しています。変換された名前が非常に長い (255文字を超える) 場合、実装によっては名前の切り詰めが行われるかもしれません。クラス名がアンダースコアのみから成る場合は変換は行われません。 \subsection{リテラル} \label{\detokenize{reference/expressions:literals}}\label{\detokenize{reference/expressions:atom-literals}} \index{literal@\spxentry{literal}}\ignorespaces Python では、文字列やバイト列リテラルと、様々な数値リテラルをサポートしています: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-literal}}\production{literal}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-stringliteral}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{stringliteral}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-bytesliteral}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{bytesliteral}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-integer}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{integer}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-floatnumber}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{floatnumber}}}}} | {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-imagnumber}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{imagnumber}}}}}} \end{productionlist} リテラルの評価は、与えられた型 (文字列、バイト列、整数、浮動小数点数、複素数) の与えられた値を持つオブジェクトを与えます。浮動小数点や虚数 (複素数) リテラルの場合、値は近似値になる場合があります。詳しくは {\hyperref[\detokenize{reference/lexical_analysis:literals}]{\sphinxcrossref{\DUrole{std,std-ref}{リテラル}}}} を参照してください。 \index{immutable@\spxentry{immutable}!data type@\spxentry{data} \spxentry{type}}\index{data@\spxentry{data}!type, immutable@\spxentry{type}, \spxentry{immutable}}\index{type@\spxentry{type}!immutable data@\spxentry{immutable} \spxentry{data}}\index{immutable@\spxentry{immutable}!object@\spxentry{object}}\index{object@\spxentry{object}!immutable@\spxentry{immutable}}\ignorespaces リテラルは全て変更不能なデータ型に対応します。このため、オブジェクトのアイデンティティはオブジェクトの値ほど重要ではありません。同じ値を持つ複数のリテラルを評価した場合、(それらのリテラルがプログラムの同じ場所由来のものであっても、そうでなくても) 同じオブジェクトを指しているか、まったく同じ値を持つ別のオブジェクトになります。 \subsection{丸括弧形式 (parenthesized form)} \label{\detokenize{reference/expressions:parenthesized-forms}}\label{\detokenize{reference/expressions:parenthesized}} \index{parenthesized form@\spxentry{parenthesized form}}\index{() (parentheses)@\spxentry{()}\spxextra{parentheses}!tuple display@\spxentry{tuple display}}\ignorespaces 丸括弧形式とは、式リストの一形態で、丸括弧で囲ったものです: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-parenth_form}}\production{parenth\_form}{ "(" {[}{\hyperref[\detokenize{reference/expressions:grammar-token-starred-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{starred\_expression}}}}}{]} ")"} \end{productionlist} 丸括弧で囲われた式のリストは、個々の式が表現するものになります: リスト内に少なくとも一つのカンマが入っていた場合、タプルになります; そうでない場合、式のリストを構成している単一の式自体の値になります。 \index{empty@\spxentry{empty}!tuple@\spxentry{tuple}}\index{tuple@\spxentry{tuple}!empty@\spxentry{empty}}\ignorespaces 中身が空の丸括弧のペアは、空のタプルオブジェクトを表します。 タプルは変更不能なので、リテラルと同じ規則が適用されます (すなわち、空のタプルが二箇所で使われると、それらは同じオブジェクトになることもあるし、ならないこともあります)。 \index{comma@\spxentry{comma}}\index{, (comma)@\spxentry{,}\spxextra{comma}}\ignorespaces タプルは丸括弧で作成されるのではなく、カンマによって作成されることに注意してください。例外は空のタプルで、この場合には丸括弧が \sphinxstyleemphasis{必要です} \sphinxhyphen{}\sphinxhyphen{}\sphinxhyphen{} 丸括弧のつかない "何も記述しない式 (nothing)" を使えるようにしてしまうと、文法があいまいなものになってしまい、よくあるタイプミスが検出されなくなってしまいます。 \subsection{リスト、集合、辞書の表示} \label{\detokenize{reference/expressions:displays-for-lists-sets-and-dictionaries}}\label{\detokenize{reference/expressions:comprehensions}} \index{comprehensions@\spxentry{comprehensions}}\ignorespaces リスト、集合、辞書を構築するために、 Python は "表示 (display)" と呼ばれる特別な構文を提供していて、次の二種類ずつがあります: \begin{itemize} \item {} コンテナの内容を明示的に列挙する \item {} \sphinxstyleemphasis{内包表記 (comprehension)} と呼ばれる、ループ処理とフィルター処理の組み合わせを用いた計算結果 \end{itemize} \index{for@\spxentry{for}!in comprehensions@\spxentry{in comprehensions}}\index{if@\spxentry{if}!in comprehensions@\spxentry{in comprehensions}}\index{async for@\spxentry{async for}!in comprehensions@\spxentry{in comprehensions}}\ignorespaces 内包表記の共通の構文要素は次の通りです: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-comprehension}}\production{comprehension}{ {\hyperref[\detokenize{reference/expressions:grammar-token-assignment-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{assignment\_expression}}}}} {\hyperref[\detokenize{reference/expressions:grammar-token-comp-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{comp\_for}}}}}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-comp_for}}\production{comp\_for}{ {[}"async"{]} "for" {\hyperref[\detokenize{reference/simple_stmts:grammar-token-target-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{target\_list}}}}} "in" {\hyperref[\detokenize{reference/expressions:grammar-token-or-test}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{or\_test}}}}} {[}{\hyperref[\detokenize{reference/expressions:grammar-token-comp-iter}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{comp\_iter}}}}}{]}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-comp_iter}}\production{comp\_iter}{ {\hyperref[\detokenize{reference/expressions:grammar-token-comp-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{comp\_for}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-comp-if}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{comp\_if}}}}}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-comp_if}}\production{comp\_if}{ "if" {\hyperref[\detokenize{reference/expressions:grammar-token-or-test}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{or\_test}}}}} {[}{\hyperref[\detokenize{reference/expressions:grammar-token-comp-iter}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{comp\_iter}}}}}{]}} \end{productionlist} 内包表記はまず単一の式、続いて少なくとも 1 個の \sphinxcode{\sphinxupquote{for}} 節、さらに続いて 0 個以上の \sphinxcode{\sphinxupquote{for}} 節あるいは \sphinxcode{\sphinxupquote{if}} 節からなります。 この場合、各々の \sphinxcode{\sphinxupquote{for}} 節や \sphinxcode{\sphinxupquote{if}} 節を、左から右へ深くなっていくネストしたブロックとみなし、ネストの最内のブロックに到達するごとに内包表記の先頭にある式を評価した結果が、最終的にできあがるコンテナの各要素になります。 ただし、最も左にある \sphinxcode{\sphinxupquote{for}} 節のイテラブル式を除いて、内包表記は暗黙的にネストされた個別のスコープで実行されます。 この仕組みのおかげで、対象のリスト内で代入された名前が外側のスコープに "漏れる" ことはありません。 最も左にある \sphinxcode{\sphinxupquote{for}} 節のイテラブル式は、それを直接囲んでいるスコープでそのまま評価され、暗黙的な入れ子のスコープに引数として渡されます。 後に続く \sphinxcode{\sphinxupquote{for}} 節と、最も左にある \sphinxcode{\sphinxupquote{for}} 節のフィルター条件はイテラブル式を直接囲んでいるスコープでは評価できません。というのは、それらは最も左のイテラブルから得られる値に依存しているかもしれないからです。 例えば次の通りです: \sphinxcode{\sphinxupquote{{[}x*y for x in range(10) for y in range(x, x+10){]}}} 。 内包表記が常に適切な型のコンテナになるのを保証するために、 \sphinxcode{\sphinxupquote{yield}} 式や \sphinxcode{\sphinxupquote{yield from}} 式は暗黙的な入れ子のスコープでは禁止されています。 \index{await@\spxentry{await}!in comprehensions@\spxentry{in comprehensions}}\ignorespaces Python 3.6 から、 {\hyperref[\detokenize{reference/compound_stmts:async-def}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async def}}}}} 関数では \sphinxcode{\sphinxupquote{async for}} 節が {\hyperref[\detokenize{glossary:term-asynchronous-iterator}]{\sphinxtermref{\DUrole{xref,std,std-term}{asynchronous iterator}}}} の反復処理をするのに使われることがありました。 \sphinxcode{\sphinxupquote{async def}} 関数に含まれる内包表記が、先頭の式に続く \sphinxcode{\sphinxupquote{for}} 節あるいは \sphinxcode{\sphinxupquote{async for}} 節で構成されていることや、追加の \sphinxcode{\sphinxupquote{for}} 節あるいは \sphinxcode{\sphinxupquote{async for}} 節を含んでいること、そのうえ {\hyperref[\detokenize{reference/expressions:await}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{await}}}}} 式を使っていることがあるかもしれません。 内包表記が \sphinxcode{\sphinxupquote{async for}} 節あるいは \sphinxcode{\sphinxupquote{await}} 式を含んでいる場合、それは \sphinxstyleemphasis{非同期内包表記} と呼ばれます。 非同期内包表記は、それが現れるコルーチン関数の実行を中断させるかもしれません。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 530@\spxentry{PEP 530}}\sphinxhref{https://www.python.org/dev/peps/pep-0530}{\sphinxstylestrong{PEP 530}} も参照してください。 \DUrole{versionmodified,added}{バージョン 3.6 で追加: }非同期内包表記が導入されました。 \DUrole{versionmodified,changed}{バージョン 3.8 で変更: }\sphinxcode{\sphinxupquote{yield}} および \sphinxcode{\sphinxupquote{yield from}} は暗黙的な入れ子のスコープでは禁止となりました。 \subsection{リスト表示} \label{\detokenize{reference/expressions:list-displays}}\label{\detokenize{reference/expressions:lists}} \index{list@\spxentry{list}!display@\spxentry{display}}\index{display@\spxentry{display}!list@\spxentry{list}}\index{list@\spxentry{list}!comprehensions@\spxentry{comprehensions}}\index{comprehensions@\spxentry{comprehensions}!list@\spxentry{list}}\index{empty@\spxentry{empty}!list@\spxentry{list}}\index{list@\spxentry{list}!empty@\spxentry{empty}}\index{オブジェクト@\spxentry{オブジェクト}!list@\spxentry{list}}\index{list@\spxentry{list}!オブジェクト@\spxentry{オブジェクト}}\index{{[}{]} (square brackets)@\spxentry{{[}{]}}\spxextra{square brackets}!list expression@\spxentry{list expression}}\index{, (comma)@\spxentry{,}\spxextra{comma}!expression list@\spxentry{expression list}}\ignorespaces リスト表示は、角括弧で囲われた式の系列です。系列は空の系列であってもかまいません: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-list_display}}\production{list\_display}{ "{[}" {[}{\hyperref[\detokenize{reference/expressions:grammar-token-starred-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{starred\_list}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-comprehension}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{comprehension}}}}}{]} "{]}"} \end{productionlist} リスト表示は、新しいリストオブジェクトを与えます。リストの内容は、式のリストまたはリスト内包表記 (list comprehension) で指定されます。 カンマで区切られた式のリストが与えられたときは、それらの各要素は左から右へと順に評価され、その順にリスト内に配置されます。 内包表記が与えられたときは、内包表記の結果の要素でリストが構成されます。 \subsection{集合表示} \label{\detokenize{reference/expressions:set-displays}}\label{\detokenize{reference/expressions:set}} \index{set@\spxentry{set}!display@\spxentry{display}}\index{display@\spxentry{display}!set@\spxentry{set}}\index{set@\spxentry{set}!comprehensions@\spxentry{comprehensions}}\index{comprehensions@\spxentry{comprehensions}!set@\spxentry{set}}\index{オブジェクト@\spxentry{オブジェクト}!set@\spxentry{set}}\index{set@\spxentry{set}!オブジェクト@\spxentry{オブジェクト}}\index{\sphinxleftcurlybrace{}\sphinxrightcurlybrace{} (curly brackets)@\spxentry{\sphinxleftcurlybrace{}\sphinxrightcurlybrace{}}\spxextra{curly brackets}!set expression@\spxentry{set expression}}\index{, (comma)@\spxentry{,}\spxextra{comma}!expression list@\spxentry{expression list}}\ignorespaces 集合表示は波括弧で表され、キーと値を分けるコロンがないことで辞書表現と区別されます: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-set_display}}\production{set\_display}{ "\{" ({\hyperref[\detokenize{reference/expressions:grammar-token-starred-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{starred\_list}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-comprehension}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{comprehension}}}}}) "\}"} \end{productionlist} 集合表示は、新しいミュータブルな集合オブジェクトを与えます。集合の内容は、式の並びまたは内包表記によって指定されます。 カンマ区切りの式のリストが与えられたときは、その要素は左から右へ順に評価され、集合オブジェクトに加えられます。 内包表記が与えられたときは、内包表記の結果の要素で集合が構成されます。 空集合は \sphinxcode{\sphinxupquote{\{\}}} で構成できません。このリテラルは空の辞書を構成します。 \subsection{辞書表示} \label{\detokenize{reference/expressions:dictionary-displays}}\label{\detokenize{reference/expressions:dict}} \index{dictionary@\spxentry{dictionary}!display@\spxentry{display}}\index{display@\spxentry{display}!dictionary@\spxentry{dictionary}}\index{dictionary@\spxentry{dictionary}!comprehensions@\spxentry{comprehensions}}\index{comprehensions@\spxentry{comprehensions}!dictionary@\spxentry{dictionary}}\index{key@\spxentry{key}}\index{datum@\spxentry{datum}}\index{key/datum pair@\spxentry{key/datum pair}}\index{オブジェクト@\spxentry{オブジェクト}!dictionary@\spxentry{dictionary}}\index{dictionary@\spxentry{dictionary}!オブジェクト@\spxentry{オブジェクト}}\index{\sphinxleftcurlybrace{}\sphinxrightcurlybrace{} (curly brackets)@\spxentry{\sphinxleftcurlybrace{}\sphinxrightcurlybrace{}}\spxextra{curly brackets}!dictionary expression@\spxentry{dictionary expression}}\index{: (colon)@\spxentry{:}\spxextra{colon}!in dictionary expressions@\spxentry{in dictionary expressions}}\index{, (comma)@\spxentry{,}\spxextra{comma}!in dictionary displays@\spxentry{in dictionary displays}}\ignorespaces 辞書表示は、波括弧で囲われた、キーと値のペアからなる系列です。系列は空の系列であってもかまいません: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-dict_display}}\production{dict\_display}{ "\{" {[}{\hyperref[\detokenize{reference/expressions:grammar-token-key-datum-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{key\_datum\_list}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-dict-comprehension}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{dict\_comprehension}}}}}{]} "\}"} \phantomsection\label{\detokenize{reference/expressions:grammar-token-key_datum_list}}\production{key\_datum\_list}{ {\hyperref[\detokenize{reference/expressions:grammar-token-key-datum}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{key\_datum}}}}} ("," {\hyperref[\detokenize{reference/expressions:grammar-token-key-datum}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{key\_datum}}}}})* {[}","{]}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-key_datum}}\production{key\_datum}{ {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} ":" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} | "**" {\hyperref[\detokenize{reference/expressions:grammar-token-or-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{or\_expr}}}}}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-dict_comprehension}}\production{dict\_comprehension}{ {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} ":" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} {\hyperref[\detokenize{reference/expressions:grammar-token-comp-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{comp\_for}}}}}} \end{productionlist} 辞書表示は、新たな辞書オブジェクトを表します。 キーとデータからなる対の並びがカンマ区切りで与えられたときは、その要素は左から右へ評価され、辞書のエントリーを定義します。すなわち、それぞれのキーオブジェクトが、辞書内で対応するデータを保存するキーとして使われます。 これにより、キーとデータのリストの中で同じキーを複数回指定することができ、そのキーに対する最終的な辞書の値は、最後に与えられたものになります。 \index{unpacking@\spxentry{unpacking}!dictionary@\spxentry{dictionary}}\index{**@\spxentry{**}!in dictionary displays@\spxentry{in dictionary displays}}\ignorespaces ダブルアスタリスク \sphinxcode{\sphinxupquote{**}} は \sphinxstyleemphasis{辞書のアンパック} を表します。このとき被演算子は {\hyperref[\detokenize{glossary:term-mapping}]{\sphinxtermref{\DUrole{xref,std,std-term}{mapping}}}} でなければなりません。それぞれのmappingの要素は、新たな辞書に追加されます。キー/データの対もしくは辞書のアンパックによって先に追加された値は、後から追加された値によって上書きされます。 \DUrole{versionmodified,added}{バージョン 3.5 で追加: }辞書表示のアンパックは最初に \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 448@\spxentry{PEP 448}}\sphinxhref{https://www.python.org/dev/peps/pep-0448}{\sphinxstylestrong{PEP 448}} で提案されました。 辞書内包表記は、リストや集合の内包表記とは対照的に、通常の "for" や "if" 節の前に、コロンで分けられた 2 つの式が必要です。内包表記が起動すると、結果のキーと値の要素が、作られた順に新しい辞書に挿入されます。 \index{immutable@\spxentry{immutable}!object@\spxentry{object}}\index{object@\spxentry{object}!immutable@\spxentry{immutable}}\index{hashable@\spxentry{hashable}}\ignorespaces キーの値として使える型に関する制限は {\hyperref[\detokenize{reference/datamodel:types}]{\sphinxcrossref{\DUrole{std,std-ref}{標準型の階層}}}} 節ですでに列挙しています。(一言でいうと、キーは変更可能なオブジェクトを全て排除した {\hyperref[\detokenize{glossary:term-hashable}]{\sphinxtermref{\DUrole{xref,std,std-term}{hashable}}}} でなければなりません。) 重複するキー間で衝突が起きても、衝突が検出されることはありません; あるキーに対して、最後に渡されたデータ (プログラムテキスト上では、辞書表記の最も右側値となるもの) が使われます。 \DUrole{versionmodified,changed}{バージョン 3.8 で変更: }Python 3.8 より前のバージョンでは、辞書内包表記において、キーと値の評価順序は明示されていませんでした。CPython では、値がキーより先に評価されていました。バージョン 3.8 からは \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 572@\spxentry{PEP 572}}\sphinxhref{https://www.python.org/dev/peps/pep-0572}{\sphinxstylestrong{PEP 572}} で提案されているように、キーが値より先に評価されます。 \subsection{ジェネレータ式} \label{\detokenize{reference/expressions:generator-expressions}}\label{\detokenize{reference/expressions:genexpr}} \index{generator@\spxentry{generator}!expression@\spxentry{expression}}\index{expression@\spxentry{expression}!generator@\spxentry{generator}}\index{オブジェクト@\spxentry{オブジェクト}!generator@\spxentry{generator}}\index{generator@\spxentry{generator}!オブジェクト@\spxentry{オブジェクト}}\index{() (parentheses)@\spxentry{()}\spxextra{parentheses}!generator expression@\spxentry{generator expression}}\ignorespaces ジェネレータ式 (generator expression) とは、丸括弧を使ったコンパクトなジェネレータ表記法です: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-generator_expression}}\production{generator\_expression}{ "(" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} {\hyperref[\detokenize{reference/expressions:grammar-token-comp-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{comp\_for}}}}} ")"} \end{productionlist} ジェネレータ式は新たなジェネレータオブジェクトを与えます。この構文は内包表記とほぼ同じですが、角括弧や波括弧ではなく、丸括弧で囲まれます。 ジェネレータ式の中で使われている変数は、 (通常のジェネレータと同じように) そのジェネレータオブジェクトに対して {\hyperref[\detokenize{reference/expressions:generator.__next__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_next\_\_()}}}}} メソッドが呼ばれるときまで評価が遅延されます。 ただし、最も左にある \sphinxcode{\sphinxupquote{for}} 節のイテラブル式は直ちに評価されます。そのためそこで生じたエラーは、最初の値が得られた時点ではなく、ジェネレータ式が定義された時点で発せられます。 後に続く \sphinxcode{\sphinxupquote{for}} 節と、最も左にある \sphinxcode{\sphinxupquote{for}} 節のフィルター条件はイテラブル式を直接囲んでいるスコープでは評価できません。というのは、それらは最も左のイテラブルから得られる値に依存しているかもしれないからです。 例えば次の通りです: \sphinxcode{\sphinxupquote{(x*y for x in range(10) for y in range(x, x+10))}} 。 関数の唯一の引数として渡す場合には、丸括弧を省略できます。詳しくは {\hyperref[\detokenize{reference/expressions:calls}]{\sphinxcrossref{\DUrole{std,std-ref}{呼び出し (call)}}}} 節を参照してください。 ジェネレータ式自身の期待される動作を妨げないために、 \sphinxcode{\sphinxupquote{yield}} 式や \sphinxcode{\sphinxupquote{yield from}} 式は暗黙的に定義されたジェネレータでは禁止されています。 ジェネレータ式が \sphinxcode{\sphinxupquote{async for}} 節あるいは {\hyperref[\detokenize{reference/expressions:await}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{await}}}}} 式を含んでいる場合、それは \sphinxstyleemphasis{非同期ジェネレータ式} と呼ばれます。 非同期ジェネレータ式は、非同期イテレータである新しい非同期ジェネレータオブジェクトを返します ({\hyperref[\detokenize{reference/datamodel:async-iterators}]{\sphinxcrossref{\DUrole{std,std-ref}{非同期イテレータ (Asynchronous Iterator)}}}} を参照してください)。 \DUrole{versionmodified,added}{バージョン 3.6 で追加: }非同期ジェネレータ式が導入されました。 \DUrole{versionmodified,changed}{バージョン 3.7 で変更: }Python 3.7 より前では、非同期ジェネレータ式は {\hyperref[\detokenize{reference/compound_stmts:async-def}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async def}}}}} コルーチンでしか使えませんでした。 3.7 からは、任意の関数で非同期ジェネレータ式が使えるようになりました。 \DUrole{versionmodified,changed}{バージョン 3.8 で変更: }\sphinxcode{\sphinxupquote{yield}} および \sphinxcode{\sphinxupquote{yield from}} は暗黙的な入れ子のスコープでは禁止となりました。 \subsection{Yield 式} \label{\detokenize{reference/expressions:yield-expressions}}\label{\detokenize{reference/expressions:yieldexpr}} \index{キーワード@\spxentry{キーワード}!yield@\spxentry{yield}}\index{yield@\spxentry{yield}!キーワード@\spxentry{キーワード}}\index{キーワード@\spxentry{キーワード}!from@\spxentry{from}}\index{from@\spxentry{from}!キーワード@\spxentry{キーワード}}\index{yield@\spxentry{yield}!expression@\spxentry{expression}}\index{expression@\spxentry{expression}!yield@\spxentry{yield}}\index{generator@\spxentry{generator}!function@\spxentry{function}}\index{function@\spxentry{function}!generator@\spxentry{generator}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-yield_atom}}\production{yield\_atom}{ "(" {\hyperref[\detokenize{reference/expressions:grammar-token-yield-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield\_expression}}}}} ")"} \phantomsection\label{\detokenize{reference/expressions:grammar-token-yield_expression}}\production{yield\_expression}{ "yield" {[}{\hyperref[\detokenize{reference/expressions:grammar-token-expression-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression\_list}}}}} | "from" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}{]}} \end{productionlist} The yield expression is used when defining a {\hyperref[\detokenize{glossary:term-generator}]{\sphinxtermref{\DUrole{xref,std,std-term}{generator}}}} function or an {\hyperref[\detokenize{glossary:term-asynchronous-generator}]{\sphinxtermref{\DUrole{xref,std,std-term}{asynchronous generator}}}} function and thus can only be used in the body of a function definition. Using a yield expression in a function's body causes that function to be a generator function, and using it in an {\hyperref[\detokenize{reference/compound_stmts:async-def}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async def}}}}} function's body causes that coroutine function to be an asynchronous generator function. For example: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{def} \PYG{n+nf}{gen}\PYG{p}{(}\PYG{p}{)}\PYG{p}{:} \PYG{c+c1}{\PYGZsh{} defines a generator function} \PYG{k}{yield} \PYG{l+m+mi}{123} \PYG{k}{async} \PYG{k}{def} \PYG{n+nf}{agen}\PYG{p}{(}\PYG{p}{)}\PYG{p}{:} \PYG{c+c1}{\PYGZsh{} defines an asynchronous generator function} \PYG{k}{yield} \PYG{l+m+mi}{123} \end{sphinxVerbatim} 含まれているスコープの副作用のため、 \sphinxcode{\sphinxupquote{yield}} 式は暗黙的に定義されたスコープの一部として内包表記やジェネレータ式を実装するのに使うことは許可されていません。 \DUrole{versionmodified,changed}{バージョン 3.8 で変更: }yield 式は、暗黙的な入れ子のスコープで内包表記やジェネレータ式を実装するための使用が禁止になりました。 ジェネレータ関数についてはすぐ下で説明されています。非同期ジェネレータ関数は、 {\hyperref[\detokenize{reference/expressions:asynchronous-generator-functions}]{\sphinxcrossref{\DUrole{std,std-ref}{非同期ジェネレータ関数 (asynchronous generator function)}}}} 節に分けて説明されています。 ジェネレータ関数が呼び出された時、ジェネレータとしてのイテレータを返します。ジェネレータはその後ジェネレータ関数の実行を制御します。ジェネレータのメソッドが呼び出されると実行が開始されます。開始されると、最初の yield 式まで処理して一時停止し、呼び出し元へ {\hyperref[\detokenize{reference/expressions:grammar-token-expression-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression\_list}}}}} の値を返します。ここで言う一時停止とは、ローカル変数の束縛、命令ポインタや内部の評価スタック、そして例外処理のを含むすべてのローカル状態が保持されることを意味します。再度、ジェネレータのメソッドが呼び出されて実行を再開した時、ジェネレータは yield 式がただの外部呼び出しであったかのように処理を継続します。再開後の yield 式の値は実行を再開するメソッドに依存します。{\hyperref[\detokenize{reference/expressions:generator.__next__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_next\_\_()}}}}} を使用した場合 (一般に {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} 文や組み込み関数 \sphinxcode{\sphinxupquote{next()}} など) の結果は \sphinxcode{\sphinxupquote{None}} となり、{\hyperref[\detokenize{reference/expressions:generator.send}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{send()}}}}} を使用した場合はそのメソッドに渡された値が結果になります。 \index{coroutine@\spxentry{coroutine}}\ignorespaces これまで説明した内容から、ジェネレータ関数はコルーチンにとてもよく似ています。ジェネレータ関数は何度も生成し、1つ以上のエントリポイントを持ち、その実行は一時停止されます。ジェネレータ関数は yield した後で実行の継続を制御できないことが唯一の違いです。その制御は常にジェネレータの呼び出し元へ移されます。 yield 式は {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} 構造内で使用できます。ジェネレータの (参照カウントがゼロに達するか、ガベージコレクションによる) 完了前に再開されない場合、ジェネレータ\sphinxhyphen{}イテレータの {\hyperref[\detokenize{reference/expressions:generator.close}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{close()}}}}} メソッドが呼ばれ、{\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節が実行されます。 \index{from@\spxentry{from}!yield from expression@\spxentry{yield from expression}}\ignorespaces When \sphinxcode{\sphinxupquote{yield from }} is used, the supplied expression must be an iterable. The values produced by iterating that iterable are passed directly to the caller of the current generator's methods. Any values passed in with {\hyperref[\detokenize{reference/expressions:generator.send}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{send()}}}}} and any exceptions passed in with {\hyperref[\detokenize{reference/expressions:generator.throw}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{throw()}}}}} are passed to the underlying iterator if it has the appropriate methods. If this is not the case, then {\hyperref[\detokenize{reference/expressions:generator.send}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{send()}}}}} will raise \sphinxcode{\sphinxupquote{AttributeError}} or \sphinxcode{\sphinxupquote{TypeError}}, while {\hyperref[\detokenize{reference/expressions:generator.throw}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{throw()}}}}} will just raise the passed in exception immediately. 根底のイテレータの完了時、引き起こされた \sphinxcode{\sphinxupquote{StopIteration}} インスタンスの \sphinxcode{\sphinxupquote{value}} 属性はその yield 式の値となります。 \sphinxcode{\sphinxupquote{StopIteration}} を起こす際に明示的にセットされるか、サブイテレータがジェネレータであれば (サブイテレータからかえる値で) 自動的にセットされるかのどちらかです。 \begin{quote} \DUrole{versionmodified,changed}{バージョン 3.3 で変更: }サブイテレータに制御フローを委譲するために \sphinxcode{\sphinxupquote{yield from }} が追加されました。 \end{quote} yield 式が代入文の単独の右辺式であるとき、括弧は省略できます。 \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 255@\spxentry{PEP 255}}\sphinxhref{https://www.python.org/dev/peps/pep-0255}{\sphinxstylestrong{PEP 255}} \sphinxhyphen{} 単純なジェネレータ}] \leavevmode Python へのジェネレータと {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} 文の導入提案。 \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 342@\spxentry{PEP 342}}\sphinxhref{https://www.python.org/dev/peps/pep-0342}{\sphinxstylestrong{PEP 342}} \sphinxhyphen{} 拡張されたジェネレータを用いたコルーチン}] \leavevmode シンプルなコルーチンとして利用できるように、ジェネレータの構文と API を拡張する提案。 \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 380@\spxentry{PEP 380}}\sphinxhref{https://www.python.org/dev/peps/pep-0380}{\sphinxstylestrong{PEP 380}} \sphinxhyphen{} サブジェネレータへの委譲構文}] \leavevmode サブジェネレータの委譲を簡単にするための、 \sphinxcode{\sphinxupquote{yield\_from}} 構文の導入提案。 \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 525@\spxentry{PEP 525}}\sphinxhref{https://www.python.org/dev/peps/pep-0525}{\sphinxstylestrong{PEP 525}} \sphinxhyphen{} 非同期ジェネレータ}] \leavevmode コルーチン関数へのジェネレータの実装能力の追加による \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 492@\spxentry{PEP 492}}\sphinxhref{https://www.python.org/dev/peps/pep-0492}{\sphinxstylestrong{PEP 492}} の拡張提案。 \end{description} \index{オブジェクト@\spxentry{オブジェクト}!generator@\spxentry{generator}}\index{generator@\spxentry{generator}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces \subsubsection{ジェネレータ\sphinxhyphen{}イテレータメソッド} \label{\detokenize{reference/expressions:generator-iterator-methods}}\label{\detokenize{reference/expressions:generator-methods}}\label{\detokenize{reference/expressions:index-31}} この説ではジェネレータイテレータのメソッドについて説明します。これらはジェネレータ関数の実行制御に使用できます。 以下のジェネレータメソッドの呼び出しは、ジェネレータが既に実行中の場合 \sphinxcode{\sphinxupquote{ValueError}} 例外を送出する点に注意してください。 \index{例外@\spxentry{例外}!StopIteration@\spxentry{StopIteration}}\index{StopIteration@\spxentry{StopIteration}!例外@\spxentry{例外}}\ignorespaces \index{\_\_next\_\_() (generator のメソッド)@\spxentry{\_\_next\_\_()}\spxextra{generator のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/expressions:generator.__next__}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{generator.}}\sphinxbfcode{\sphinxupquote{\_\_next\_\_}}}{}{} ジェネレータ関数の実行を開始するか、最後に yield 式が実行されたところから再開します。ジェネレータ関数が {\hyperref[\detokenize{reference/expressions:generator.__next__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_next\_\_()}}}}} メソッドによって再開された時、その時点の {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} 式の値は常に \sphinxcode{\sphinxupquote{None}} と評価されます。その後次の {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} 式まで実行し、ジェネレータは一時停止し、{\hyperref[\detokenize{reference/expressions:grammar-token-expression-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression\_list}}}}} の値を {\hyperref[\detokenize{reference/expressions:generator.__next__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_next\_\_()}}}}} メソッドの呼び出し元に返します。ジェネレータが次の値を yield せずに終了した場合、\sphinxcode{\sphinxupquote{StopIteration}} 例外が送出されます。 このメソッドは通常、例えば {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} ループや組み込みの \sphinxcode{\sphinxupquote{next()}} 関数によって暗黙に呼び出されます。 \end{fulllineitems} \index{send() (generator のメソッド)@\spxentry{send()}\spxextra{generator のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/expressions:generator.send}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{generator.}}\sphinxbfcode{\sphinxupquote{send}}}{\emph{value}}{} ジェネレータ関数の内部へ値を "送り"、実行を再開します。引数の \sphinxstyleemphasis{value} はその時点の yield 式の結果になります。 {\hyperref[\detokenize{reference/expressions:generator.send}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{send()}}}}} メソッドは次にジェネレータが生成した値を返し、ジェネレータが次の値を生成することなく終了すると \sphinxcode{\sphinxupquote{StopIteration}} を送出します。 {\hyperref[\detokenize{reference/expressions:generator.send}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{send()}}}}} が呼び出されてジェネレータが開始するときは、値を受け取る yield 式が存在しないので、 \sphinxcode{\sphinxupquote{None}} を引数として呼び出さなければなりません。 \end{fulllineitems} \index{throw() (generator のメソッド)@\spxentry{throw()}\spxextra{generator のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/expressions:generator.throw}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{generator.}}\sphinxbfcode{\sphinxupquote{throw}}}{\emph{value}}{}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{generator.}}\sphinxbfcode{\sphinxupquote{throw}}}{\emph{type}\sphinxoptional{, \emph{value}\sphinxoptional{, \emph{traceback}}}}{} Raises an exception at the point where the generator was paused, and returns the next value yielded by the generator function. If the generator exits without yielding another value, a \sphinxcode{\sphinxupquote{StopIteration}} exception is raised. If the generator function does not catch the passed\sphinxhyphen{}in exception, or raises a different exception, then that exception propagates to the caller. In typical use, this is called with a single exception instance similar to the way the {\hyperref[\detokenize{reference/simple_stmts:raise}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{raise}}}}} keyword is used. For backwards compatability, however, the second signature is supported, following a convention from older versions of Python. The \sphinxstyleemphasis{type} argument should be an exception class, and \sphinxstyleemphasis{value} should be an exception instance. If the \sphinxstyleemphasis{value} is not provided, the \sphinxstyleemphasis{type} constructor is called to get an instance. If \sphinxstyleemphasis{traceback} is provided, it is set on the exception, otherwise any existing \sphinxcode{\sphinxupquote{\_\_traceback\_\_}} attribute stored in \sphinxstyleemphasis{value} may be cleared. \end{fulllineitems} \index{例外@\spxentry{例外}!GeneratorExit@\spxentry{GeneratorExit}}\index{GeneratorExit@\spxentry{GeneratorExit}!例外@\spxentry{例外}}\ignorespaces \index{close() (generator のメソッド)@\spxentry{close()}\spxextra{generator のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/expressions:generator.close}}\pysiglinewithargsret{\sphinxcode{\sphinxupquote{generator.}}\sphinxbfcode{\sphinxupquote{close}}}{}{} ジェネレータ関数が一時停止した時点で \sphinxcode{\sphinxupquote{GeneratorExit}} を発生させます。 そして、ジェネレータ関数が無事に終了するか、既にクローズされているか、(例外が捕捉されなかったために) \sphinxcode{\sphinxupquote{GeneratorExit}} が送出された場合、 close は呼び出し元へ戻ります。 ジェネレータが値を生成する場合 \sphinxcode{\sphinxupquote{RuntimeError}} が発生します。 {\hyperref[\detokenize{reference/expressions:generator.close}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{close()}}}}} はジェネレータが例外や正常な終了により既に終了している場合は何もしません。 \end{fulllineitems} \index{yield@\spxentry{yield}!examples@\spxentry{examples}}\ignorespaces \subsubsection{使用例} \label{\detokenize{reference/expressions:examples}}\label{\detokenize{reference/expressions:index-34}} 以下の簡単なサンプルはジェネレータとジェネレータ関数の振る舞いを実際に紹介します: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k}{def} \PYG{n+nf}{echo}\PYG{p}{(}\PYG{n}{value}\PYG{o}{=}\PYG{k+kc}{None}\PYG{p}{)}\PYG{p}{:} \PYG{g+gp}{... } \PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{Execution starts when }\PYG{l+s+s2}{\PYGZsq{}}\PYG{l+s+s2}{next()}\PYG{l+s+s2}{\PYGZsq{}}\PYG{l+s+s2}{ is called for the first time.}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} \PYG{g+gp}{... } \PYG{k}{try}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{while} \PYG{k+kc}{True}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{try}\PYG{p}{:} \PYG{g+gp}{... } \PYG{n}{value} \PYG{o}{=} \PYG{p}{(}\PYG{k}{yield} \PYG{n}{value}\PYG{p}{)} \PYG{g+gp}{... } \PYG{k}{except} \PYG{n+ne}{Exception} \PYG{k}{as} \PYG{n}{e}\PYG{p}{:} \PYG{g+gp}{... } \PYG{n}{value} \PYG{o}{=} \PYG{n}{e} \PYG{g+gp}{... } \PYG{k}{finally}\PYG{p}{:} \PYG{g+gp}{... } \PYG{n+nb}{print}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{Don}\PYG{l+s+s2}{\PYGZsq{}}\PYG{l+s+s2}{t forget to clean up when }\PYG{l+s+s2}{\PYGZsq{}}\PYG{l+s+s2}{close()}\PYG{l+s+s2}{\PYGZsq{}}\PYG{l+s+s2}{ is called.}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} \PYG{g+gp}{...} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{generator} \PYG{o}{=} \PYG{n}{echo}\PYG{p}{(}\PYG{l+m+mi}{1}\PYG{p}{)} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{print}\PYG{p}{(}\PYG{n+nb}{next}\PYG{p}{(}\PYG{n}{generator}\PYG{p}{)}\PYG{p}{)} \PYG{g+go}{Execution starts when \PYGZsq{}next()\PYGZsq{} is called for the first time.} \PYG{g+go}{1} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{print}\PYG{p}{(}\PYG{n+nb}{next}\PYG{p}{(}\PYG{n}{generator}\PYG{p}{)}\PYG{p}{)} \PYG{g+go}{None} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{generator}\PYG{o}{.}\PYG{n}{send}\PYG{p}{(}\PYG{l+m+mi}{2}\PYG{p}{)}\PYG{p}{)} \PYG{g+go}{2} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{generator}\PYG{o}{.}\PYG{n}{throw}\PYG{p}{(}\PYG{n+ne}{TypeError}\PYG{p}{,} \PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{spam}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} \PYG{g+go}{TypeError(\PYGZsq{}spam\PYGZsq{},)} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{generator}\PYG{o}{.}\PYG{n}{close}\PYG{p}{(}\PYG{p}{)} \PYG{g+go}{Don\PYGZsq{}t forget to clean up when \PYGZsq{}close()\PYGZsq{} is called.} \end{sphinxVerbatim} \sphinxcode{\sphinxupquote{yield from}} の使用例は、"What's New in Python." の \DUrole{xref,std,std-ref}{pep\sphinxhyphen{}380} を参照してください。 \subsubsection{非同期ジェネレータ関数 (asynchronous generator function)} \label{\detokenize{reference/expressions:asynchronous-generator-functions}}\label{\detokenize{reference/expressions:id3}} {\hyperref[\detokenize{reference/compound_stmts:async-def}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async def}}}}} を使用して定義された関数やメソッドに yield 式があると、その関数は {\hyperref[\detokenize{glossary:term-asynchronous-generator}]{\sphinxtermref{\DUrole{xref,std,std-term}{非同期ジェネレータ}}}} 関数として定義されます。 非同期ジェネレータ関数が呼び出されると、非同期ジェネレータオブジェクトと呼ばれる非同期イテレータが返されます。 そして、そのオブジェクトはジェネレータ関数の実行を制御します。 通常、非同期ジェネレータオブジェクトは、コルーチン関数内の {\hyperref[\detokenize{reference/compound_stmts:async-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async for}}}}} 文で使われ、これはジェネレータオブジェクトが {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} 文で使われる様子に類似します。 非同期ジェネレータのメソッドの 1 つを呼び出すと {\hyperref[\detokenize{glossary:term-awaitable}]{\sphinxtermref{\DUrole{xref,std,std-term}{awaitable}}}} オブジェクトが返され、このオブジェクトが動く番になったときに実行が開始されます。 そのときに実行は最初の yield 式まで進み、そこで再び中断され、 {\hyperref[\detokenize{reference/expressions:grammar-token-expression-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression\_list}}}}} の値を待機中のコルーチンに返します。 ジェネレータと同様に、中断とは、現在のローカル変数束縛、命令ポインタ、内部評価スタック、および例外処理の状態など、すべてのローカルな状態が保たれることを意味します。 非同期ジェネレータのメソッドから次のオブジェクトが返されたことで実行が再開されると、関数はあたかも yield 式が単なる外部呼び出しであるかのように処理を進めていきます。 再開後の yield 式の値は、実行を再開したメソッドによって異なります。 {\hyperref[\detokenize{reference/expressions:agen.__anext__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_anext\_\_()}}}}} を使った場合は、結果は \sphinxcode{\sphinxupquote{None}} になります。 そうではなく、 {\hyperref[\detokenize{reference/expressions:agen.asend}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{asend()}}}}} が使用された場合は、結果はそのメソッドに渡された値になります。 非同期ジェネレータ関数では、 {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} 構造内の任意の場所で yield 式が使用できます。 ただし、非同期ジェネレータが、(参照カウントがゼロに達するか、ガベージコレクションによる) 終了処理より前に再開されない場合、 \sphinxcode{\sphinxupquote{try}} 構造内の yield 式は失敗となり、実行待ちだった {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節が実行されます。 このケースでは、非同期ジェネレータが作動しているイベントループやスケジューラの責務は、非同期ジェネレータの {\hyperref[\detokenize{reference/expressions:agen.aclose}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{aclose()}}}}} メソッドを呼び出し、残りのコルーチンオブジェクトを実行し、それによって実行待ちだった \sphinxcode{\sphinxupquote{finally}} 節が実行できるようにします。 To take care of finalization, an event loop should define a \sphinxstyleemphasis{finalizer} function which takes an asynchronous generator\sphinxhyphen{}iterator and presumably calls {\hyperref[\detokenize{reference/expressions:agen.aclose}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{aclose()}}}}} and executes the coroutine. This \sphinxstyleemphasis{finalizer} may be registered by calling \sphinxcode{\sphinxupquote{sys.set\_asyncgen\_hooks()}}. When first iterated over, an asynchronous generator\sphinxhyphen{}iterator will store the registered \sphinxstyleemphasis{finalizer} to be called upon finalization. For a reference example of a \sphinxstyleemphasis{finalizer} method see the implementation of \sphinxcode{\sphinxupquote{asyncio.Loop.shutdown\_asyncgens}} in \sphinxhref{https://github.com/python/cpython/tree/3.9/Lib/asyncio/base\_events.py}{Lib/asyncio/base\_events.py}. \sphinxcode{\sphinxupquote{yield from }} 式は、非同期ジェネレータ関数で使われると文法エラーになります。 \index{オブジェクト@\spxentry{オブジェクト}!asynchronous\sphinxhyphen{}generator@\spxentry{asynchronous\sphinxhyphen{}generator}}\index{asynchronous\sphinxhyphen{}generator@\spxentry{asynchronous\sphinxhyphen{}generator}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces \subsubsection{非同期ジェネレータイテレータメソッド} \label{\detokenize{reference/expressions:asynchronous-generator-iterator-methods}}\label{\detokenize{reference/expressions:asynchronous-generator-methods}}\label{\detokenize{reference/expressions:index-35}} この小節では、ジェネレータ関数の実行制御に使われる非同期ジェネレータイテレータのメソッドについて説明します。 \index{例外@\spxentry{例外}!StopAsyncIteration@\spxentry{StopAsyncIteration}}\index{StopAsyncIteration@\spxentry{StopAsyncIteration}!例外@\spxentry{例外}}\ignorespaces \index{\_\_anext\_\_() (agen のメソッド)@\spxentry{\_\_anext\_\_()}\spxextra{agen のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/expressions:agen.__anext__}}\pysiglinewithargsret{\sphinxbfcode{\sphinxupquote{coroutine }}\sphinxcode{\sphinxupquote{agen.}}\sphinxbfcode{\sphinxupquote{\_\_anext\_\_}}}{}{} Returns an awaitable which when run starts to execute the asynchronous generator or resumes it at the last executed yield expression. When an asynchronous generator function is resumed with an {\hyperref[\detokenize{reference/expressions:agen.__anext__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_anext\_\_()}}}}} method, the current yield expression always evaluates to \sphinxcode{\sphinxupquote{None}} in the returned awaitable, which when run will continue to the next yield expression. The value of the {\hyperref[\detokenize{reference/expressions:grammar-token-expression-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression\_list}}}}} of the yield expression is the value of the \sphinxcode{\sphinxupquote{StopIteration}} exception raised by the completing coroutine. If the asynchronous generator exits without yielding another value, the awaitable instead raises a \sphinxcode{\sphinxupquote{StopAsyncIteration}} exception, signalling that the asynchronous iteration has completed. このメソッドは通常、 {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} ループによって暗黙に呼び出されます。 \end{fulllineitems} \index{asend() (agen のメソッド)@\spxentry{asend()}\spxextra{agen のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/expressions:agen.asend}}\pysiglinewithargsret{\sphinxbfcode{\sphinxupquote{coroutine }}\sphinxcode{\sphinxupquote{agen.}}\sphinxbfcode{\sphinxupquote{asend}}}{\emph{value}}{} Returns an awaitable which when run resumes the execution of the asynchronous generator. As with the {\hyperref[\detokenize{reference/expressions:generator.send}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{send()}}}}} method for a generator, this "sends" a value into the asynchronous generator function, and the \sphinxstyleemphasis{value} argument becomes the result of the current yield expression. The awaitable returned by the {\hyperref[\detokenize{reference/expressions:agen.asend}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{asend()}}}}} method will return the next value yielded by the generator as the value of the raised \sphinxcode{\sphinxupquote{StopIteration}}, or raises \sphinxcode{\sphinxupquote{StopAsyncIteration}} if the asynchronous generator exits without yielding another value. When {\hyperref[\detokenize{reference/expressions:agen.asend}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{asend()}}}}} is called to start the asynchronous generator, it must be called with \sphinxcode{\sphinxupquote{None}} as the argument, because there is no yield expression that could receive the value. \end{fulllineitems} \index{athrow() (agen のメソッド)@\spxentry{athrow()}\spxextra{agen のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/expressions:agen.athrow}}\pysiglinewithargsret{\sphinxbfcode{\sphinxupquote{coroutine }}\sphinxcode{\sphinxupquote{agen.}}\sphinxbfcode{\sphinxupquote{athrow}}}{\emph{type}\sphinxoptional{, \emph{value}\sphinxoptional{, \emph{traceback}}}}{} Returns an awaitable that raises an exception of type \sphinxcode{\sphinxupquote{type}} at the point where the asynchronous generator was paused, and returns the next value yielded by the generator function as the value of the raised \sphinxcode{\sphinxupquote{StopIteration}} exception. If the asynchronous generator exits without yielding another value, a \sphinxcode{\sphinxupquote{StopAsyncIteration}} exception is raised by the awaitable. If the generator function does not catch the passed\sphinxhyphen{}in exception, or raises a different exception, then when the awaitable is run that exception propagates to the caller of the awaitable. \end{fulllineitems} \index{例外@\spxentry{例外}!GeneratorExit@\spxentry{GeneratorExit}}\index{GeneratorExit@\spxentry{GeneratorExit}!例外@\spxentry{例外}}\ignorespaces \index{aclose() (agen のメソッド)@\spxentry{aclose()}\spxextra{agen のメソッド}} \begin{fulllineitems} \phantomsection\label{\detokenize{reference/expressions:agen.aclose}}\pysiglinewithargsret{\sphinxbfcode{\sphinxupquote{coroutine }}\sphinxcode{\sphinxupquote{agen.}}\sphinxbfcode{\sphinxupquote{aclose}}}{}{} Returns an awaitable that when run will throw a \sphinxcode{\sphinxupquote{GeneratorExit}} into the asynchronous generator function at the point where it was paused. If the asynchronous generator function then exits gracefully, is already closed, or raises \sphinxcode{\sphinxupquote{GeneratorExit}} (by not catching the exception), then the returned awaitable will raise a \sphinxcode{\sphinxupquote{StopIteration}} exception. Any further awaitables returned by subsequent calls to the asynchronous generator will raise a \sphinxcode{\sphinxupquote{StopAsyncIteration}} exception. If the asynchronous generator yields a value, a \sphinxcode{\sphinxupquote{RuntimeError}} is raised by the awaitable. If the asynchronous generator raises any other exception, it is propagated to the caller of the awaitable. If the asynchronous generator has already exited due to an exception or normal exit, then further calls to {\hyperref[\detokenize{reference/expressions:agen.aclose}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{aclose()}}}}} will return an awaitable that does nothing. \end{fulllineitems} \section{プライマリ} \label{\detokenize{reference/expressions:primaries}}\label{\detokenize{reference/expressions:id4}} \index{primary@\spxentry{primary}}\ignorespaces プライマリは、言語において最も結合の強い操作を表します。文法は以下のようになります: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-primary}}\production{primary}{ {\hyperref[\detokenize{reference/expressions:grammar-token-atom}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{atom}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-attributeref}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{attributeref}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-subscription}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{subscription}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-slicing}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{slicing}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-call}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{call}}}}}} \end{productionlist} \subsection{属性参照} \label{\detokenize{reference/expressions:attribute-references}}\label{\detokenize{reference/expressions:id5}} \index{attribute@\spxentry{attribute}!reference@\spxentry{reference}}\index{reference@\spxentry{reference}!attribute@\spxentry{attribute}}\index{. (dot)@\spxentry{.}\spxextra{dot}!attribute reference@\spxentry{attribute reference}}\ignorespaces 属性参照は、プライマリの後ろにピリオドと名前を連ねたものです: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-attributeref}}\production{attributeref}{ {\hyperref[\detokenize{reference/expressions:grammar-token-primary}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{primary}}}}} "." {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}} \end{productionlist} \index{例外@\spxentry{例外}!AttributeError@\spxentry{AttributeError}}\index{AttributeError@\spxentry{AttributeError}!例外@\spxentry{例外}}\index{オブジェクト@\spxentry{オブジェクト}!module@\spxentry{module}}\index{module@\spxentry{module}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!list@\spxentry{list}}\index{list@\spxentry{list}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces プライマリの評価は、属性参照をサポートする型のオブジェクトでなければならず、これにはほとんどのオブジェクトが当てはまります。そしてこのオブジェクトは、名前が指定した識別子名であるような属性を生成しなければなりません。この生成は {\hyperref[\detokenize{reference/datamodel:object.__getattr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getattr\_\_()}}}}} メソッドをオーバーライドすることでカスタマイズできます。その属性が得られなければ、例外 \sphinxcode{\sphinxupquote{AttributeError}} が送出されます。そうでなければ、生成されるオブジェクトの型と値は、属性を生成したオブジェクトにより決まります。同じ属性参照を複数回評価すると、互いに異なる属性オブジェクトが得られることがあります。 \subsection{添字表記 (subscription)} \label{\detokenize{reference/expressions:subscriptions}}\label{\detokenize{reference/expressions:id6}} \index{subscription@\spxentry{subscription}}\index{{[}{]} (square brackets)@\spxentry{{[}{]}}\spxextra{square brackets}!subscription@\spxentry{subscription}}\ignorespaces \index{オブジェクト@\spxentry{オブジェクト}!sequence@\spxentry{sequence}}\index{sequence@\spxentry{sequence}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!mapping@\spxentry{mapping}}\index{mapping@\spxentry{mapping}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!string@\spxentry{string}}\index{string@\spxentry{string}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!tuple@\spxentry{tuple}}\index{tuple@\spxentry{tuple}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!list@\spxentry{list}}\index{list@\spxentry{list}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!dictionary@\spxentry{dictionary}}\index{dictionary@\spxentry{dictionary}!オブジェクト@\spxentry{オブジェクト}}\index{sequence@\spxentry{sequence}!item@\spxentry{item}}\index{item@\spxentry{item}!sequence@\spxentry{sequence}}\ignorespaces The subscription of an instance of a {\hyperref[\detokenize{reference/datamodel:sequence-types}]{\sphinxcrossref{\DUrole{std,std-ref}{container class}}}} will generally select an element from the container. The subscription of a {\hyperref[\detokenize{glossary:term-generic-type}]{\sphinxtermref{\DUrole{xref,std,std-term}{generic class}}}} will generally return a \DUrole{xref,std,std-ref}{GenericAlias} object. \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-subscription}}\production{subscription}{ {\hyperref[\detokenize{reference/expressions:grammar-token-primary}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{primary}}}}} "{[}" {\hyperref[\detokenize{reference/expressions:grammar-token-expression-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression\_list}}}}} "{]}"} \end{productionlist} When an object is subscripted, the interpreter will evaluate the primary and the expression list. The primary must evaluate to an object that supports subscription. An object may support subscription through defining one or both of {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} and {\hyperref[\detokenize{reference/datamodel:object.__class_getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_()}}}}}. When the primary is subscripted, the evaluated result of the expression list will be passed to one of these methods. For more details on when \sphinxcode{\sphinxupquote{\_\_class\_getitem\_\_}} is called instead of \sphinxcode{\sphinxupquote{\_\_getitem\_\_}}, see {\hyperref[\detokenize{reference/datamodel:classgetitem-versus-getitem}]{\sphinxcrossref{\DUrole{std,std-ref}{\_\_class\_getitem\_\_ versus \_\_getitem\_\_}}}}. If the expression list contains at least one comma, it will evaluate to a \sphinxcode{\sphinxupquote{tuple}} containing the items of the expression list. Otherwise, the expression list will evaluate to the value of the list's sole member. For built\sphinxhyphen{}in objects, there are two types of objects that support subscription via {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}}: \begin{enumerate} \sphinxsetlistlabels{\arabic}{enumi}{enumii}{}{.}% \item {} Mappings. If the primary is a {\hyperref[\detokenize{glossary:term-mapping}]{\sphinxtermref{\DUrole{xref,std,std-term}{mapping}}}}, the expression list must evaluate to an object whose value is one of the keys of the mapping, and the subscription selects the value in the mapping that corresponds to that key. An example of a builtin mapping class is the \sphinxcode{\sphinxupquote{dict}} class. \item {} Sequences. If the primary is a {\hyperref[\detokenize{glossary:term-sequence}]{\sphinxtermref{\DUrole{xref,std,std-term}{sequence}}}}, the expression list must evaluate to an \sphinxcode{\sphinxupquote{int}} or a \sphinxcode{\sphinxupquote{slice}} (as discussed in the following section). Examples of builtin sequence classes include the \sphinxcode{\sphinxupquote{str}}, \sphinxcode{\sphinxupquote{list}} and \sphinxcode{\sphinxupquote{tuple}} classes. \end{enumerate} The formal syntax makes no special provision for negative indices in {\hyperref[\detokenize{glossary:term-sequence}]{\sphinxtermref{\DUrole{xref,std,std-term}{sequences}}}}. However, built\sphinxhyphen{}in sequences all provide a {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} method that interprets negative indices by adding the length of the sequence to the index so that, for example, \sphinxcode{\sphinxupquote{x{[}\sphinxhyphen{}1{]}}} selects the last item of \sphinxcode{\sphinxupquote{x}}. The resulting value must be a nonnegative integer less than the number of items in the sequence, and the subscription selects the item whose index is that value (counting from zero). Since the support for negative indices and slicing occurs in the object's {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} method, subclasses overriding this method will need to explicitly add that support. \index{character@\spxentry{character}}\index{string@\spxentry{string}!item@\spxentry{item}}\index{item@\spxentry{item}!string@\spxentry{string}}\ignorespaces A \sphinxcode{\sphinxupquote{string}} is a special kind of sequence whose items are \sphinxstyleemphasis{characters}. A character is not a separate data type but a string of exactly one character. \subsection{スライス表記 (slicing)} \label{\detokenize{reference/expressions:slicings}}\label{\detokenize{reference/expressions:id7}} \index{slicing@\spxentry{slicing}}\index{slice@\spxentry{slice}}\index{: (colon)@\spxentry{:}\spxextra{colon}!slicing@\spxentry{slicing}}\index{, (comma)@\spxentry{,}\spxextra{comma}!slicing@\spxentry{slicing}}\ignorespaces \index{オブジェクト@\spxentry{オブジェクト}!sequence@\spxentry{sequence}}\index{sequence@\spxentry{sequence}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!string@\spxentry{string}}\index{string@\spxentry{string}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!tuple@\spxentry{tuple}}\index{tuple@\spxentry{tuple}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!list@\spxentry{list}}\index{list@\spxentry{list}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces スライス表記はシーケンスオブジェクト (文字列、タプルまたはリスト) におけるある範囲の要素を選択します。スライス表記は式として用いたり、代入や {\hyperref[\detokenize{reference/simple_stmts:del}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{del}}}}} 文の対象として用いたりできます。スライス表記の構文は以下のようになります: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-slicing}}\production{slicing}{ {\hyperref[\detokenize{reference/expressions:grammar-token-primary}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{primary}}}}} "{[}" {\hyperref[\detokenize{reference/expressions:grammar-token-slice-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{slice\_list}}}}} "{]}"} \phantomsection\label{\detokenize{reference/expressions:grammar-token-slice_list}}\production{slice\_list}{ {\hyperref[\detokenize{reference/expressions:grammar-token-slice-item}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{slice\_item}}}}} ("," {\hyperref[\detokenize{reference/expressions:grammar-token-slice-item}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{slice\_item}}}}})* {[}","{]}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-slice_item}}\production{slice\_item}{ {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-proper-slice}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{proper\_slice}}}}}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-proper_slice}}\production{proper\_slice}{ {[}{\hyperref[\detokenize{reference/expressions:grammar-token-lower-bound}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{lower\_bound}}}}}{]} ":" {[}{\hyperref[\detokenize{reference/expressions:grammar-token-upper-bound}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{upper\_bound}}}}}{]} {[} ":" {[}{\hyperref[\detokenize{reference/expressions:grammar-token-stride}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{stride}}}}}{]} {]}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-lower_bound}}\production{lower\_bound}{ {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-upper_bound}}\production{upper\_bound}{ {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-stride}}\production{stride}{ {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}} \end{productionlist} 上記の形式的な構文法にはあいまいなところがあります: 式リストに見えるものは、スライスリストにも見えるため、添字表記はスライス表記としても解釈されうるということです。(スライスリストが適切なスライスを含まない場合)、これ以上の構文の複雑化はせず、スライス表記としての解釈よりも添字表記としての解釈が優先されるように定義することで、あいまいさを取り除いています。 \index{start (slice object attribute)@\spxentry{start}\spxextra{slice object attribute}}\index{stop (slice object attribute)@\spxentry{stop}\spxextra{slice object attribute}}\index{step (slice object attribute)@\spxentry{step}\spxextra{slice object attribute}}\ignorespaces スライス表記に対する意味付けは、以下のようになります。プライマリの値評価結果は、以下に述べるようにしてスライスリストから生成されたキーによって (通常の添字表記と同じ {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} メソッドを使って) インデクス指定できなければなりません。スライスリストに一つ以上のカンマが含まれている場合、キーは各スライス要素を値変換したものからなるタプルになります; それ以外の場合、単一のスライス要素自体を値変換したものがキーになります。一個の式であるスライス要素は、その式に変換されます。適切なスライスは、スライスオブジェクト ({\hyperref[\detokenize{reference/datamodel:types}]{\sphinxcrossref{\DUrole{std,std-ref}{標準型の階層}}}} 参照) に変換され、その \sphinxcode{\sphinxupquote{start}}, \sphinxcode{\sphinxupquote{stop}} および \sphinxcode{\sphinxupquote{step}} 属性は、それぞれ指定した下境界、上境界、およびとび幅 (stride) になります。式がない場所は \sphinxcode{\sphinxupquote{None}} で置き換えられます。 \index{オブジェクト@\spxentry{オブジェクト}!callable@\spxentry{callable}}\index{callable@\spxentry{callable}!オブジェクト@\spxentry{オブジェクト}}\index{call@\spxentry{call}}\index{argument@\spxentry{argument}!call semantics@\spxentry{call semantics}}\index{() (parentheses)@\spxentry{()}\spxextra{parentheses}!call@\spxentry{call}}\index{, (comma)@\spxentry{,}\spxextra{comma}!argument list@\spxentry{argument list}}\index{= (equals)@\spxentry{=}\spxextra{equals}!in function calls@\spxentry{in function calls}}\ignorespaces \subsection{呼び出し (call)} \label{\detokenize{reference/expressions:calls}}\label{\detokenize{reference/expressions:index-47}}\label{\detokenize{reference/expressions:id8}} 呼び出しは、呼び出し可能オブジェクト (例えば {\hyperref[\detokenize{glossary:term-function}]{\sphinxtermref{\DUrole{xref,std,std-term}{function}}}}) を {\hyperref[\detokenize{glossary:term-argument}]{\sphinxtermref{\DUrole{xref,std,std-term}{arguments}}}} の系列とともに呼び出します。系列は空の系列であってもかまいません: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-call}}\production{call}{ {\hyperref[\detokenize{reference/expressions:grammar-token-primary}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{primary}}}}} "(" {[}{\hyperref[\detokenize{reference/expressions:grammar-token-argument-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{argument\_list}}}}} {[}","{]} | {\hyperref[\detokenize{reference/expressions:grammar-token-comprehension}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{comprehension}}}}}{]} ")"} \phantomsection\label{\detokenize{reference/expressions:grammar-token-argument_list}}\production{argument\_list}{ {\hyperref[\detokenize{reference/expressions:grammar-token-positional-arguments}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{positional\_arguments}}}}} {[}"," {\hyperref[\detokenize{reference/expressions:grammar-token-starred-and-keywords}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{starred\_and\_keywords}}}}}{]}} \productioncont{ {[}"," {\hyperref[\detokenize{reference/expressions:grammar-token-keywords-arguments}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{keywords\_arguments}}}}}{]}} \productioncont{ | {\hyperref[\detokenize{reference/expressions:grammar-token-starred-and-keywords}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{starred\_and\_keywords}}}}} {[}"," {\hyperref[\detokenize{reference/expressions:grammar-token-keywords-arguments}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{keywords\_arguments}}}}}{]}} \productioncont{ | {\hyperref[\detokenize{reference/expressions:grammar-token-keywords-arguments}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{keywords\_arguments}}}}}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-positional_arguments}}\production{positional\_arguments}{ positional\_item ("," positional\_item)*} \phantomsection\label{\detokenize{reference/expressions:grammar-token-positional_item}}\production{positional\_item}{ {\hyperref[\detokenize{reference/expressions:grammar-token-assignment-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{assignment\_expression}}}}} | "*" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-starred_and_keywords}}\production{starred\_and\_keywords}{ ("*" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-keyword-item}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{keyword\_item}}}}})} \productioncont{ ("," "*" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} | "," {\hyperref[\detokenize{reference/expressions:grammar-token-keyword-item}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{keyword\_item}}}}})*} \phantomsection\label{\detokenize{reference/expressions:grammar-token-keywords_arguments}}\production{keywords\_arguments}{ ({\hyperref[\detokenize{reference/expressions:grammar-token-keyword-item}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{keyword\_item}}}}} | "**" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}})} \productioncont{ ("," {\hyperref[\detokenize{reference/expressions:grammar-token-keyword-item}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{keyword\_item}}}}} | "," "**" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}})*} \phantomsection\label{\detokenize{reference/expressions:grammar-token-keyword_item}}\production{keyword\_item}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}} "=" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}} \end{productionlist} 最後の位置引数やキーワード引数の後にカンマをつけてもかまいません。構文の意味付けに影響を及ぼすことはありません。 \index{parameter@\spxentry{parameter}!call semantics@\spxentry{call semantics}}\ignorespaces プライマリの評価は呼び出し可能オブジェクトでなければなりません。 (ユーザ定義関数、組み込み関数、組み込みオブジェクトのメソッド、クラスオブジェクト、クラスインスタンスのメソッド、および {\hyperref[\detokenize{reference/datamodel:object.__call__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_call\_\_()}}}}} メソッドを持つ全てのオブジェクトが呼び出し可能です)。引数式は全て、呼び出しを試みる前に評価されます。仮引数 (formal {\hyperref[\detokenize{glossary:term-parameter}]{\sphinxtermref{\DUrole{xref,std,std-term}{parameter}}}}) リストの構文については {\hyperref[\detokenize{reference/compound_stmts:function}]{\sphinxcrossref{\DUrole{std,std-ref}{関数定義}}}} を参照してください。 キーワード引数が存在する場合、以下のようにして最初に位置引数 (positional argument) に変換されます。まず、値の入っていないスロットが仮引数に対して生成されます。N 個の位置引数がある場合、位置引数は先頭の N スロットに配置されます。次に、各キーワード引数について、識別子を使って対応するスロットを決定します (識別子が最初の仮引数名と同じなら、最初のスロットを使う、といった具合です)。スロットがすでにすべて埋まっていたなら \sphinxcode{\sphinxupquote{TypeError}} 例外が送出されます。それ以外の場合、引数値をスロットに埋めていきます。 (式が \sphinxcode{\sphinxupquote{None}} であっても、その式でスロットを埋めます)。全ての引数が処理されたら、まだ埋められていないスロットをそれぞれに対応する関数定義時のデフォルト値で埋めます。(デフォルト値は、関数が定義されたときに一度だけ計算されます; 従って、リストや辞書のような変更可能なオブジェクトがデフォルト値として使われると、対応するスロットに引数を指定しない限り、このオブジェクトが全ての呼び出しから共有されます; このような状況は通常避けるべきです。) デフォルト値が指定されていない、値の埋められていないスロットが残っている場合 \sphinxcode{\sphinxupquote{TypeError}} 例外が送出されます。そうでない場合、値の埋められたスロットからなるリストが呼び出しの引数として使われます。 \sphinxstylestrong{CPython implementation detail:} 実装では、名前を持たない位置引数を受け取る組み込み関数を提供されるかもしれません。そういった引数がドキュメント化のために '名付けられて' いたとしても、実際には名付けられていないのでキーワードでは提供されません。 CPython では、C 言語で実装された関数の、名前を持たない位置引数をパースするために \sphinxcode{\sphinxupquote{PyArg\_ParseTuple()}} を使用します。 仮引数スロットの数よりも多くの位置引数がある場合、構文 \sphinxcode{\sphinxupquote{*identifier}} を使って指定された仮引数がないかぎり、 \sphinxcode{\sphinxupquote{TypeError}} 例外が送出されます; 仮引数 \sphinxcode{\sphinxupquote{*identifier}} がある場合、この仮引数は余分な位置引数が入ったタプル (もしくは、余分な位置引数がない場合には空のタプル) を受け取ります。 キーワード引数のいずれかが仮引数名に対応しない場合、構文 \sphinxcode{\sphinxupquote{**identifier}} を使って指定された仮引数がない限り、 \sphinxcode{\sphinxupquote{TypeError}} 例外が送出されます; 仮引数 \sphinxcode{\sphinxupquote{**identifier}} がある場合、この仮引数は余分なキーワード引数が入った (キーワードをキーとし、引数値をキーに対応する値とした) 辞書を受け取ります。余分なキーワード引数がない場合には、空の (新たな) 辞書を受け取ります。 \index{* (asterisk)@\spxentry{*}\spxextra{asterisk}!in function calls@\spxentry{in function calls}}\index{unpacking@\spxentry{unpacking}!in function calls@\spxentry{in function calls}}\ignorespaces 関数呼び出しに \sphinxcode{\sphinxupquote{*expression}} という構文が現れる場合は、 \sphinxcode{\sphinxupquote{expression}} の評価結果は {\hyperref[\detokenize{glossary:term-iterable}]{\sphinxtermref{\DUrole{xref,std,std-term}{イテラブル}}}} でなければなりません。 そのイテラブルの要素は、追加の位置引数であるかのように扱われます。 \sphinxcode{\sphinxupquote{f(x1, x2, *y, x3, x4)}} という呼び出しにおいて、 \sphinxstyleemphasis{y} の評価結果がシーケンス \sphinxstyleemphasis{y1}, ..., \sphinxstyleemphasis{yM} だった場合は、この呼び出しは M+4 個の位置引数 \sphinxstyleemphasis{x1}, \sphinxstyleemphasis{x2}, \sphinxstyleemphasis{y1}, ..., \sphinxstyleemphasis{yM}, \sphinxstyleemphasis{x3}, \sphinxstyleemphasis{x4} での呼び出しと同じになります。 この結論としては、 \sphinxcode{\sphinxupquote{*expression}} 構文がキーワード引数の \sphinxstyleemphasis{後ろ} に来ることもありますが、キーワード引数 (と任意の \sphinxcode{\sphinxupquote{**expression}} 引数 \sphinxhyphen{}\sphinxhyphen{} 下を参照) よりも \sphinxstyleemphasis{前} にあるものとして処理されます。 従って、このような動作になります: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k}{def} \PYG{n+nf}{f}\PYG{p}{(}\PYG{n}{a}\PYG{p}{,} \PYG{n}{b}\PYG{p}{)}\PYG{p}{:} \PYG{g+gp}{... } \PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{a}\PYG{p}{,} \PYG{n}{b}\PYG{p}{)} \PYG{g+gp}{...} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{f}\PYG{p}{(}\PYG{n}{b}\PYG{o}{=}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{o}{*}\PYG{p}{(}\PYG{l+m+mi}{2}\PYG{p}{,}\PYG{p}{)}\PYG{p}{)} \PYG{g+go}{2 1} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{f}\PYG{p}{(}\PYG{n}{a}\PYG{o}{=}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{o}{*}\PYG{p}{(}\PYG{l+m+mi}{2}\PYG{p}{,}\PYG{p}{)}\PYG{p}{)} \PYG{g+gt}{Traceback (most recent call last):} File \PYG{n+nb}{\PYGZdq{}\PYGZlt{}stdin\PYGZgt{}\PYGZdq{}}, line \PYG{l+m}{1}, in \PYG{n}{\PYGZlt{}module\PYGZgt{}} \PYG{g+gr}{TypeError}: \PYG{n}{f() got multiple values for keyword argument \PYGZsq{}a\PYGZsq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{f}\PYG{p}{(}\PYG{l+m+mi}{1}\PYG{p}{,} \PYG{o}{*}\PYG{p}{(}\PYG{l+m+mi}{2}\PYG{p}{,}\PYG{p}{)}\PYG{p}{)} \PYG{g+go}{1 2} \end{sphinxVerbatim} キーワード引数と \sphinxcode{\sphinxupquote{*expression}} 構文を同じ呼び出しで一緒に使うことはあまりないので、実際に上記のような混乱が生じることはありません。 \index{**@\spxentry{**}!in function calls@\spxentry{in function calls}}\ignorespaces 関数呼び出しで \sphinxcode{\sphinxupquote{**expression}} 構文が使われた場合、 \sphinxcode{\sphinxupquote{expression}} の評価結果は {\hyperref[\detokenize{glossary:term-mapping}]{\sphinxtermref{\DUrole{xref,std,std-term}{マッピング}}}} でなければなりません。その内容は追加のキーワード引数として扱われます。 キーワードが (明示的なキーワード引数として、あるいは他のアンパックの中に) 既に存在する場合、 \sphinxcode{\sphinxupquote{TypeError}} 例外が送出されます。 \sphinxcode{\sphinxupquote{*identifier}} や \sphinxcode{\sphinxupquote{**identifier}} 構文を使った仮引数は、位置引数スロットやキーワード引数名にすることができません。 \DUrole{versionmodified,changed}{バージョン 3.5 で変更: }関数呼び出しは任意の数の \sphinxcode{\sphinxupquote{*}} アンパックと \sphinxcode{\sphinxupquote{**}} アンパックを受け取り、位置引数はイテラブルアンパック (\sphinxcode{\sphinxupquote{*}}) の後ろに置け、キーワード引数は辞書アンパック (\sphinxcode{\sphinxupquote{**}}) の後ろに置けるようになりました。 最初に \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 448@\spxentry{PEP 448}}\sphinxhref{https://www.python.org/dev/peps/pep-0448}{\sphinxstylestrong{PEP 448}} で提案されました。 呼び出しを行うと、例外を送出しない限り、常に何らかの値を返します。 \sphinxcode{\sphinxupquote{None}} を返す場合もあります。戻り値がどのように算出されるかは、呼び出し可能オブジェクトの形態によって異なります。 各形態では\sphinxhyphen{}\sphinxhyphen{}\sphinxhyphen{} \begin{description} \item[{ユーザ定義関数:}] \leavevmode \index{function@\spxentry{function}!call@\spxentry{call}}\index{call@\spxentry{call}!function@\spxentry{function}}\index{user\sphinxhyphen{}defined@\spxentry{user\sphinxhyphen{}defined}!function call@\spxentry{function} \spxentry{call}}\index{function@\spxentry{function}!call, user\sphinxhyphen{}defined@\spxentry{call}, \spxentry{user\sphinxhyphen{}defined}}\index{call@\spxentry{call}!user\sphinxhyphen{}defined function@\spxentry{user\sphinxhyphen{}defined} \spxentry{function}}\index{オブジェクト@\spxentry{オブジェクト}!user\sphinxhyphen{}defined function@\spxentry{user\sphinxhyphen{}defined function}}\index{user\sphinxhyphen{}defined function@\spxentry{user\sphinxhyphen{}defined function}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!function@\spxentry{function}}\index{function@\spxentry{function}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces 関数のコードブロックに引数リストが渡され、実行されます。コードブロックは、まず仮引数を実引数に結合 (bind) します; この動作については {\hyperref[\detokenize{reference/compound_stmts:function}]{\sphinxcrossref{\DUrole{std,std-ref}{関数定義}}}} で記述しています。コードブロックで {\hyperref[\detokenize{reference/simple_stmts:return}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{return}}}}} 文が実行される際に、関数呼び出しの戻り値 (return value) が決定されます。 \item[{組み込み関数またはメソッド:}] \leavevmode \index{function@\spxentry{function}!call@\spxentry{call}}\index{call@\spxentry{call}!function@\spxentry{function}}\index{built\sphinxhyphen{}in function@\spxentry{built\sphinxhyphen{}in function}!call@\spxentry{call}}\index{call@\spxentry{call}!built\sphinxhyphen{}in function@\spxentry{built\sphinxhyphen{}in function}}\index{method@\spxentry{method}!call@\spxentry{call}}\index{call@\spxentry{call}!method@\spxentry{method}}\index{built\sphinxhyphen{}in method@\spxentry{built\sphinxhyphen{}in method}!call@\spxentry{call}}\index{call@\spxentry{call}!built\sphinxhyphen{}in method@\spxentry{built\sphinxhyphen{}in method}}\index{オブジェクト@\spxentry{オブジェクト}!built\sphinxhyphen{}in method@\spxentry{built\sphinxhyphen{}in method}}\index{built\sphinxhyphen{}in method@\spxentry{built\sphinxhyphen{}in method}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!built\sphinxhyphen{}in function@\spxentry{built\sphinxhyphen{}in function}}\index{built\sphinxhyphen{}in function@\spxentry{built\sphinxhyphen{}in function}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!method@\spxentry{method}}\index{method@\spxentry{method}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!function@\spxentry{function}}\index{function@\spxentry{function}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces 結果はインタプリタに依存します; 組み込み関数やメソッドの詳細は \DUrole{xref,std,std-ref}{built\sphinxhyphen{}in\sphinxhyphen{}funcs} を参照してください。 \item[{クラスオブジェクト:}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!class@\spxentry{class}}\index{class@\spxentry{class}!オブジェクト@\spxentry{オブジェクト}}\index{class object@\spxentry{class object}!call@\spxentry{call}}\index{call@\spxentry{call}!class object@\spxentry{class object}}\ignorespaces そのクラスの新しいインスタンスが返されます。 \item[{クラスインスタンスメソッド:}] \leavevmode \index{オブジェクト@\spxentry{オブジェクト}!class instance@\spxentry{class instance}}\index{class instance@\spxentry{class instance}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!instance@\spxentry{instance}}\index{instance@\spxentry{instance}!オブジェクト@\spxentry{オブジェクト}}\index{class instance@\spxentry{class instance}!call@\spxentry{call}}\index{call@\spxentry{call}!class instance@\spxentry{class instance}}\ignorespaces 対応するユーザ定義の関数が呼び出されます。このとき、呼び出し時の引数リストより一つ長い引数リストで呼び出されます: インスタンスが引数リストの先頭に追加されます。 \item[{クラスインスタンス:}] \leavevmode \index{instance@\spxentry{instance}!call@\spxentry{call}}\index{call@\spxentry{call}!instance@\spxentry{instance}}\index{\_\_call\_\_() (object method)@\spxentry{\_\_call\_\_()}\spxextra{object method}}\ignorespaces クラスで {\hyperref[\detokenize{reference/datamodel:object.__call__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_call\_\_()}}}}} メソッドが定義されていなければなりません; {\hyperref[\detokenize{reference/datamodel:object.__call__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_call\_\_()}}}}} メソッドが呼び出された場合と同じ効果をもたらします。 \end{description} \index{キーワード@\spxentry{キーワード}!await@\spxentry{await}}\index{await@\spxentry{await}!キーワード@\spxentry{キーワード}}\ignorespaces \section{Await 式} \label{\detokenize{reference/expressions:await-expression}}\label{\detokenize{reference/expressions:await}}\label{\detokenize{reference/expressions:index-57}} {\hyperref[\detokenize{glossary:term-awaitable}]{\sphinxtermref{\DUrole{xref,std,std-term}{awaitable}}}} オブジェクトでの {\hyperref[\detokenize{glossary:term-coroutine}]{\sphinxtermref{\DUrole{xref,std,std-term}{coroutine}}}} 実行を一時停止します。 {\hyperref[\detokenize{glossary:term-coroutine-function}]{\sphinxtermref{\DUrole{xref,std,std-term}{coroutine function}}}} 内でのみ使用できます。 \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-await_expr}}\production{await\_expr}{ "await" {\hyperref[\detokenize{reference/expressions:grammar-token-primary}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{primary}}}}}} \end{productionlist} \DUrole{versionmodified,added}{バージョン 3.5 で追加.} \section{べき乗演算 (power operator)} \label{\detokenize{reference/expressions:the-power-operator}}\label{\detokenize{reference/expressions:power}} \index{power@\spxentry{power}!operation@\spxentry{operation}}\index{operation@\spxentry{operation}!power@\spxentry{power}}\index{演算子@\spxentry{演算子}!**@\spxentry{**}}\index{**@\spxentry{**}!演算子@\spxentry{演算子}}\ignorespaces べき乗演算は、左側にある単項演算子よりも強い結合優先順位となります。一方、右側にある単項演算子よりは弱い結合優先順位になっています。構文は以下のようになります: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-power}}\production{power}{ ({\hyperref[\detokenize{reference/expressions:grammar-token-await-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{await\_expr}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-primary}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{primary}}}}}) {[}"**" {\hyperref[\detokenize{reference/expressions:grammar-token-u-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{u\_expr}}}}}{]}} \end{productionlist} 従って、べき乗演算子と単項演算子からなる演算列が丸括弧で囲われていない場合、演算子は右から左へと評価されます (この場合は演算子の評価順序を強制しません。つまり \sphinxcode{\sphinxupquote{\sphinxhyphen{}1**2}} は \sphinxcode{\sphinxupquote{\sphinxhyphen{}1}} になります)。 べき乗演算子の意味は、二つの引数で呼び出される組み込み関数 \sphinxcode{\sphinxupquote{pow()}} と同じで、左引数を右引数乗して与えます。数値引数はまず共通の型に変換され、結果はその型です。 整数の被演算子では、第二引数が負でない限り、結果は被演算子と同じ型になります; 第二引数が負の場合、全ての引数は浮動小数点型に変換され、浮動小数点型が返されます。例えば \sphinxcode{\sphinxupquote{10**2}} は \sphinxcode{\sphinxupquote{100}} を返しますが、\sphinxcode{\sphinxupquote{10**\sphinxhyphen{}2}} は \sphinxcode{\sphinxupquote{0.01}} を返します。 \sphinxcode{\sphinxupquote{0.0}} を負の数でべき乗すると \sphinxcode{\sphinxupquote{ZeroDivisionError}} を送出します。負の数を小数でべき乗した結果は複素数 (\sphinxcode{\sphinxupquote{complex}} number) になります。 (以前のバージョンでは \sphinxcode{\sphinxupquote{ValueError}} を送出していました) This operation can be customized using the special {\hyperref[\detokenize{reference/datamodel:object.__pow__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_pow\_\_()}}}}} method. \section{単項算術演算とビット単位演算 (unary arithmetic and bitwise operation)} \label{\detokenize{reference/expressions:unary-arithmetic-and-bitwise-operations}}\label{\detokenize{reference/expressions:unary}} \index{unary@\spxentry{unary}!arithmetic operation@\spxentry{arithmetic} \spxentry{operation}}\index{arithmetic@\spxentry{arithmetic}!operation, unary@\spxentry{operation}, \spxentry{unary}}\index{operation@\spxentry{operation}!unary arithmetic@\spxentry{unary} \spxentry{arithmetic}}\index{unary@\spxentry{unary}!bitwise operation@\spxentry{bitwise} \spxentry{operation}}\index{bitwise@\spxentry{bitwise}!operation, unary@\spxentry{operation}, \spxentry{unary}}\index{operation@\spxentry{operation}!unary bitwise@\spxentry{unary} \spxentry{bitwise}}\ignorespaces 全ての単項算術演算とビット単位演算は、同じ優先順位を持っています: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-u_expr}}\production{u\_expr}{ {\hyperref[\detokenize{reference/expressions:grammar-token-power}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{power}}}}} | "\sphinxhyphen{}" {\hyperref[\detokenize{reference/expressions:grammar-token-u-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{u\_expr}}}}} | "+" {\hyperref[\detokenize{reference/expressions:grammar-token-u-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{u\_expr}}}}} | "\textasciitilde{}" {\hyperref[\detokenize{reference/expressions:grammar-token-u-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{u\_expr}}}}}} \end{productionlist} \index{negation@\spxentry{negation}}\index{minus@\spxentry{minus}}\index{operator@\spxentry{operator}!\sphinxhyphen{} (minus)@\spxentry{\sphinxhyphen{}}\spxextra{minus}}\index{\sphinxhyphen{} (minus)@\spxentry{\sphinxhyphen{}}\spxextra{minus}!unary operator@\spxentry{unary operator}}\ignorespaces The unary \sphinxcode{\sphinxupquote{\sphinxhyphen{}}} (minus) operator yields the negation of its numeric argument; the operation can be overridden with the {\hyperref[\detokenize{reference/datamodel:object.__neg__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_neg\_\_()}}}}} special method. \index{plus@\spxentry{plus}}\index{operator@\spxentry{operator}!+ (plus)@\spxentry{+}\spxextra{plus}}\index{+ (plus)@\spxentry{+}\spxextra{plus}!unary operator@\spxentry{unary operator}}\ignorespaces The unary \sphinxcode{\sphinxupquote{+}} (plus) operator yields its numeric argument unchanged; the operation can be overridden with the {\hyperref[\detokenize{reference/datamodel:object.__pos__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_pos\_\_()}}}}} special method. \index{inversion@\spxentry{inversion}}\index{演算子@\spxentry{演算子}!\textasciitilde{} (tilde)@\spxentry{\textasciitilde{}}\spxextra{tilde}}\index{\textasciitilde{} (tilde)@\spxentry{\textasciitilde{}}\spxextra{tilde}!演算子@\spxentry{演算子}}\ignorespaces The unary \sphinxcode{\sphinxupquote{\textasciitilde{}}} (invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion of \sphinxcode{\sphinxupquote{x}} is defined as \sphinxcode{\sphinxupquote{\sphinxhyphen{}(x+1)}}. It only applies to integral numbers or to custom objects that override the {\hyperref[\detokenize{reference/datamodel:object.__invert__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_invert\_\_()}}}}} special method. \index{例外@\spxentry{例外}!TypeError@\spxentry{TypeError}}\index{TypeError@\spxentry{TypeError}!例外@\spxentry{例外}}\ignorespaces 上記の三つはいずれも、引数が正しい型でない場合には \sphinxcode{\sphinxupquote{TypeError}} 例外が送出されます。 \section{二項算術演算 (binary arithmetic operation)} \label{\detokenize{reference/expressions:binary-arithmetic-operations}}\label{\detokenize{reference/expressions:binary}} \index{binary@\spxentry{binary}!arithmetic operation@\spxentry{arithmetic} \spxentry{operation}}\index{arithmetic@\spxentry{arithmetic}!operation, binary@\spxentry{operation}, \spxentry{binary}}\index{operation@\spxentry{operation}!binary arithmetic@\spxentry{binary} \spxentry{arithmetic}}\ignorespaces 二項算術演算は、慣習的な優先順位を踏襲しています。演算子のいずれかは、特定の非数値型にも適用されるので注意してください。べき乗 (power) 演算子を除き、演算子には二つのレベル、すなわち乗算的 (multiplicatie) 演算子と加算的 (additie) 演算子しかありません: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-m_expr}}\production{m\_expr}{ {\hyperref[\detokenize{reference/expressions:grammar-token-u-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{u\_expr}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-m-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{m\_expr}}}}} "*" {\hyperref[\detokenize{reference/expressions:grammar-token-u-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{u\_expr}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-m-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{m\_expr}}}}} "@" {\hyperref[\detokenize{reference/expressions:grammar-token-m-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{m\_expr}}}}} |} \productioncont{ {\hyperref[\detokenize{reference/expressions:grammar-token-m-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{m\_expr}}}}} "//" {\hyperref[\detokenize{reference/expressions:grammar-token-u-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{u\_expr}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-m-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{m\_expr}}}}} "/" {\hyperref[\detokenize{reference/expressions:grammar-token-u-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{u\_expr}}}}} |} \productioncont{ {\hyperref[\detokenize{reference/expressions:grammar-token-m-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{m\_expr}}}}} "\%" {\hyperref[\detokenize{reference/expressions:grammar-token-u-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{u\_expr}}}}}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-a_expr}}\production{a\_expr}{ {\hyperref[\detokenize{reference/expressions:grammar-token-m-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{m\_expr}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-a-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{a\_expr}}}}} "+" {\hyperref[\detokenize{reference/expressions:grammar-token-m-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{m\_expr}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-a-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{a\_expr}}}}} "\sphinxhyphen{}" {\hyperref[\detokenize{reference/expressions:grammar-token-m-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{m\_expr}}}}}} \end{productionlist} \index{multiplication@\spxentry{multiplication}}\index{演算子@\spxentry{演算子}!* (asterisk)@\spxentry{*}\spxextra{asterisk}}\index{* (asterisk)@\spxentry{*}\spxextra{asterisk}!演算子@\spxentry{演算子}}\ignorespaces \sphinxcode{\sphinxupquote{*}} (乗算: multiplication) 演算子は、引数同士の積を与えます。引数は、両方とも数値であるか、片方が整数で他方がシーケンスかのどちらかでなければなりません。前者の場合、数値は共通の型に変換された後乗算されます。後者の場合、シーケンスの繰り返し操作が行われます。繰り返し数を負にすると、空のシーケンスを与えます。 This operation can be customized using the special {\hyperref[\detokenize{reference/datamodel:object.__mul__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_mul\_\_()}}}}} and {\hyperref[\detokenize{reference/datamodel:object.__rmul__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_rmul\_\_()}}}}} methods. \index{matrix multiplication@\spxentry{matrix multiplication}}\index{演算子@\spxentry{演算子}!"@ (at)@\spxentry{"@}\spxextra{at}}\index{"@ (at)@\spxentry{"@}\spxextra{at}!演算子@\spxentry{演算子}}\ignorespaces \sphinxcode{\sphinxupquote{@}} (at) 演算子は行列の乗算に対し使用されます。 Python の組み込み型はこの演算子を実装していません。 \DUrole{versionmodified,added}{バージョン 3.5 で追加.} \index{例外@\spxentry{例外}!ZeroDivisionError@\spxentry{ZeroDivisionError}}\index{ZeroDivisionError@\spxentry{ZeroDivisionError}!例外@\spxentry{例外}}\index{division@\spxentry{division}}\index{演算子@\spxentry{演算子}!/ (slash)@\spxentry{/}\spxextra{slash}}\index{/ (slash)@\spxentry{/}\spxextra{slash}!演算子@\spxentry{演算子}}\index{演算子@\spxentry{演算子}!//@\spxentry{//}}\index{//@\spxentry{//}!演算子@\spxentry{演算子}}\ignorespaces \sphinxcode{\sphinxupquote{/}} (除算: division) および \sphinxcode{\sphinxupquote{//}} (切り捨て除算: floor division) は、引数同士の商を与えます。数値引数はまず共通の型に変換されます。整数の除算結果は浮動小数点になりますが、整数の切り捨て除算結果は整数になります; この場合、結果は数学的な除算に 'floor' 関数 を適用したものになります。ゼロによる除算を行うと \sphinxcode{\sphinxupquote{ZeroDivisionError}} 例外を送出します。 This operation can be customized using the special {\hyperref[\detokenize{reference/datamodel:object.__truediv__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_truediv\_\_()}}}}} and {\hyperref[\detokenize{reference/datamodel:object.__floordiv__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_floordiv\_\_()}}}}} methods. \index{modulo@\spxentry{modulo}}\index{演算子@\spxentry{演算子}!\% (percent)@\spxentry{\%}\spxextra{percent}}\index{\% (percent)@\spxentry{\%}\spxextra{percent}!演算子@\spxentry{演算子}}\ignorespaces \sphinxcode{\sphinxupquote{\%}} (剰余: modulo) 演算は、第一引数を第二引数で除算したときの剰余になります。数値引数はまず共通の型に変換されます。右引数値がゼロの場合には \sphinxcode{\sphinxupquote{ZeroDivisionError}} 例外が送出されます。引数値は浮動小数点でもよく。例えば \sphinxcode{\sphinxupquote{3.14\%0.7}} は \sphinxcode{\sphinxupquote{0.34}} になります (\sphinxcode{\sphinxupquote{3.14}} は \sphinxcode{\sphinxupquote{4*0.7 + 0.34}} だからです)。剰余演算子は常に第二引数と同じ符号 (またはゼロ) の結果になります; 剰余演算の結果の絶対値は、常に第二引数の絶対値よりも小さくなります。 % \begin{footnote}[1]\sphinxAtStartFootnote \sphinxcode{\sphinxupquote{abs(x\%y) < abs(y)}} は数学的には真となりますが、浮動小数点に対する演算の場合には、値丸め (roundoff) のために数値計算的に真にならない場合があります。例えば、Python の浮動小数点型が IEEE754 倍精度数型になっているプラットフォームを仮定すると、 \sphinxcode{\sphinxupquote{\sphinxhyphen{}1e\sphinxhyphen{}100 \% 1e100}} は \sphinxcode{\sphinxupquote{1e100}} と同じ符号になるはずなのに、計算結果は \sphinxcode{\sphinxupquote{\sphinxhyphen{}1e\sphinxhyphen{}100 + 1e100}} となります。これは数値計算的には厳密に \sphinxcode{\sphinxupquote{1e100}} と等価です。関数 \sphinxcode{\sphinxupquote{math.fmod()}} は、最初の引数と符号が一致するような値を返すので、上記の場合には \sphinxcode{\sphinxupquote{\sphinxhyphen{}1e\sphinxhyphen{}100}} を返します。どちらのアプローチが適切かは、アプリケーションに依存します。 % \end{footnote} 切り捨て除算演算と剰余演算は、恒等式: \sphinxcode{\sphinxupquote{x == (x//y)*y + (x\%y)}} の関係にあります。切り捨て除算や剰余はまた、組み込み関数 \sphinxcode{\sphinxupquote{divmod()}}: \sphinxcode{\sphinxupquote{divmod(x, y) == (x//y, x\%y)}} とも関係しています。 % \begin{footnote}[2]\sphinxAtStartFootnote x が y の正確な整数倍に非常に近いと、丸めのために \sphinxcode{\sphinxupquote{x//y}} が \sphinxcode{\sphinxupquote{(x\sphinxhyphen{}x\%y)//y}} よりも 1 だけ大きくなる可能性があります。そのような場合、Python は \sphinxcode{\sphinxupquote{divmod(x,y){[}0{]} * y + x \% y}} が \sphinxcode{\sphinxupquote{x}} に非常に近くなるという関係を保つために、後者の値を返します。 % \end{footnote} 。 \sphinxcode{\sphinxupquote{\%}} 演算子は、数値に対する剰余演算を行うのに加えて、文字列 (string) オブジェクトにオーバーロードされ、旧式の文字列の書式化 (いわゆる補間) を行います。文字列の書式化の構文は Python ライブラリリファレンス \DUrole{xref,std,std-ref}{old\sphinxhyphen{}string\sphinxhyphen{}formatting} 節を参照してください。 The \sphinxstyleemphasis{modulo} operation can be customized using the special {\hyperref[\detokenize{reference/datamodel:object.__mod__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_mod\_\_()}}}}} method. 切り捨て除算演算子、剰余演算子、および \sphinxcode{\sphinxupquote{divmod()}} 関数は、複素数に対しては定義されていません。目的に合うならば、代わりに \sphinxcode{\sphinxupquote{abs()}} を使って浮動小数点に変換してください。 \index{addition@\spxentry{addition}}\index{operator@\spxentry{operator}!+ (plus)@\spxentry{+}\spxextra{plus}}\index{+ (plus)@\spxentry{+}\spxextra{plus}!binary operator@\spxentry{binary operator}}\ignorespaces \sphinxcode{\sphinxupquote{+}} (加算) 演算は、引数同士の和を与えます。引数は双方とも数値型か、双方とも同じ型のシーケンスでなければなりません。前者の場合、数値は共通の型に変換され、加算されます。後者の場合、シーケンスは結合 (concatenate) されます。 This operation can be customized using the special {\hyperref[\detokenize{reference/datamodel:object.__add__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_add\_\_()}}}}} and {\hyperref[\detokenize{reference/datamodel:object.__radd__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_radd\_\_()}}}}} methods. \index{subtraction@\spxentry{subtraction}}\index{operator@\spxentry{operator}!\sphinxhyphen{} (minus)@\spxentry{\sphinxhyphen{}}\spxextra{minus}}\index{\sphinxhyphen{} (minus)@\spxentry{\sphinxhyphen{}}\spxextra{minus}!binary operator@\spxentry{binary operator}}\ignorespaces \sphinxcode{\sphinxupquote{\sphinxhyphen{}}} (減算) 演算は、引数間で減算を行った値を返します。数値引数はまず共通の型に変換されます。 This operation can be customized using the special {\hyperref[\detokenize{reference/datamodel:object.__sub__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_sub\_\_()}}}}} method. \section{シフト演算 (shifting operation)} \label{\detokenize{reference/expressions:shifting-operations}}\label{\detokenize{reference/expressions:shifting}} \index{shifting@\spxentry{shifting}!operation@\spxentry{operation}}\index{operation@\spxentry{operation}!shifting@\spxentry{shifting}}\index{演算子@\spxentry{演算子}!<<@\spxentry{<<}}\index{<<@\spxentry{<<}!演算子@\spxentry{演算子}}\index{演算子@\spxentry{演算子}!>>@\spxentry{>>}}\index{>>@\spxentry{>>}!演算子@\spxentry{演算子}}\ignorespaces シフト演算は、算術演算よりも低い優先順位を持っています: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-shift_expr}}\production{shift\_expr}{ {\hyperref[\detokenize{reference/expressions:grammar-token-a-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{a\_expr}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-shift-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{shift\_expr}}}}} ("<<" | ">>") {\hyperref[\detokenize{reference/expressions:grammar-token-a-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{a\_expr}}}}}} \end{productionlist} これらは整数を引数にとります。引数は共通の型に変換されます。シフト演算は第一引数を、第二引数で与えられたビット数だけ、左または右にビットシフトします。 This operation can be customized using the special {\hyperref[\detokenize{reference/datamodel:object.__lshift__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_lshift\_\_()}}}}} and {\hyperref[\detokenize{reference/datamodel:object.__rshift__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_rshift\_\_()}}}}} methods. \index{例外@\spxentry{例外}!ValueError@\spxentry{ValueError}}\index{ValueError@\spxentry{ValueError}!例外@\spxentry{例外}}\ignorespaces \sphinxstyleemphasis{n} ビットの右シフトは \sphinxcode{\sphinxupquote{pow(2,n)}} による除算として定義されます。\sphinxstyleemphasis{n} ビットの左シフトは \sphinxcode{\sphinxupquote{pow(2,n)}} による乗算として定義されます。 \section{ビット単位演算の二項演算 (binary bitwise operation)} \label{\detokenize{reference/expressions:binary-bitwise-operations}}\label{\detokenize{reference/expressions:bitwise}} \index{binary@\spxentry{binary}!bitwise operation@\spxentry{bitwise} \spxentry{operation}}\index{bitwise@\spxentry{bitwise}!operation, binary@\spxentry{operation}, \spxentry{binary}}\index{operation@\spxentry{operation}!binary bitwise@\spxentry{binary} \spxentry{bitwise}}\ignorespaces 以下の三つのビット単位演算には、それぞれ異なる優先順位レベルがあります: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-and_expr}}\production{and\_expr}{ {\hyperref[\detokenize{reference/expressions:grammar-token-shift-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{shift\_expr}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-and-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{and\_expr}}}}} "\&" {\hyperref[\detokenize{reference/expressions:grammar-token-shift-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{shift\_expr}}}}}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-xor_expr}}\production{xor\_expr}{ {\hyperref[\detokenize{reference/expressions:grammar-token-and-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{and\_expr}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-xor-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{xor\_expr}}}}} "\textasciicircum{}" {\hyperref[\detokenize{reference/expressions:grammar-token-and-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{and\_expr}}}}}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-or_expr}}\production{or\_expr}{ {\hyperref[\detokenize{reference/expressions:grammar-token-xor-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{xor\_expr}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-or-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{or\_expr}}}}} "|" {\hyperref[\detokenize{reference/expressions:grammar-token-xor-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{xor\_expr}}}}}} \end{productionlist} \index{bitwise@\spxentry{bitwise}!and@\spxentry{and}}\index{and@\spxentry{and}!bitwise@\spxentry{bitwise}}\index{演算子@\spxentry{演算子}!\& (ampersand)@\spxentry{\&}\spxextra{ampersand}}\index{\& (ampersand)@\spxentry{\&}\spxextra{ampersand}!演算子@\spxentry{演算子}}\ignorespaces The \sphinxcode{\sphinxupquote{\&}} operator yields the bitwise AND of its arguments, which must be integers or one of them must be a custom object overriding {\hyperref[\detokenize{reference/datamodel:object.__and__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_and\_\_()}}}}} or {\hyperref[\detokenize{reference/datamodel:object.__rand__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_rand\_\_()}}}}} special methods. \index{bitwise@\spxentry{bitwise}!xor@\spxentry{xor}}\index{xor@\spxentry{xor}!bitwise@\spxentry{bitwise}}\index{exclusive@\spxentry{exclusive}!or@\spxentry{or}}\index{or@\spxentry{or}!exclusive@\spxentry{exclusive}}\index{演算子@\spxentry{演算子}!\textasciicircum{} (caret)@\spxentry{\textasciicircum{}}\spxextra{caret}}\index{\textasciicircum{} (caret)@\spxentry{\textasciicircum{}}\spxextra{caret}!演算子@\spxentry{演算子}}\ignorespaces The \sphinxcode{\sphinxupquote{\textasciicircum{}}} operator yields the bitwise XOR (exclusive OR) of its arguments, which must be integers or one of them must be a custom object overriding {\hyperref[\detokenize{reference/datamodel:object.__xor__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_xor\_\_()}}}}} or {\hyperref[\detokenize{reference/datamodel:object.__rxor__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_rxor\_\_()}}}}} special methods. \index{bitwise@\spxentry{bitwise}!or@\spxentry{or}}\index{or@\spxentry{or}!bitwise@\spxentry{bitwise}}\index{inclusive@\spxentry{inclusive}!or@\spxentry{or}}\index{or@\spxentry{or}!inclusive@\spxentry{inclusive}}\index{演算子@\spxentry{演算子}!\textbar{} (vertical bar)@\spxentry{\textbar{}}\spxextra{vertical bar}}\index{\textbar{} (vertical bar)@\spxentry{\textbar{}}\spxextra{vertical bar}!演算子@\spxentry{演算子}}\ignorespaces The \sphinxcode{\sphinxupquote{|}} operator yields the bitwise (inclusive) OR of its arguments, which must be integers or one of them must be a custom object overriding {\hyperref[\detokenize{reference/datamodel:object.__or__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_or\_\_()}}}}} or {\hyperref[\detokenize{reference/datamodel:object.__ror__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_ror\_\_()}}}}} special methods. \section{比較} \label{\detokenize{reference/expressions:comparisons}}\label{\detokenize{reference/expressions:id11}} \index{comparison@\spxentry{comparison}}\index{C@\spxentry{C}!language@\spxentry{language}}\index{language@\spxentry{language}!C@\spxentry{C}}\index{演算子@\spxentry{演算子}!< (less)@\spxentry{<}\spxextra{less}}\index{< (less)@\spxentry{<}\spxextra{less}!演算子@\spxentry{演算子}}\index{演算子@\spxentry{演算子}!> (greater)@\spxentry{>}\spxextra{greater}}\index{> (greater)@\spxentry{>}\spxextra{greater}!演算子@\spxentry{演算子}}\index{演算子@\spxentry{演算子}!<=@\spxentry{<=}}\index{<=@\spxentry{<=}!演算子@\spxentry{演算子}}\index{演算子@\spxentry{演算子}!>=@\spxentry{>=}}\index{>=@\spxentry{>=}!演算子@\spxentry{演算子}}\index{演算子@\spxentry{演算子}!==@\spxentry{==}}\index{==@\spxentry{==}!演算子@\spxentry{演算子}}\index{演算子@\spxentry{演算子}!"!=@\spxentry{"!=}}\index{"!=@\spxentry{"!=}!演算子@\spxentry{演算子}}\ignorespaces C 言語と違って、Python における比較演算子は同じ優先順位をもっており、全ての算術演算子、シフト演算子、ビット単位演算子よりも低くなっています。また \sphinxcode{\sphinxupquote{a < b < c}} が数学で伝統的に用いられているのと同じ解釈になる点も C 言語と違います: \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-comparison}}\production{comparison}{ {\hyperref[\detokenize{reference/expressions:grammar-token-or-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{or\_expr}}}}} ({\hyperref[\detokenize{reference/expressions:grammar-token-comp-operator}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{comp\_operator}}}}} {\hyperref[\detokenize{reference/expressions:grammar-token-or-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{or\_expr}}}}})*} \phantomsection\label{\detokenize{reference/expressions:grammar-token-comp_operator}}\production{comp\_operator}{ "<" | ">" | "==" | ">=" | "<=" | "!="} \productioncont{ | "is" {[}"not"{]} | {[}"not"{]} "in"} \end{productionlist} Comparisons yield boolean values: \sphinxcode{\sphinxupquote{True}} or \sphinxcode{\sphinxupquote{False}}. Custom \sphinxstyleemphasis{rich comparison methods} may return non\sphinxhyphen{}boolean values. In this case Python will call \sphinxcode{\sphinxupquote{bool()}} on such value in boolean contexts. \index{chaining@\spxentry{chaining}!comparisons@\spxentry{comparisons}}\index{comparisons@\spxentry{comparisons}!chaining@\spxentry{chaining}}\ignorespaces 比較はいくらでも連鎖することができます。例えば \sphinxcode{\sphinxupquote{x < y <= z}} は \sphinxcode{\sphinxupquote{x < y and y <= z}} と等価になります。ただしこの場合、前者では \sphinxcode{\sphinxupquote{y}} はただ一度だけ評価される点が異なります (どちらの場合でも、 \sphinxcode{\sphinxupquote{x < y}} が偽になると \sphinxcode{\sphinxupquote{z}} の値はまったく評価されません)。 形式的には、 \sphinxstyleemphasis{a}, \sphinxstyleemphasis{b}, \sphinxstyleemphasis{c}, ..., \sphinxstyleemphasis{y}, \sphinxstyleemphasis{z} が式で \sphinxstyleemphasis{op1}, \sphinxstyleemphasis{op2}, ..., \sphinxstyleemphasis{opN} が比較演算子である場合、 \sphinxcode{\sphinxupquote{a op1 b op2 c ... y opN z}} は \sphinxcode{\sphinxupquote{a op1 b and b op2 c and ... y opN z}} と等価になります。ただし、前者では各式は多くても一度しか評価されません。 \sphinxcode{\sphinxupquote{a op1 b op2 c}} と書いた場合、 \sphinxstyleemphasis{a} から \sphinxstyleemphasis{c} までの範囲にあるかどうかのテストを指すのではないことに注意してください。例えば \sphinxcode{\sphinxupquote{x < y > z}} は (きれいな書き方ではありませんが) 完全に正しい文法です。 \subsection{値の比較} \label{\detokenize{reference/expressions:value-comparisons}} 演算子 \sphinxcode{\sphinxupquote{<}}, \sphinxcode{\sphinxupquote{>}}, \sphinxcode{\sphinxupquote{==}}, \sphinxcode{\sphinxupquote{>=}}, \sphinxcode{\sphinxupquote{<=}}, および \sphinxcode{\sphinxupquote{!=}} は2つのオブジェクトの値を比較します。 オブジェクトが同じ型を持つ必要はりません。 {\hyperref[\detokenize{reference/datamodel:objects}]{\sphinxcrossref{\DUrole{std,std-ref}{オブジェクト、値、および型}}}} の章では、オブジェクトは (型や id に加えて) 値を持つことを述べています。 オブジェクトの値は Python ではやや抽象的な概念です: 例えば、オブジェクトの値にアクセスする正統な方法はありません。 また、その全てのデータ属性から構成されるなどの特定の方法で、オブジェクトの値を構築する必要性もありません。 比較演算子は、オブジェクトの値とは何かについての特定の概念を実装しています。 この比較の実装によって、間接的にオブジェクトの値を定義していると考えることもできます。 全ての型は (直接的あるいは間接的に) \sphinxcode{\sphinxupquote{object}} のサブクラスとなっているので、デフォルトの比較の振る舞いを \sphinxcode{\sphinxupquote{object}} から継承しています。 {\hyperref[\detokenize{reference/datamodel:customization}]{\sphinxcrossref{\DUrole{std,std-ref}{基本的なカスタマイズ}}}} で解説されているように、型を使って \sphinxstyleemphasis{rich comparison methods} である {\hyperref[\detokenize{reference/datamodel:object.__lt__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_lt\_\_()}}}}} などのメソッドを実装することで、 比較の振る舞いをカスタマイズできます。 等価比較 (\sphinxcode{\sphinxupquote{==}} および \sphinxcode{\sphinxupquote{!=}}) のデフォルトの振る舞いは、オブジェクトの同一性に基づいています。 従って、同一のインスタンスの等価比較の結果は等しいとなり、同一でないインスタンスの等価比較の結果は等しくないとなります。 デフォルトの振る舞いをこのようにしたのは、全てのオブジェクトを反射的 (reflexive つまり \sphinxcode{\sphinxupquote{x is y}} ならば \sphinxcode{\sphinxupquote{x == y}}) なものにしたかったからです。 デフォルトの順序比較 (\sphinxcode{\sphinxupquote{<}}, \sphinxcode{\sphinxupquote{>}}, \sphinxcode{\sphinxupquote{<=}}, \sphinxcode{\sphinxupquote{>=}}) は提供されません; 比較しようとすると \sphinxcode{\sphinxupquote{TypeError}} が送出されます。 この振る舞いをデフォルトの振る舞いにした動機は、等価性と同じような不変性が欠けているからです。 同一でないインスタンスは常に等価でないとする等価比較のデフォルトの振る舞いは、型が必要とするオブジェクトの値や値に基づいた等価性の実用的な定義とは対照的に思えるでしょう。 そのような型では比較の振る舞いをカスタマイズする必要が出てきて、実際にたくさんの組み込み型でそれが行われています。 次のリストでは、最重要の組み込み型の比較の振る舞いを解説しています。 \begin{itemize} \item {} いくつかの組み込みの数値型 (\DUrole{xref,std,std-ref}{typesnumeric}) と標準ライブラリの型 \sphinxcode{\sphinxupquote{fractions.Fraction}} および \sphinxcode{\sphinxupquote{decimal.Decimal}} は、これらの型の範囲で異なる型とも比較できますが、複素数では順序比較がサポートされていないという制限があります。 関わる型の制限の範囲内では、精度のロス無しに数学的に (アルゴリズム的に) 正しい比較が行われます。 非数値である \sphinxcode{\sphinxupquote{float('NaN')}} と \sphinxcode{\sphinxupquote{decimal.Decimal('NaN')}} は特別です。 数と非数値との任意の順序比較は偽です。 直観に反する帰結として、非数値は自分自身と等価ではないことになります。 例えば \sphinxcode{\sphinxupquote{x = float('NaN')}} ならば、 \sphinxcode{\sphinxupquote{3 < x}}, \sphinxcode{\sphinxupquote{x < 3}}, \sphinxcode{\sphinxupquote{x == x}} は全て偽で、\sphinxcode{\sphinxupquote{x != x}} は真です。 この振る舞いは IEEE 754 に従ったものです。 \item {} \sphinxcode{\sphinxupquote{None}} and \sphinxcode{\sphinxupquote{NotImplemented}} are singletons. \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 8@\spxentry{PEP 8}}\sphinxhref{https://www.python.org/dev/peps/pep-0008}{\sphinxstylestrong{PEP 8}} advises that comparisons for singletons should always be done with \sphinxcode{\sphinxupquote{is}} or \sphinxcode{\sphinxupquote{is not}}, never the equality operators. \item {} バイナリシーケンス (\sphinxcode{\sphinxupquote{bytes}} または \sphinxcode{\sphinxupquote{bytearray}} のインスタンス) は、これらの型の範囲で異なる型とも比較できます。 比較は要素の数としての値を使った辞書式順序で行われます。 \item {} 文字列 (\sphinxcode{\sphinxupquote{str}} のインスタンス) の比較は、文字の Unicode のコードポイントの数としての値 (組み込み関数 \sphinxcode{\sphinxupquote{ord()}} の返り値) を使った辞書式順序で行われます。 % \begin{footnote}[3]\sphinxAtStartFootnote Unicode 標準では、 \sphinxstyleemphasis{コードポイント (code point)} (例えば、U+0041) と \sphinxstyleemphasis{抽象文字 (abstract character)} (例えば、"LATIN CAPITAL LETTER A") を区別します。 Unicode のほとんどの抽象文字は 1 つのコードポイントだけを使って表現されますが、複数のコードポイントの列を使っても表現できる抽象文字もたくさんあります。 例えば、抽象文字 "LATIN CAPITAL LETTER C WITH CEDILLA" はコード位置 U+00C7 にある \sphinxstyleemphasis{合成済み文字 (precomposed character)} 1 つだけでも表現できますし、コード位置 U+0043 (LATIN CAPITAL LETTER C) にある \sphinxstyleemphasis{基底文字 (base character)} の後ろに、コード位置 U+0327 (COMBINING CEDILLA) にある \sphinxstyleemphasis{結合文字 (combining character)} が続く列としても表現できます。 文字列の比較操作は Unicode のコードポイントのレベルで行われます。 これは人間にとっては直感的ではないかもしれません。 例えば、 \sphinxcode{\sphinxupquote{"\textbackslash{}u00C7" == "\textbackslash{}u0043\textbackslash{}u0327"}} は、どちらの文字も同じ抽象文字 "LATIN CAPITAL LETTER C WITH CEDILLA" を表現しているにもかかわらず、その結果は \sphinxcode{\sphinxupquote{False}} となります。 抽象文字のレベルで (つまり、人間にとって直感的な方法で) 文字列を比較するには \sphinxcode{\sphinxupquote{unicodedata.normalize()}} を使ってください。 % \end{footnote} 文字列とバイナリシーケンスは直接には比較できません。 \item {} シーケンス (\sphinxcode{\sphinxupquote{tuple}}, \sphinxcode{\sphinxupquote{list}}, or \sphinxcode{\sphinxupquote{range}} のインスタンス) の比較は、同じ型どうしでしか行えず、 range は順序比較をサポートしていません。 異なる型どうしの等価比較の結果は等価でないとなり、異なる型どうしの順序比較は \sphinxcode{\sphinxupquote{TypeError}} を送出します。 Sequences compare lexicographically using comparison of corresponding elements. The built\sphinxhyphen{}in containers typically assume identical objects are equal to themselves. That lets them bypass equality tests for identical objects to improve performance and to maintain their internal invariants. 組み込みのコレクションどうしの辞書式比較は次のように動作します: \begin{itemize} \item {} 比較の結果が等価となる2つのコレクションは、同じ型、同じ長さ、対応する要素どうしの比較の結果が等価でなければなりません (例えば、 \sphinxcode{\sphinxupquote{{[}1,2{]} == (1,2)}} は型が同じでないので偽です)。 \item {} 順序比較をサポートしているコレクションの順序は、最初の等価でない要素の順序と同じになります (例えば、 \sphinxcode{\sphinxupquote{{[}1,2,x{]} <= {[}1,2,y{]}}} は \sphinxcode{\sphinxupquote{x <= y}} と同じ値になります)。 対応する要素が存在しない場合、短い方のコレクションの方が先の順序となります (例えば、 \sphinxcode{\sphinxupquote{{[}1,2{]} < {[}1,2,3{]}}} は真です)。 \end{itemize} \item {} マッピング (\sphinxcode{\sphinxupquote{dict}} のインスタンス) の比較の結果が等価となるのは、同じ \sphinxtitleref{(key, value)} を持っているときかつそのときに限ります。 キーと値の等価比較では反射性が強制されます。 順序比較 (\sphinxcode{\sphinxupquote{<}}, \sphinxcode{\sphinxupquote{>}}, \sphinxcode{\sphinxupquote{<=}}, \sphinxcode{\sphinxupquote{>=}}) は \sphinxcode{\sphinxupquote{TypeError}} を送出します。 \item {} 集合 (\sphinxcode{\sphinxupquote{set}} または \sphinxcode{\sphinxupquote{frozenset}} のインスタンス) の比較は、これらの型の範囲で異なる型とも行えます。 集合には、部分集合あるいは上位集合かどうかを基準とする順序比較が定義されています。 この関係は全順序を定義しません (例えば、 \sphinxcode{\sphinxupquote{\{1,2\}}} と \sphinxcode{\sphinxupquote{\{2,3\}}} という2つの集合は片方がもう一方の部分集合でもなく上位集合でもありません)。 従って、集合は全順序性に依存する関数の引数として適切ではありません (例えば、 \sphinxcode{\sphinxupquote{min()}}, \sphinxcode{\sphinxupquote{max()}}, \sphinxcode{\sphinxupquote{sorted()}} は集合のリストを入力として与えると未定義な結果となります)。 集合の比較では、その要素の反射性が強制されます。 \item {} 他の組み込み型のほとんどは比較メソッドが実装されておらず、デフォルトの比較の振る舞いを継承します。 \end{itemize} 比較の振る舞いをカスタマイズしたユーザ定義クラスは、可能なら次の一貫性の規則に従う必要があります: \begin{itemize} \item {} 等価比較は反射的でなければなりません。 つまり、同一のオブジェクトは等しくなければなりません: \begin{quote} \sphinxcode{\sphinxupquote{x is y}} ならば \sphinxcode{\sphinxupquote{x == y}} \end{quote} \item {} 比較は対称的でなければなりません。 つまり、以下の式の結果は同じでなければなりません: \begin{quote} \sphinxcode{\sphinxupquote{x == y}} と \sphinxcode{\sphinxupquote{y == x}} \sphinxcode{\sphinxupquote{x != y}} と \sphinxcode{\sphinxupquote{y != x}} \sphinxcode{\sphinxupquote{x < y}} と \sphinxcode{\sphinxupquote{y > x}} \sphinxcode{\sphinxupquote{x <= y}} と \sphinxcode{\sphinxupquote{y >= x}} \end{quote} \item {} 比較は推移的でなければなりません。 以下の (包括的でない) 例がその説明です: \begin{quote} \sphinxcode{\sphinxupquote{x > y and y > z}} ならば \sphinxcode{\sphinxupquote{x > z}} \sphinxcode{\sphinxupquote{x < y and y <= z}} ならば \sphinxcode{\sphinxupquote{x < z}} \end{quote} \item {} 比較の逆は真偽値の否定でなければなりません。 つまり、以下の式の結果は同じでなければなりません: \begin{quote} \sphinxcode{\sphinxupquote{x == y}} と \sphinxcode{\sphinxupquote{not x != y}} \sphinxcode{\sphinxupquote{x < y}} と \sphinxcode{\sphinxupquote{not x >= y}} (全順序の場合) \sphinxcode{\sphinxupquote{x > y}} と \sphinxcode{\sphinxupquote{not x <= y}} (全順序の場合) \end{quote} 最後の2式は全順序コレクションに当てはまります (たとえばシーケンスには当てはまりますが、集合やマッピングには当てはまりません)。 \sphinxcode{\sphinxupquote{total\_ordering()}} デコレータも参照してください。 \item {} \sphinxcode{\sphinxupquote{hash()}} の結果は等価性と一貫している必要があります。 等価なオブジェクトどうしは同じハッシュ値を持つか、ハッシュ値が計算できないものとされる必要があります。 \end{itemize} Python はこの一貫性規則を強制しません。 事実、非数値がこの規則に従わない例となります。 \subsection{所属検査演算} \label{\detokenize{reference/expressions:membership-test-operations}}\label{\detokenize{reference/expressions:membership-test-details}}\label{\detokenize{reference/expressions:not-in}}\label{\detokenize{reference/expressions:in}} 演算子 {\hyperref[\detokenize{reference/expressions:in}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{in}}}}} および {\hyperref[\detokenize{reference/expressions:not-in}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{not in}}}}} は所属関係を調べます。 \sphinxcode{\sphinxupquote{x in s}} の評価は、 \sphinxstyleemphasis{x} が \sphinxstyleemphasis{s} の要素であれば \sphinxcode{\sphinxupquote{True}} となり、そうでなければ \sphinxcode{\sphinxupquote{False}} となります。 \sphinxcode{\sphinxupquote{x not in s}} は \sphinxcode{\sphinxupquote{x in s}} の否定を返します。 すべての組み込みのシーケンス型と集合型に加えて、辞書も \sphinxcode{\sphinxupquote{in}} を辞書が与えられたキーを持っているかを調べる演算子としてサポートしています。 リスト、タプル、集合、凍結集合、辞書、 collections.deque のようなコンテナ型において、式 \sphinxcode{\sphinxupquote{x in y}} は \sphinxcode{\sphinxupquote{any(x is e or x == e for e in y)}} と等価です。 文字列やバイト列型については、 \sphinxcode{\sphinxupquote{x in y}} は \sphinxstyleemphasis{x} が \sphinxstyleemphasis{y} の部分文字列であるとき、かつそのときに限り \sphinxcode{\sphinxupquote{True}} になります。これは \sphinxcode{\sphinxupquote{y.find(x) != \sphinxhyphen{}1}} と等価です。空文字列は、他の任意の文字列の部分文字列とみなされます。従って \sphinxcode{\sphinxupquote{"" in "abc"}} は \sphinxcode{\sphinxupquote{True}} を返すことになります。 {\hyperref[\detokenize{reference/datamodel:object.__contains__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_contains\_\_()}}}}} メソッドを実装したユーザ定義クラスでは、 \sphinxcode{\sphinxupquote{y.\_\_contains\_\_(x)}} の返り値が真となる場合に \sphinxcode{\sphinxupquote{x in y}} の返り値は \sphinxcode{\sphinxupquote{True}} となり、そうでない場合は \sphinxcode{\sphinxupquote{False}} となります。 For user\sphinxhyphen{}defined classes which do not define {\hyperref[\detokenize{reference/datamodel:object.__contains__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_contains\_\_()}}}}} but do define {\hyperref[\detokenize{reference/datamodel:object.__iter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_iter\_\_()}}}}}, \sphinxcode{\sphinxupquote{x in y}} is \sphinxcode{\sphinxupquote{True}} if some value \sphinxcode{\sphinxupquote{z}}, for which the expression \sphinxcode{\sphinxupquote{x is z or x == z}} is true, is produced while iterating over \sphinxcode{\sphinxupquote{y}}. If an exception is raised during the iteration, it is as if {\hyperref[\detokenize{reference/expressions:in}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{in}}}}} raised that exception. Lastly, the old\sphinxhyphen{}style iteration protocol is tried: if a class defines {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}}, \sphinxcode{\sphinxupquote{x in y}} is \sphinxcode{\sphinxupquote{True}} if and only if there is a non\sphinxhyphen{}negative integer index \sphinxstyleemphasis{i} such that \sphinxcode{\sphinxupquote{x is y{[}i{]} or x == y{[}i{]}}}, and no lower integer index raises the \sphinxcode{\sphinxupquote{IndexError}} exception. (If any other exception is raised, it is as if {\hyperref[\detokenize{reference/expressions:in}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{in}}}}} raised that exception). \index{演算子@\spxentry{演算子}!in@\spxentry{in}}\index{in@\spxentry{in}!演算子@\spxentry{演算子}}\index{演算子@\spxentry{演算子}!not in@\spxentry{not in}}\index{not in@\spxentry{not in}!演算子@\spxentry{演算子}}\index{membership@\spxentry{membership}!test@\spxentry{test}}\index{test@\spxentry{test}!membership@\spxentry{membership}}\index{オブジェクト@\spxentry{オブジェクト}!sequence@\spxentry{sequence}}\index{sequence@\spxentry{sequence}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces 演算子 {\hyperref[\detokenize{reference/expressions:not-in}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{not in}}}}} は {\hyperref[\detokenize{reference/expressions:in}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{in}}}}} の真理値を反転した値として定義されています。 \index{演算子@\spxentry{演算子}!is@\spxentry{is}}\index{is@\spxentry{is}!演算子@\spxentry{演算子}}\index{演算子@\spxentry{演算子}!is not@\spxentry{is not}}\index{is not@\spxentry{is not}!演算子@\spxentry{演算子}}\index{identity@\spxentry{identity}!test@\spxentry{test}}\index{test@\spxentry{test}!identity@\spxentry{identity}}\ignorespaces \subsection{同一性の比較} \label{\detokenize{reference/expressions:is-not}}\label{\detokenize{reference/expressions:is}}\label{\detokenize{reference/expressions:index-81}}\label{\detokenize{reference/expressions:identity-comparisons}} 演算子 {\hyperref[\detokenize{reference/expressions:is}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{is}}}}} および {\hyperref[\detokenize{reference/expressions:is-not}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{is not}}}}} は、オブジェクトの同一性に対するテストを行います: \sphinxcode{\sphinxupquote{x is y}} は、 \sphinxstyleemphasis{x} と \sphinxstyleemphasis{y} が同じオブジェクトを指すとき、かつそのときに限り真になります。 オブジェクトの同一性は \sphinxcode{\sphinxupquote{id()}} 関数を使って判定されます。 \sphinxcode{\sphinxupquote{x is not y}} は {\hyperref[\detokenize{reference/expressions:is}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{is}}}}} の真値を反転したものになります。 % \begin{footnote}[4]\sphinxAtStartFootnote 自動的なガベージコレクション、フリーリスト、ディスクリプタの動的特性のために、インスタンスメソッドや定数の比較を行うようなときに {\hyperref[\detokenize{reference/expressions:is}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{is}}}}} 演算子の利用は、一見すると普通ではない振る舞いだと気付くかもしれません。詳細はそれぞれのドキュメントを確認してください。 % \end{footnote} \section{ブール演算 (boolean operation)} \label{\detokenize{reference/expressions:boolean-operations}}\label{\detokenize{reference/expressions:not}}\label{\detokenize{reference/expressions:or}}\label{\detokenize{reference/expressions:and}}\label{\detokenize{reference/expressions:booleans}} \index{Conditional@\spxentry{Conditional}!expression@\spxentry{expression}}\index{expression@\spxentry{expression}!Conditional@\spxentry{Conditional}}\index{Boolean@\spxentry{Boolean}!operation@\spxentry{operation}}\index{operation@\spxentry{operation}!Boolean@\spxentry{Boolean}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-or_test}}\production{or\_test}{ {\hyperref[\detokenize{reference/expressions:grammar-token-and-test}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{and\_test}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-or-test}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{or\_test}}}}} "or" {\hyperref[\detokenize{reference/expressions:grammar-token-and-test}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{and\_test}}}}}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-and_test}}\production{and\_test}{ {\hyperref[\detokenize{reference/expressions:grammar-token-not-test}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{not\_test}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-and-test}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{and\_test}}}}} "and" {\hyperref[\detokenize{reference/expressions:grammar-token-not-test}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{not\_test}}}}}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-not_test}}\production{not\_test}{ {\hyperref[\detokenize{reference/expressions:grammar-token-comparison}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{comparison}}}}} | "not" {\hyperref[\detokenize{reference/expressions:grammar-token-not-test}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{not\_test}}}}}} \end{productionlist} ブール演算のコンテキストや、式が制御フローの文で使われる際には、次の値は偽だと解釈されます: \sphinxcode{\sphinxupquote{False}} 、 \sphinxcode{\sphinxupquote{None}} 、すべての型における数値の 0、空の文字列、空のコンテナ (文字列、タプル、リスト、辞書、集合、凍結集合など)。 それ以外の値は真だと解釈されます。 ユーザ定義のオブジェクトは、 {\hyperref[\detokenize{reference/datamodel:object.__bool__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_bool\_\_()}}}}} メソッドを与えることで、真偽値をカスタマイズできます。 \index{演算子@\spxentry{演算子}!not@\spxentry{not}}\index{not@\spxentry{not}!演算子@\spxentry{演算子}}\ignorespaces 演算子 {\hyperref[\detokenize{reference/expressions:not}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{not}}}}} は、引数が偽である場合には \sphinxcode{\sphinxupquote{True}} を、それ以外の場合には \sphinxcode{\sphinxupquote{False}} になります。 \index{演算子@\spxentry{演算子}!and@\spxentry{and}}\index{and@\spxentry{and}!演算子@\spxentry{演算子}}\ignorespaces 式 \sphinxcode{\sphinxupquote{x and y}} は、まず \sphinxstyleemphasis{x} を評価します; \sphinxstyleemphasis{x} が偽なら \sphinxstyleemphasis{x} の値を返します; それ以外の場合には、 \sphinxstyleemphasis{y} の値を評価し、その結果を返します。 \index{演算子@\spxentry{演算子}!or@\spxentry{or}}\index{or@\spxentry{or}!演算子@\spxentry{演算子}}\ignorespaces 式 \sphinxcode{\sphinxupquote{x or y}} は、まず \sphinxstyleemphasis{x} を評価します; \sphinxstyleemphasis{x} が真なら \sphinxstyleemphasis{x} の値を返します; それ以外の場合には、 \sphinxstyleemphasis{y} の値を評価し、その結果を返します。 なお、 {\hyperref[\detokenize{reference/expressions:and}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{and}}}}} も {\hyperref[\detokenize{reference/expressions:or}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{or}}}}} も、返す値を \sphinxcode{\sphinxupquote{True}} や \sphinxcode{\sphinxupquote{False}} に制限せず、最後に評価した引数を返します。 この仕様が便利なときもあります。例えば \sphinxcode{\sphinxupquote{s}} が文字列で、空文字列ならデフォルトの値に置き換えたいとき、式 \sphinxcode{\sphinxupquote{s or 'foo'}} は望んだ値を与えます。 {\hyperref[\detokenize{reference/expressions:not}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{not}}}}} は必ず新しい値を作成するので、引数の型に関係なくブール値を返します (例えば、 \sphinxcode{\sphinxupquote{not 'foo'}} は \sphinxcode{\sphinxupquote{''}} ではなく \sphinxcode{\sphinxupquote{False}} になります)。 \section{代入式} \label{\detokenize{reference/expressions:assignment-expressions}} \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-assignment_expression}}\production{assignment\_expression}{ {[}{\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}} ":="{]} {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}} \end{productionlist} An assignment expression (sometimes also called a "named expression" or "walrus") assigns an {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} to an {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}, while also returning the value of the {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}. One common use case is when handling matched regular expressions: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{if} \PYG{n}{matching} \PYG{o}{:=} \PYG{n}{pattern}\PYG{o}{.}\PYG{n}{search}\PYG{p}{(}\PYG{n}{data}\PYG{p}{)}\PYG{p}{:} \PYG{n}{do\PYGZus{}something}\PYG{p}{(}\PYG{n}{matching}\PYG{p}{)} \end{sphinxVerbatim} Or, when processing a file stream in chunks: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{while} \PYG{n}{chunk} \PYG{o}{:=} \PYG{n}{file}\PYG{o}{.}\PYG{n}{read}\PYG{p}{(}\PYG{l+m+mi}{9000}\PYG{p}{)}\PYG{p}{:} \PYG{n}{process}\PYG{p}{(}\PYG{n}{chunk}\PYG{p}{)} \end{sphinxVerbatim} \DUrole{versionmodified,added}{バージョン 3.8 で追加: }代入式に関してより詳しくは \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 572@\spxentry{PEP 572}}\sphinxhref{https://www.python.org/dev/peps/pep-0572}{\sphinxstylestrong{PEP 572}} を参照してください。 \section{条件式 (Conditional Expressions)} \label{\detokenize{reference/expressions:conditional-expressions}}\label{\detokenize{reference/expressions:if-expr}} \index{conditional@\spxentry{conditional}!expression@\spxentry{expression}}\index{expression@\spxentry{expression}!conditional@\spxentry{conditional}}\index{ternary@\spxentry{ternary}!operator@\spxentry{operator}}\index{operator@\spxentry{operator}!ternary@\spxentry{ternary}}\index{if@\spxentry{if}!conditional expression@\spxentry{conditional expression}}\index{else@\spxentry{else}!conditional expression@\spxentry{conditional expression}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-conditional_expression}}\production{conditional\_expression}{ {\hyperref[\detokenize{reference/expressions:grammar-token-or-test}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{or\_test}}}}} {[}"if" {\hyperref[\detokenize{reference/expressions:grammar-token-or-test}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{or\_test}}}}} "else" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}{]}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-expression}}\production{expression}{ {\hyperref[\detokenize{reference/expressions:grammar-token-conditional-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{conditional\_expression}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-lambda-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{lambda\_expr}}}}}} \end{productionlist} 条件式 (しばしば "三項演算子" と呼ばれます) は最も優先度が低いPython の演算です。 \sphinxcode{\sphinxupquote{x if C else y}} という式は最初に \sphinxstyleemphasis{x} ではなく条件 \sphinxstyleemphasis{C} を評価します。 \sphinxstyleemphasis{C} が true の場合 \sphinxstyleemphasis{x} が評価され値が返されます。 それ以外の場合には \sphinxstyleemphasis{y} が評価され返されます。 条件演算に関してより詳しくは \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 308@\spxentry{PEP 308}}\sphinxhref{https://www.python.org/dev/peps/pep-0308}{\sphinxstylestrong{PEP 308}} を参照してください。 \section{ラムダ (lambda)} \label{\detokenize{reference/expressions:lambda}}\label{\detokenize{reference/expressions:lambdas}}\label{\detokenize{reference/expressions:id14}} \index{lambda@\spxentry{lambda}!expression@\spxentry{expression}}\index{expression@\spxentry{expression}!lambda@\spxentry{lambda}}\index{lambda@\spxentry{lambda}!form@\spxentry{form}}\index{form@\spxentry{form}!lambda@\spxentry{lambda}}\index{anonymous@\spxentry{anonymous}!function@\spxentry{function}}\index{function@\spxentry{function}!anonymous@\spxentry{anonymous}}\index{: (colon)@\spxentry{:}\spxextra{colon}!lambda expression@\spxentry{lambda expression}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-lambda_expr}}\production{lambda\_expr}{ "lambda" {[}{\hyperref[\detokenize{reference/compound_stmts:grammar-token-parameter-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{parameter\_list}}}}}{]} ":" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}} \end{productionlist} ラムダ式 (ラムダ形式とも呼ばれます) は無名関数を作成するのに使います。 式 \sphinxcode{\sphinxupquote{lambda parameters: expression}} は関数オブジェクトになります。 この無名オブジェクトは以下に定義されている関数オブジェクト同様に動作します: \begin{sphinxVerbatim}[commandchars=\\\{\}] def \PYGZlt{}lambda\PYGZgt{}(parameters): return expression \end{sphinxVerbatim} 引数の一覧の構文は {\hyperref[\detokenize{reference/compound_stmts:function}]{\sphinxcrossref{\DUrole{std,std-ref}{関数定義}}}} を参照してください。ラムダ式で作成された関数は文やアノテーションを含むことができない点に注意してください。 \section{式のリスト} \label{\detokenize{reference/expressions:expression-lists}}\label{\detokenize{reference/expressions:exprlists}} \index{expression@\spxentry{expression}!list@\spxentry{list}}\index{list@\spxentry{list}!expression@\spxentry{expression}}\index{, (comma)@\spxentry{,}\spxextra{comma}!expression list@\spxentry{expression list}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/expressions:grammar-token-expression_list}}\production{expression\_list}{ {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} ("," {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}})* {[}","{]}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-starred_list}}\production{starred\_list}{ {\hyperref[\detokenize{reference/expressions:grammar-token-starred-item}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{starred\_item}}}}} ("," {\hyperref[\detokenize{reference/expressions:grammar-token-starred-item}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{starred\_item}}}}})* {[}","{]}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-starred_expression}}\production{starred\_expression}{ {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} | ({\hyperref[\detokenize{reference/expressions:grammar-token-starred-item}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{starred\_item}}}}} ",")* {[}{\hyperref[\detokenize{reference/expressions:grammar-token-starred-item}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{starred\_item}}}}}{]}} \phantomsection\label{\detokenize{reference/expressions:grammar-token-starred_item}}\production{starred\_item}{ {\hyperref[\detokenize{reference/expressions:grammar-token-assignment-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{assignment\_expression}}}}} | "*" {\hyperref[\detokenize{reference/expressions:grammar-token-or-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{or\_expr}}}}}} \end{productionlist} \index{オブジェクト@\spxentry{オブジェクト}!tuple@\spxentry{tuple}}\index{tuple@\spxentry{tuple}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces リスト表示や辞書表示の一部になっているものを除き、少なくとも一つのカンマを含む式のリストはタプルになります。 タプルの長さは、リストにある式の数に等しくなります。 式は左から右へ評価されます。 \index{iterable@\spxentry{iterable}!unpacking@\spxentry{unpacking}}\index{unpacking@\spxentry{unpacking}!iterable@\spxentry{iterable}}\index{* (asterisk)@\spxentry{*}\spxextra{asterisk}!in expression lists@\spxentry{in expression lists}}\ignorespaces アスタリスク \sphinxcode{\sphinxupquote{*}} は \sphinxstyleemphasis{イテラブルのアンパック} を意味します。 この被演算子は {\hyperref[\detokenize{glossary:term-iterable}]{\sphinxtermref{\DUrole{xref,std,std-term}{イテラブル}}}} でなければなりません。 このイテラブルはアンパックされた位置で要素のシーケンスに展開され、新しいタプル、リスト、集合に入れ込まれます。 \DUrole{versionmodified,added}{バージョン 3.5 で追加: }式リストでのイテラブルのアンパックは最初に \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 448@\spxentry{PEP 448}}\sphinxhref{https://www.python.org/dev/peps/pep-0448}{\sphinxstylestrong{PEP 448}} で提案されました。 \index{trailing@\spxentry{trailing}!comma@\spxentry{comma}}\index{comma@\spxentry{comma}!trailing@\spxentry{trailing}}\ignorespaces 単一要素のタプル (別名 \sphinxstyleemphasis{単集合 (singleton)} ) を作りたければ、末尾にカンマが必要です。単一の式だけで、末尾にカンマをつけない場合には、タプルではなくその式の値になります (空のタプルを作りたいなら、中身が空の丸括弧ペア: \sphinxcode{\sphinxupquote{()}} を使います。) \section{評価順序} \label{\detokenize{reference/expressions:evaluation-order}}\label{\detokenize{reference/expressions:evalorder}} \index{evaluation@\spxentry{evaluation}!order@\spxentry{order}}\index{order@\spxentry{order}!evaluation@\spxentry{evaluation}}\ignorespaces Python は、式を左から右へと順に評価します。 ただし、代入式を評価するときは、右辺が左辺よりも先に評価されます。 以下に示す実行文の各行での評価順序は、添え字の数字順序と同じになります: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{expr1}\PYG{p}{,} \PYG{n}{expr2}\PYG{p}{,} \PYG{n}{expr3}\PYG{p}{,} \PYG{n}{expr4} \PYG{p}{(}\PYG{n}{expr1}\PYG{p}{,} \PYG{n}{expr2}\PYG{p}{,} \PYG{n}{expr3}\PYG{p}{,} \PYG{n}{expr4}\PYG{p}{)} \PYG{p}{\PYGZob{}}\PYG{n}{expr1}\PYG{p}{:} \PYG{n}{expr2}\PYG{p}{,} \PYG{n}{expr3}\PYG{p}{:} \PYG{n}{expr4}\PYG{p}{\PYGZcb{}} \PYG{n}{expr1} \PYG{o}{+} \PYG{n}{expr2} \PYG{o}{*} \PYG{p}{(}\PYG{n}{expr3} \PYG{o}{\PYGZhy{}} \PYG{n}{expr4}\PYG{p}{)} \PYG{n}{expr1}\PYG{p}{(}\PYG{n}{expr2}\PYG{p}{,} \PYG{n}{expr3}\PYG{p}{,} \PYG{o}{*}\PYG{n}{expr4}\PYG{p}{,} \PYG{o}{*}\PYG{o}{*}\PYG{n}{expr5}\PYG{p}{)} \PYG{n}{expr3}\PYG{p}{,} \PYG{n}{expr4} \PYG{o}{=} \PYG{n}{expr1}\PYG{p}{,} \PYG{n}{expr2} \end{sphinxVerbatim} \section{演算子の優先順位} \label{\detokenize{reference/expressions:operator-precedence}}\label{\detokenize{reference/expressions:operator-summary}} \index{operator@\spxentry{operator}!precedence@\spxentry{precedence}}\index{precedence@\spxentry{precedence}!operator@\spxentry{operator}}\ignorespaces The following table summarizes the operator precedence in Python, from highest precedence (most binding) to lowest precedence (least binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for exponentiation, which groups from right to left). {\hyperref[\detokenize{reference/expressions:comparisons}]{\sphinxcrossref{\DUrole{std,std-ref}{比較}}}} 節で述べられているように、比較、所属、同一性のテストは全てが同じ優先順位を持っていて、左から右に連鎖するという特徴を持っていることに注意してください。 \begin{savenotes}\sphinxattablestart \centering \begin{tabulary}{\linewidth}[t]{|T|T|} \hline \sphinxstyletheadfamily 演算子 &\sphinxstyletheadfamily 説明 \\ \hline \sphinxcode{\sphinxupquote{(expressions...)}}, \sphinxcode{\sphinxupquote{{[}expressions...{]}}}, \sphinxcode{\sphinxupquote{\{key: value...\}}}, \sphinxcode{\sphinxupquote{\{expressions...\}}} & 結合式または括弧式、リスト表示、辞書表示、集合表示 \\ \hline \sphinxcode{\sphinxupquote{x{[}index{]}}}, \sphinxcode{\sphinxupquote{x{[}index:index{]}}}, \sphinxcode{\sphinxupquote{x(arguments...)}}, \sphinxcode{\sphinxupquote{x.attribute}} & 添字指定、スライス操作、呼び出し、属性参照 \\ \hline {\hyperref[\detokenize{reference/expressions:await}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{await x}}}}} & Await 式 \\ \hline \sphinxcode{\sphinxupquote{**}} & べき乗 % \begin{footnote}[5]\sphinxAtStartFootnote べき乗演算子 \sphinxcode{\sphinxupquote{**}} は、右側にある単項算術演算子あるいは単項ビット演算子より弱い結合優先順位となります。 つまり \sphinxcode{\sphinxupquote{2**\sphinxhyphen{}1}} は \sphinxcode{\sphinxupquote{0.5}} になります。 % \end{footnote} \\ \hline \sphinxcode{\sphinxupquote{+x}}, \sphinxcode{\sphinxupquote{\sphinxhyphen{}x}}, \sphinxcode{\sphinxupquote{\textasciitilde{}x}} & 正数、負数、ビット単位 NOT \\ \hline \sphinxcode{\sphinxupquote{*}}, \sphinxcode{\sphinxupquote{@}}, \sphinxcode{\sphinxupquote{/}}, \sphinxcode{\sphinxupquote{//}}, \sphinxcode{\sphinxupquote{\%}} & 乗算、行列乗算、除算、切り捨て除算、剰余 % \begin{footnote}[6]\sphinxAtStartFootnote \sphinxcode{\sphinxupquote{\%}} 演算子は文字列フォーマットにも使われ、同じ優先順位が当てはまります。 % \end{footnote} \\ \hline \sphinxcode{\sphinxupquote{+}}, \sphinxcode{\sphinxupquote{\sphinxhyphen{}}} & 加算および減算 \\ \hline \sphinxcode{\sphinxupquote{<<}}, \sphinxcode{\sphinxupquote{>>}} & シフト演算 \\ \hline \sphinxcode{\sphinxupquote{\&}} & ビット単位 AND \\ \hline \sphinxcode{\sphinxupquote{\textasciicircum{}}} & ビット単位 XOR \\ \hline \sphinxcode{\sphinxupquote{|}} & ビット単位 OR \\ \hline {\hyperref[\detokenize{reference/expressions:in}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{in}}}}}, {\hyperref[\detokenize{reference/expressions:not-in}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{not in}}}}}, {\hyperref[\detokenize{reference/expressions:is}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{is}}}}}, {\hyperref[\detokenize{reference/expressions:is-not}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{is not}}}}}, \sphinxcode{\sphinxupquote{<}}, \sphinxcode{\sphinxupquote{<=}}, \sphinxcode{\sphinxupquote{>}}, \sphinxcode{\sphinxupquote{>=}}, \sphinxcode{\sphinxupquote{!=}}, \sphinxcode{\sphinxupquote{==}} & 所属や同一性のテストを含む比較 \\ \hline {\hyperref[\detokenize{reference/expressions:not}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{not x}}}}} & ブール演算 NOT \\ \hline {\hyperref[\detokenize{reference/expressions:and}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{and}}}}} & ブール演算 AND \\ \hline {\hyperref[\detokenize{reference/expressions:or}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{or}}}}} & ブール演算 OR \\ \hline {\hyperref[\detokenize{reference/expressions:if-expr}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{if}}}}} \sphinxhyphen{}\sphinxhyphen{} \sphinxcode{\sphinxupquote{else}} & 条件式 \\ \hline {\hyperref[\detokenize{reference/expressions:lambda}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{lambda}}}}} & ラムダ式 \\ \hline \sphinxcode{\sphinxupquote{:=}} & 代入式 \\ \hline \end{tabulary} \par \sphinxattableend\end{savenotes} \subsubsection*{脚注} \chapter{単純文 (simple statement)} \label{\detokenize{reference/simple_stmts:simple-statements}}\label{\detokenize{reference/simple_stmts:simple}}\label{\detokenize{reference/simple_stmts::doc}} \index{simple@\spxentry{simple}!statement@\spxentry{statement}}\index{statement@\spxentry{statement}!simple@\spxentry{simple}}\ignorespaces 単純文とは、単一の論理行内に収められる文です。単一の行内には、複数の単純文をセミコロンで区切って入れることができます。単純文の構文は以下の通りです: \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-simple_stmt}}\production{simple\_stmt}{ {\hyperref[\detokenize{reference/simple_stmts:grammar-token-expression-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-assert-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{assert\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-assignment-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{assignment\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-augmented-assignment-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{augmented\_assignment\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-annotated-assignment-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{annotated\_assignment\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-pass-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{pass\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-del-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{del\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-return-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{return\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-yield-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-raise-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{raise\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-break-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{break\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-continue-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{continue\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-import-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{import\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-future-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{future\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-global-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{global\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/simple_stmts:grammar-token-nonlocal-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{nonlocal\_stmt}}}}}} \end{productionlist} \section{式文 (expression statement)} \label{\detokenize{reference/simple_stmts:expression-statements}}\label{\detokenize{reference/simple_stmts:exprstmts}} \index{expression@\spxentry{expression}!statement@\spxentry{statement}}\index{statement@\spxentry{statement}!expression@\spxentry{expression}}\index{expression@\spxentry{expression}!list@\spxentry{list}}\index{list@\spxentry{list}!expression@\spxentry{expression}}\ignorespaces \index{expression@\spxentry{expression}!list@\spxentry{list}}\index{list@\spxentry{list}!expression@\spxentry{expression}}\ignorespaces 式文は、(主に対話的な使い方では) 値を計算して出力するために使ったり、(通常は) プロシジャ (procedure: 有意な結果を返さない関数のことです; Python では、プロシジャは値 \sphinxcode{\sphinxupquote{None}} を返します) を呼び出すために使います。その他の使い方でも式文を使うことができますし、有用なこともあります。式文の構文は以下の通りです: \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-expression_stmt}}\production{expression\_stmt}{ {\hyperref[\detokenize{reference/expressions:grammar-token-starred-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{starred\_expression}}}}}} \end{productionlist} 式文は式のリスト (単一の式のこともあります) を値評価します。 \index{組み込み関数@\spxentry{組み込み関数}!repr@\spxentry{repr}}\index{repr@\spxentry{repr}!組み込み関数@\spxentry{組み込み関数}}\index{オブジェクト@\spxentry{オブジェクト}!None@\spxentry{None}}\index{None@\spxentry{None}!オブジェクト@\spxentry{オブジェクト}}\index{string@\spxentry{string}!conversion@\spxentry{conversion}}\index{conversion@\spxentry{conversion}!string@\spxentry{string}}\index{output@\spxentry{output}}\index{standard@\spxentry{standard}!output@\spxentry{output}}\index{output@\spxentry{output}!standard@\spxentry{standard}}\index{writing@\spxentry{writing}!values@\spxentry{values}}\index{values@\spxentry{values}!writing@\spxentry{writing}}\index{procedure@\spxentry{procedure}!call@\spxentry{call}}\index{call@\spxentry{call}!procedure@\spxentry{procedure}}\ignorespaces 対話モードでは、値が \sphinxcode{\sphinxupquote{None}} でなければ、値を組み込み関数 \sphinxcode{\sphinxupquote{repr()}} で文字列に変換して、その結果の文字列を標準出力に一行使って書き出します。 (\sphinxcode{\sphinxupquote{None}} になる式文の値は書き出されないので、プロシジャの呼び出しを行っても出力は得られません。) \section{代入文 (assignment statement)} \label{\detokenize{reference/simple_stmts:assignment-statements}}\label{\detokenize{reference/simple_stmts:assignment}} \index{= (equals)@\spxentry{=}\spxextra{equals}!assignment statement@\spxentry{assignment statement}}\index{assignment@\spxentry{assignment}!statement@\spxentry{statement}}\index{statement@\spxentry{statement}!assignment@\spxentry{assignment}}\index{binding@\spxentry{binding}!name@\spxentry{name}}\index{name@\spxentry{name}!binding@\spxentry{binding}}\index{rebinding@\spxentry{rebinding}!name@\spxentry{name}}\index{name@\spxentry{name}!rebinding@\spxentry{rebinding}}\index{オブジェクト@\spxentry{オブジェクト}!mutable@\spxentry{mutable}}\index{mutable@\spxentry{mutable}!オブジェクト@\spxentry{オブジェクト}}\index{attribute@\spxentry{attribute}!assignment@\spxentry{assignment}}\index{assignment@\spxentry{assignment}!attribute@\spxentry{attribute}}\ignorespaces 代入文は、名前を値に (再) 束縛したり、変更可能なオブジェクトの属性や要素を変更したりするために使われます: \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-assignment_stmt}}\production{assignment\_stmt}{ ({\hyperref[\detokenize{reference/simple_stmts:grammar-token-target-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{target\_list}}}}} "=")+ ({\hyperref[\detokenize{reference/expressions:grammar-token-starred-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{starred\_expression}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-yield-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield\_expression}}}}})} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-target_list}}\production{target\_list}{ {\hyperref[\detokenize{reference/simple_stmts:grammar-token-target}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{target}}}}} ("," {\hyperref[\detokenize{reference/simple_stmts:grammar-token-target}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{target}}}}})* {[}","{]}} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-target}}\production{target}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}} \productioncont{ | "(" {[}{\hyperref[\detokenize{reference/simple_stmts:grammar-token-target-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{target\_list}}}}}{]} ")"} \productioncont{ | "{[}" {[}{\hyperref[\detokenize{reference/simple_stmts:grammar-token-target-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{target\_list}}}}}{]} "{]}"} \productioncont{ | {\hyperref[\detokenize{reference/expressions:grammar-token-attributeref}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{attributeref}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/expressions:grammar-token-subscription}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{subscription}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/expressions:grammar-token-slicing}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{slicing}}}}}} \productioncont{ | "*" {\hyperref[\detokenize{reference/simple_stmts:grammar-token-target}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{target}}}}}} \end{productionlist} (\sphinxstyleemphasis{attributeref}, \sphinxstyleemphasis{subscription}, \sphinxstyleemphasis{slicing} の構文については {\hyperref[\detokenize{reference/expressions:primaries}]{\sphinxcrossref{\DUrole{std,std-ref}{プライマリ}}}} 節を参照してください。) 代入文は式のリスト (これは単一の式でも、カンマで区切られた式リストでもよく、後者はタプルになることを思い出してください) を評価し、得られた単一の結果オブジェクトをターゲット (target) のリストに対して左から右へと代入してゆきます。 \index{target@\spxentry{target}}\index{target@\spxentry{target}!list@\spxentry{list}}\index{list@\spxentry{list}!target@\spxentry{target}}\ignorespaces 代入はターゲット (リスト) の形式に従って再帰的に行われます。ターゲットが変更可能なオブジェクト (属性参照、添字表記、またはスライス) の一部である場合、この変更可能なオブジェクトは最終的に代入を実行して、その代入が有効な操作であるか判断しなければなりません。代入が不可能な場合には例外を発行することもできます。型ごとにみられる規則や、送出される例外は、そのオブジェクト型定義で与えられています ({\hyperref[\detokenize{reference/datamodel:types}]{\sphinxcrossref{\DUrole{std,std-ref}{標準型の階層}}}} 節を参照してください). \index{target@\spxentry{target}!list assignment@\spxentry{list} \spxentry{assignment}}\index{list@\spxentry{list}!assignment, target@\spxentry{assignment}, \spxentry{target}}\index{assignment@\spxentry{assignment}!target list@\spxentry{target} \spxentry{list}}\index{, (comma)@\spxentry{,}\spxextra{comma}!in target list@\spxentry{in target list}}\index{* (asterisk)@\spxentry{*}\spxextra{asterisk}!in assignment target list@\spxentry{in assignment target list}}\index{{[}{]} (square brackets)@\spxentry{{[}{]}}\spxextra{square brackets}!in assignment target list@\spxentry{in assignment target list}}\index{() (parentheses)@\spxentry{()}\spxextra{parentheses}!in assignment target list@\spxentry{in assignment target list}}\ignorespaces ターゲットリストは、丸括弧や角括弧で囲まれていてもよく、それに対するオブジェクトの代入は、以下のように再帰的に定義されています。 \begin{itemize} \item {} ターゲットリストのターゲットが1つだけでコンマが続いておらず、任意に丸括弧で囲われている場合、オブジェクトはそのターゲットに代入されます。 \item {} Else: \begin{itemize} \item {} "星付き"のターゲットと呼ばれる、頭にアスタリスクが一つ付いたターゲットがターゲットリストに一つだけ含まれている場合: オブジェクトはイテラブルで、少なくともターゲットリストのターゲットの数よりも一つ少ない要素を持たなければはなりません。 星付きのターゲットより前のターゲットに、イテラブルの先頭の要素が左から右へ代入されます。 星付きのターゲットより後ろのターゲットに、イテラブルの末尾の要素が代入されます。 星付きのターゲットに、イテラブルの残った要素のリストが代入されます (リスト空でもかまいません)。 \item {} そうでない場合: オブジェクトは、ターゲットリストのターゲットと同じ数の要素を持つイテラブルでなければならず、要素は左から右へ対応するターゲットに代入されます。 \end{itemize} \end{itemize} 単一のターゲットへの単一のオブジェクトの代入は、以下のようにして再帰的に定義されています。 \begin{itemize} \item {} ターゲットが識別子 (名前) の場合: \begin{itemize} \item {} 名前が現在のコードブロック内の {\hyperref[\detokenize{reference/simple_stmts:global}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{global}}}}} や {\hyperref[\detokenize{reference/simple_stmts:nonlocal}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{nonlocal}}}}} 文に書かれていないければ: 名前は現在のローカル名前空間内のオブジェクトに束縛されます。 \item {} そうでなければ: 名前はそれぞれグローバル名前空間内か、 {\hyperref[\detokenize{reference/simple_stmts:nonlocal}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{nonlocal}}}}} で決められた外側の名前空間内のオブジェクトに束縛されます。 \end{itemize} \index{destructor@\spxentry{destructor}}\ignorespaces 名前がすでに束縛済みの場合、再束縛 (rebind) がおこなわれます。再束縛によって、以前その名前に束縛されていたオブジェクトの参照カウント (reference count) がゼロになった場合、オブジェクトは解放 (deallocate) され、デストラクタ (destructor) が (存在すれば) 呼び出されます。 \index{attribute@\spxentry{attribute}!assignment@\spxentry{assignment}}\index{assignment@\spxentry{assignment}!attribute@\spxentry{attribute}}\ignorespaces \item {} ターゲットが属性参照の場合: 参照されている一次語の式が値評価されます。値は代入可能な属性を伴うオブジェクトでなければなりません; そうでなければ、 \sphinxcode{\sphinxupquote{TypeError}} が送出されます。次に、このオブジェクトに対して、被代入オブジェクトを指定した属性に代入してよいか問い合わせます; 代入を実行できない場合、例外 (通常は \sphinxcode{\sphinxupquote{AttributeError}} ですが、必然ではありません) を送出します。 \phantomsection\label{\detokenize{reference/simple_stmts:attr-target-note}} Note: If the object is a class instance and the attribute reference occurs on both sides of the assignment operator, the right\sphinxhyphen{}hand side expression, \sphinxcode{\sphinxupquote{a.x}} can access either an instance attribute or (if no instance attribute exists) a class attribute. The left\sphinxhyphen{}hand side target \sphinxcode{\sphinxupquote{a.x}} is always set as an instance attribute, creating it if necessary. Thus, the two occurrences of \sphinxcode{\sphinxupquote{a.x}} do not necessarily refer to the same attribute: if the right\sphinxhyphen{}hand side expression refers to a class attribute, the left\sphinxhyphen{}hand side creates a new instance attribute as the target of the assignment: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{class} \PYG{n+nc}{Cls}\PYG{p}{:} \PYG{n}{x} \PYG{o}{=} \PYG{l+m+mi}{3} \PYG{c+c1}{\PYGZsh{} class variable} \PYG{n}{inst} \PYG{o}{=} \PYG{n}{Cls}\PYG{p}{(}\PYG{p}{)} \PYG{n}{inst}\PYG{o}{.}\PYG{n}{x} \PYG{o}{=} \PYG{n}{inst}\PYG{o}{.}\PYG{n}{x} \PYG{o}{+} \PYG{l+m+mi}{1} \PYG{c+c1}{\PYGZsh{} writes inst.x as 4 leaving Cls.x as 3} \end{sphinxVerbatim} このことは、 \sphinxcode{\sphinxupquote{property()}} で作成されたプロパティのようなデスクリプタ属性に対しては、必ずしもあてはまるとは限りません。 \index{subscription@\spxentry{subscription}!assignment@\spxentry{assignment}}\index{assignment@\spxentry{assignment}!subscription@\spxentry{subscription}}\index{オブジェクト@\spxentry{オブジェクト}!mutable@\spxentry{mutable}}\index{mutable@\spxentry{mutable}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces \item {} ターゲットが添字表記なら: 参照されている一次語式が評価されます。参照から (リストのような) ミュータブルなシーケンスオブジェクトか、(辞書のような) マッピングオブジェクトが得られなければなりません。次に、添字表記の表す式が評価されます。 \index{オブジェクト@\spxentry{オブジェクト}!sequence@\spxentry{sequence}}\index{sequence@\spxentry{sequence}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!list@\spxentry{list}}\index{list@\spxentry{list}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces 一次語が (リストのような) ミュータブルなシーケンスオブジェクトであれば、添字表記は整数を与えなければなりません。整数が負なら、シーケンスの長さが加算されます。整数は最終的に、シーケンスの長さよりも小さな非負の整数でなくてはならず、シーケンスは、そのインデクスに持つ要素に被代入オブジェクトを代入してよいか問い合わせられます。インデクスが範囲外なら、 \sphinxcode{\sphinxupquote{IndexError}} が送出されます (添字指定されたシーケンスに代入を行っても、リスト要素の新たな追加はできません)。 \index{オブジェクト@\spxentry{オブジェクト}!mapping@\spxentry{mapping}}\index{mapping@\spxentry{mapping}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!dictionary@\spxentry{dictionary}}\index{dictionary@\spxentry{dictionary}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces 一次語が (辞書のような) マップオブジェクトの場合、まず添字はマップのキー型と互換性のある型でなくてはなりません。次に、添字を被代入オブジェクトに関連付けるようなキー/データの対を生成するようマップオブジェクトに問い合わせます。この操作では、既存のキー/値の対を同じキーと別の値で置き換えてもよく、(同じ値を持つキーが存在しない場合) 新たなキー/値の対を挿入してもかまいません。 ユーザ定義のオブジェクトには、適切な引数で {\hyperref[\detokenize{reference/datamodel:object.__setitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_setitem\_\_()}}}}} メソッドが呼び出されます。 \index{slicing@\spxentry{slicing}!assignment@\spxentry{assignment}}\index{assignment@\spxentry{assignment}!slicing@\spxentry{slicing}}\ignorespaces \item {} ターゲットがスライスなら: 参照されている一次語式が評価されます。一次語式は、(リストのような) ミュータブルなシーケンスオブジェクトを与えなければなりません。被代入オブジェクトは同じ型のシーケンスオブジェクトでなければなりません。次に、スライスの下限と上限を示す式があれば評価されます; デフォルト値はそれぞれ 0 とシーケンスの長さです。上限と下限の評価は整数でなければなりません。いずれかの境界が負数なら、シーケンスの長さが加算されます。最終的に、境界は 0 からシーケンスの長さまでに収まるように刈りこまれます。最後に、スライスを被代入オブジェクトで置き換えてよいかシーケンスオブジェクトに問い合わせます。ターゲットシーケンスで許されている限り、スライスの長さは被代入シーケンスの長さと異なっていてよく、この場合にはターゲットシーケンスの長さが変更されます。 \end{itemize} \sphinxstylestrong{CPython implementation detail:} 現在の実装では、ターゲットの構文は式の構文と同じであるとみなされており、無効な構文はコード生成フェーズ中に詳細なエラーメッセージを伴って拒否されます。 代入の定義によれば、左辺と右辺のオーバーラップは '同時 (simultaneous)' です (例えば \sphinxcode{\sphinxupquote{a, b = b, a}} は二つの変数を入れ替えます) が、代入対象となる変数群 \sphinxstyleemphasis{どうし} のオーバーラップは左から右へ起こり、混乱の元です。例えば、以下のプログラムは \sphinxcode{\sphinxupquote{{[}0, 2{]}}} を出力してしまいます: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{x} \PYG{o}{=} \PYG{p}{[}\PYG{l+m+mi}{0}\PYG{p}{,} \PYG{l+m+mi}{1}\PYG{p}{]} \PYG{n}{i} \PYG{o}{=} \PYG{l+m+mi}{0} \PYG{n}{i}\PYG{p}{,} \PYG{n}{x}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{o}{=} \PYG{l+m+mi}{1}\PYG{p}{,} \PYG{l+m+mi}{2} \PYG{c+c1}{\PYGZsh{} i is updated, then x[i] is updated} \PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)} \end{sphinxVerbatim} \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 3132@\spxentry{PEP 3132}}\sphinxhref{https://www.python.org/dev/peps/pep-3132}{\sphinxstylestrong{PEP 3132}} \sphinxhyphen{} Extended Iterable Unpacking}] \leavevmode \sphinxcode{\sphinxupquote{*target}} の指定機能。 \end{description} \subsection{累算代入文 (augmented assignment statement)} \label{\detokenize{reference/simple_stmts:augmented-assignment-statements}}\label{\detokenize{reference/simple_stmts:augassign}} \index{augmented@\spxentry{augmented}!assignment@\spxentry{assignment}}\index{assignment@\spxentry{assignment}!augmented@\spxentry{augmented}}\index{statement@\spxentry{statement}!assignment, augmented@\spxentry{assignment, augmented}}\index{+=@\spxentry{+=}!augmented assignment@\spxentry{augmented assignment}}\index{\sphinxhyphen{}=@\spxentry{\sphinxhyphen{}=}!augmented assignment@\spxentry{augmented assignment}}\index{*=@\spxentry{*=}!augmented assignment@\spxentry{augmented assignment}}\index{/=@\spxentry{/=}!augmented assignment@\spxentry{augmented assignment}}\index{\%=@\spxentry{\%=}!augmented assignment@\spxentry{augmented assignment}}\index{\&=@\spxentry{\&=}!augmented assignment@\spxentry{augmented assignment}}\index{\textasciicircum{}=@\spxentry{\textasciicircum{}=}!augmented assignment@\spxentry{augmented assignment}}\index{\textbar{}=@\spxentry{\textbar{}=}!augmented assignment@\spxentry{augmented assignment}}\index{**=@\spxentry{**=}!augmented assignment@\spxentry{augmented assignment}}\index{//=@\spxentry{//=}!augmented assignment@\spxentry{augmented assignment}}\index{>>=@\spxentry{>>=}!augmented assignment@\spxentry{augmented assignment}}\index{<<=@\spxentry{<<=}!augmented assignment@\spxentry{augmented assignment}}\ignorespaces 累算代入文は、二項演算と代入文を組み合わせて一つの文にしたものです: \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-augmented_assignment_stmt}}\production{augmented\_assignment\_stmt}{ {\hyperref[\detokenize{reference/simple_stmts:grammar-token-augtarget}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{augtarget}}}}} {\hyperref[\detokenize{reference/simple_stmts:grammar-token-augop}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{augop}}}}} ({\hyperref[\detokenize{reference/expressions:grammar-token-expression-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression\_list}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-yield-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield\_expression}}}}})} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-augtarget}}\production{augtarget}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-attributeref}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{attributeref}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-subscription}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{subscription}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-slicing}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{slicing}}}}}} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-augop}}\production{augop}{ "+=" | "\sphinxhyphen{}=" | "*=" | "@=" | "/=" | "//=" | "\%=" | "**="} \productioncont{ | ">>=" | "<<=" | "\&=" | "\textasciicircum{}=" | "|="} \end{productionlist} (最後の3つの構文定義については {\hyperref[\detokenize{reference/expressions:primaries}]{\sphinxcrossref{\DUrole{std,std-ref}{プライマリ}}}} を参照してください。) 累算代入文は、ターゲット (通常の代入文と違って、アンパックは起こりません) と式リストを評価し、それら二つの被演算子間で特定の累算代入型の二項演算を行い、結果をもとのターゲットに代入します。ターゲットは一度しか評価されません。 \sphinxcode{\sphinxupquote{x += 1}} のような累算代入式は、 \sphinxcode{\sphinxupquote{x = x + 1}} のように書き換えてほぼ同様の動作にできますが、厳密に等価にはなりません。累算代入の方では、 \sphinxcode{\sphinxupquote{x}} は一度しか評価されません。また、実際の処理として、可能ならば \sphinxstyleemphasis{インプレース (in\sphinxhyphen{}place)} 演算が実行されます。これは、代入時に新たなオブジェクトを生成してターゲットに代入するのではなく、以前のオブジェクトの内容を変更するということです。 通常の代入とは違い、累算代入文は右辺を評価する \sphinxstyleemphasis{前に} 左辺を評価します。たとえば、\sphinxcode{\sphinxupquote{a{[}i{]} += f(x)}} はまず \sphinxcode{\sphinxupquote{a{[}i{]}}} を調べ、\sphinxcode{\sphinxupquote{f(x)}} を評価して加算を行い、最後に結果を \sphinxcode{\sphinxupquote{a{[}i{]}}} に割り当てます。 累算代入文で行われる代入は、タプルへの代入や、一文中に複数のターゲットが存在する場合を除き、通常の代入と同じように扱われます。同様に、累算代入で行われる二項演算は、場合によって \sphinxstyleemphasis{インプレース演算} が行われることを除き、通常の二項演算と同じです。 属性参照のターゲットの場合、 {\hyperref[\detokenize{reference/simple_stmts:attr-target-note}]{\sphinxcrossref{\DUrole{std,std-ref}{クラス属性とインスタンス属性についての注意}}}} と同様に通常の代入が適用されます。 \subsection{注釈付き代入文 (annotated assignment statements)} \label{\detokenize{reference/simple_stmts:annotated-assignment-statements}}\label{\detokenize{reference/simple_stmts:annassign}} \index{annotated@\spxentry{annotated}!assignment@\spxentry{assignment}}\index{assignment@\spxentry{assignment}!annotated@\spxentry{annotated}}\index{statement@\spxentry{statement}!assignment, annotated@\spxentry{assignment, annotated}}\index{: (colon)@\spxentry{:}\spxextra{colon}!annotated variable@\spxentry{annotated variable}}\ignorespaces {\hyperref[\detokenize{glossary:term-variable-annotation}]{\sphinxtermref{\DUrole{xref,std,std-term}{注釈}}}} 代入は、1 つの文の中で変数や属性のアノテーションとオプションの代入文を組み合わせたものです: \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-annotated_assignment_stmt}}\production{annotated\_assignment\_stmt}{ {\hyperref[\detokenize{reference/simple_stmts:grammar-token-augtarget}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{augtarget}}}}} ":" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}} \productioncont{ {[}"=" ({\hyperref[\detokenize{reference/expressions:grammar-token-starred-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{starred\_expression}}}}} | {\hyperref[\detokenize{reference/expressions:grammar-token-yield-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield\_expression}}}}}){]}} \end{productionlist} The difference from normal {\hyperref[\detokenize{reference/simple_stmts:assignment}]{\sphinxcrossref{\DUrole{std,std-ref}{代入文 (assignment statement)}}}} is that only single target is allowed. 代入先として単純名を使うと、クラススコープもしくはモジュールスコープの場合、注釈は評価され、クラスもしくはモジュールの特殊属性 \sphinxcode{\sphinxupquote{\_\_annotations\_\_}} に格納されます。 この属性は、変数名 (プライベート変数の場合はマングリングされた名前) から評価後の注釈への対応付けを持つ辞書です。 この属性は書き込み可能であり、注釈が静的に存在している場合、クラスもしくはモジュールの本体の実行の先頭で自動的に作成されます。 代入先として式を使うと、クラススコープもしくはモジュールスコープの場合、注釈は評価されますが、格納されません。 関数スコープで名前に注釈が付いていた場合は、その名前はその関数スコープでローカルなものになります。 注釈は絶対に評価されず、関数スコープにも格納されません。 右辺がある場合、注釈代入はアノテーション (有効であれば) を評価する前に、実際に代入を行います。 対象となる式の右辺が無い場合は、インタプリタは最後の {\hyperref[\detokenize{reference/datamodel:object.__setitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_setitem\_\_()}}}}} や {\hyperref[\detokenize{reference/datamodel:object.__setattr__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_setattr\_\_()}}}}} 呼び出し以外の対象の式を評価します。 \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 526@\spxentry{PEP 526}}\sphinxhref{https://www.python.org/dev/peps/pep-0526}{\sphinxstylestrong{PEP 526}} \sphinxhyphen{} Syntax for Variable Annotations}] \leavevmode (クラス変数やインスタンス変数を含んだ) 変数の型注釈を付ける、コメントで表現するのではない文法の追加提案。 \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 484@\spxentry{PEP 484}}\sphinxhref{https://www.python.org/dev/peps/pep-0484}{\sphinxstylestrong{PEP 484}} \sphinxhyphen{} Type hints}] \leavevmode \sphinxcode{\sphinxupquote{typing}} モジュールを追加し、静的解析ツールや IDE で使える型アノテーションの標準的な文法を提供する提案。 \end{description} \DUrole{versionmodified,changed}{バージョン 3.8 で変更: }Now annotated assignments allow same expressions in the right hand side as the regular assignments. Previously, some expressions (like un\sphinxhyphen{}parenthesized tuple expressions) caused a syntax error. \section{\sphinxstyleliteralintitle{\sphinxupquote{assert}} 文} \label{\detokenize{reference/simple_stmts:the-assert-statement}}\label{\detokenize{reference/simple_stmts:assert}} \index{文@\spxentry{文}!assert@\spxentry{assert}|spxpagem}\index{assert@\spxentry{assert}!文@\spxentry{文}|spxpagem}\index{debugging@\spxentry{debugging}!assertions@\spxentry{assertions}}\index{assertions@\spxentry{assertions}!debugging@\spxentry{debugging}}\index{, (comma)@\spxentry{,}\spxextra{comma}!expression list@\spxentry{expression list}}\ignorespaces assert 文は、プログラム内にデバッグ用アサーション (debugging assertion) を仕掛けるための便利な方法です: \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-assert_stmt}}\production{assert\_stmt}{ "assert" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} {[}"," {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}{]}} \end{productionlist} 単純な形式 \sphinxcode{\sphinxupquote{assert expression}} は \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{if} \PYG{n}{\PYGZus{}\PYGZus{}debug\PYGZus{}\PYGZus{}}\PYG{p}{:} \PYG{k}{if} \PYG{o+ow}{not} \PYG{n}{expression}\PYG{p}{:} \PYG{k}{raise} \PYG{n+ne}{AssertionError} \end{sphinxVerbatim} と等価です。拡張形式 \sphinxcode{\sphinxupquote{assert expression1, expression2}} は、これと等価です \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{if} \PYG{n}{\PYGZus{}\PYGZus{}debug\PYGZus{}\PYGZus{}}\PYG{p}{:} \PYG{k}{if} \PYG{o+ow}{not} \PYG{n}{expression1}\PYG{p}{:} \PYG{k}{raise} \PYG{n+ne}{AssertionError}\PYG{p}{(}\PYG{n}{expression2}\PYG{p}{)} \end{sphinxVerbatim} \index{\_\_debug\_\_@\spxentry{\_\_debug\_\_}}\index{例外@\spxentry{例外}!AssertionError@\spxentry{AssertionError}}\index{AssertionError@\spxentry{AssertionError}!例外@\spxentry{例外}}\ignorespaces 上記の等価関係は、 \sphinxcode{\sphinxupquote{\_\_debug\_\_}} と \sphinxcode{\sphinxupquote{AssertionError}} が、同名の組み込み変数を参照しているという前提の上に成り立っています。現在の実装では、組み込み変数 \sphinxcode{\sphinxupquote{\_\_debug\_\_}} は通常の状況では \sphinxcode{\sphinxupquote{True}} であり、最適化が要求された場合(コマンドラインオプション \sphinxcode{\sphinxupquote{\sphinxhyphen{}O}})は \sphinxcode{\sphinxupquote{False}} です。現状のコード生成器は、コンパイル時に最適化が要求されていると assert 文のコードを一切出力しません。実行に失敗した式のソースコードをエラーメッセージ内に入れる必要はありません; コードはスタックトレース内で表示されます。 \sphinxcode{\sphinxupquote{\_\_debug\_\_}} への代入は不正な操作です。組み込み変数の値は、インタプリタが開始するときに決定されます。 \section{\sphinxstyleliteralintitle{\sphinxupquote{pass}} 文} \label{\detokenize{reference/simple_stmts:the-pass-statement}}\label{\detokenize{reference/simple_stmts:pass}} \index{文@\spxentry{文}!pass@\spxentry{pass}}\index{pass@\spxentry{pass}!文@\spxentry{文}}\index{null@\spxentry{null}!operation@\spxentry{operation}}\index{operation@\spxentry{operation}!null@\spxentry{null}}\index{null@\spxentry{null}!operation@\spxentry{operation}}\index{operation@\spxentry{operation}!null@\spxentry{null}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-pass_stmt}}\production{pass\_stmt}{ "pass"} \end{productionlist} {\hyperref[\detokenize{reference/simple_stmts:pass}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{pass}}}}} はヌル操作 (null operation) です \sphinxhyphen{}\sphinxhyphen{}\sphinxhyphen{} {\hyperref[\detokenize{reference/simple_stmts:pass}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{pass}}}}} が実行されても、何も起きません。 {\hyperref[\detokenize{reference/simple_stmts:pass}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{pass}}}}} は、構文法的には文が必要だが、コードとしては何も実行したくない場合のプレースホルダとして有用です。例えば: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{def} \PYG{n+nf}{f}\PYG{p}{(}\PYG{n}{arg}\PYG{p}{)}\PYG{p}{:} \PYG{k}{pass} \PYG{c+c1}{\PYGZsh{} a function that does nothing (yet)} \PYG{k}{class} \PYG{n+nc}{C}\PYG{p}{:} \PYG{k}{pass} \PYG{c+c1}{\PYGZsh{} a class with no methods (yet)} \end{sphinxVerbatim} \section{\sphinxstyleliteralintitle{\sphinxupquote{del}} 文} \label{\detokenize{reference/simple_stmts:the-del-statement}}\label{\detokenize{reference/simple_stmts:del}} \index{文@\spxentry{文}!del@\spxentry{del}|spxpagem}\index{del@\spxentry{del}!文@\spxentry{文}|spxpagem}\index{deletion@\spxentry{deletion}!target@\spxentry{target}}\index{target@\spxentry{target}!deletion@\spxentry{deletion}}\index{deletion@\spxentry{deletion}!target list@\spxentry{target} \spxentry{list}}\index{target@\spxentry{target}!list, deletion@\spxentry{list}, \spxentry{deletion}}\index{list@\spxentry{list}!deletion target@\spxentry{deletion} \spxentry{target}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-del_stmt}}\production{del\_stmt}{ "del" {\hyperref[\detokenize{reference/simple_stmts:grammar-token-target-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{target\_list}}}}}} \end{productionlist} オブジェクトの削除 (deletion) は、代入の定義と非常に似た方法で再帰的に定義されています。ここでは完全な詳細は記述せず、いくつかのヒントを述べるにとどめます。 ターゲットリストに対する削除は、各々のターゲットを左から右へと順に再帰的に削除します。 \index{文@\spxentry{文}!global@\spxentry{global}}\index{global@\spxentry{global}!文@\spxentry{文}}\index{unbinding@\spxentry{unbinding}!name@\spxentry{name}}\index{name@\spxentry{name}!unbinding@\spxentry{unbinding}}\ignorespaces 名前の削除は、ローカルまたはグローバル名前空間からその名前の束縛を取り除きます。どちらの名前空間かは、名前が同じコードブロック内の {\hyperref[\detokenize{reference/simple_stmts:global}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{global}}}}} 文で宣言されているかどうかによります。名前が未束縛 (unbound) なら、 \sphinxcode{\sphinxupquote{NameError}} 例外が送出されます。 \index{attribute@\spxentry{attribute}!deletion@\spxentry{deletion}}\index{deletion@\spxentry{deletion}!attribute@\spxentry{attribute}}\ignorespaces 属性参照、添字表記、およびスライスの削除操作は、対象となる一次語オブジェクトに渡されます; スライスの削除は一般的には適切な型の空のスライスを代入するのと等価です (が、この仕様自体もスライスされるオブジェクトで決定されています)。 \DUrole{versionmodified,changed}{バージョン 3.2 で変更: }以前は、ある名前がネストしたブロックの自由変数として表れる場合は、ローカル名前空間からその名前を削除することは不正な処理でした。 \section{\sphinxstyleliteralintitle{\sphinxupquote{return}} 文} \label{\detokenize{reference/simple_stmts:the-return-statement}}\label{\detokenize{reference/simple_stmts:return}} \index{文@\spxentry{文}!return@\spxentry{return}|spxpagem}\index{return@\spxentry{return}!文@\spxentry{文}|spxpagem}\index{function@\spxentry{function}!definition@\spxentry{definition}}\index{definition@\spxentry{definition}!function@\spxentry{function}}\index{class@\spxentry{class}!definition@\spxentry{definition}}\index{definition@\spxentry{definition}!class@\spxentry{class}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-return_stmt}}\production{return\_stmt}{ "return" {[}{\hyperref[\detokenize{reference/expressions:grammar-token-expression-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression\_list}}}}}{]}} \end{productionlist} {\hyperref[\detokenize{reference/simple_stmts:return}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{return}}}}} は、関数定義内で構文法的にネストして現れますが、ネストしたクラス定義内には現れません。 式リストがある場合、リストが値評価されます。それ以外の場合は \sphinxcode{\sphinxupquote{None}} で置き換えられます。 {\hyperref[\detokenize{reference/simple_stmts:return}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{return}}}}} を使うと、式リスト (または \sphinxcode{\sphinxupquote{None}}) を戻り値として、現在の関数呼び出しから抜け出します。 \index{キーワード@\spxentry{キーワード}!finally@\spxentry{finally}}\index{finally@\spxentry{finally}!キーワード@\spxentry{キーワード}}\ignorespaces {\hyperref[\detokenize{reference/simple_stmts:return}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{return}}}}} によって、 {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節をともなう {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} 文の外に処理が引き渡されると、実際に関数から抜ける前に \sphinxcode{\sphinxupquote{finally}} 節が実行されます。 ジェネレータ関数では、 {\hyperref[\detokenize{reference/simple_stmts:return}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{return}}}}} 文はジェネレータの終わりを示し、 \sphinxcode{\sphinxupquote{StopIteration}} 例外を送出させます。返された値は (あれば)、 \sphinxcode{\sphinxupquote{StopIteration}} を構成する引数に使われ、 \sphinxcode{\sphinxupquote{StopIteration.value}} 属性になります。 非同期ジェネレータ関数では、引数無しの {\hyperref[\detokenize{reference/simple_stmts:return}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{return}}}}} 文は非同期ジェネレータの終わりを示し、 \sphinxcode{\sphinxupquote{StopAsyncIteration}} を送出させます。 引数ありの \sphinxcode{\sphinxupquote{return}} 文は、非同期ジェネレータ関数では文法エラーです。 \section{\sphinxstyleliteralintitle{\sphinxupquote{yield}} 文} \label{\detokenize{reference/simple_stmts:the-yield-statement}}\label{\detokenize{reference/simple_stmts:yield}} \index{文@\spxentry{文}!yield@\spxentry{yield}}\index{yield@\spxentry{yield}!文@\spxentry{文}}\index{generator@\spxentry{generator}!function@\spxentry{function}}\index{generator@\spxentry{generator}!iterator@\spxentry{iterator}}\index{function@\spxentry{function}!generator@\spxentry{generator}}\index{例外@\spxentry{例外}!StopIteration@\spxentry{StopIteration}}\index{StopIteration@\spxentry{StopIteration}!例外@\spxentry{例外}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-yield_stmt}}\production{yield\_stmt}{ {\hyperref[\detokenize{reference/expressions:grammar-token-yield-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield\_expression}}}}}} \end{productionlist} {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} 文は意味的に {\hyperref[\detokenize{reference/expressions:yieldexpr}]{\sphinxcrossref{\DUrole{std,std-ref}{yield 式}}}} と同じです。yield 文を用いると yield 式文で必要な括弧を省略することが出来ます。例えば、yield 文 \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{yield} \PYG{o}{\PYGZlt{}}\PYG{n}{expr}\PYG{o}{\PYGZgt{}} \PYG{k}{yield from} \PYG{o}{\PYGZlt{}}\PYG{n}{expr}\PYG{o}{\PYGZgt{}} \end{sphinxVerbatim} は以下の yield 式文と等価です \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{p}{(}\PYG{k}{yield} \PYG{o}{\PYGZlt{}}\PYG{n}{expr}\PYG{o}{\PYGZgt{}}\PYG{p}{)} \PYG{p}{(}\PYG{k}{yield from} \PYG{o}{\PYGZlt{}}\PYG{n}{expr}\PYG{o}{\PYGZgt{}}\PYG{p}{)} \end{sphinxVerbatim} yield 式及び文は {\hyperref[\detokenize{glossary:term-generator}]{\sphinxtermref{\DUrole{xref,std,std-term}{generator}}}} を定義するときに、その本体内でのみ使うことが出来ます。関数定義内で yield を使用することで、その定義は通常の関数でなくジェネレータ関数になります。 {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} の意味の完全な説明は、 {\hyperref[\detokenize{reference/expressions:yieldexpr}]{\sphinxcrossref{\DUrole{std,std-ref}{Yield 式}}}} 節を参照してください。 \section{\sphinxstyleliteralintitle{\sphinxupquote{raise}} 文} \label{\detokenize{reference/simple_stmts:the-raise-statement}}\label{\detokenize{reference/simple_stmts:raise}} \index{文@\spxentry{文}!raise@\spxentry{raise}|spxpagem}\index{raise@\spxentry{raise}!文@\spxentry{文}|spxpagem}\index{exception@\spxentry{exception}}\index{raising@\spxentry{raising}!exception@\spxentry{exception}}\index{exception@\spxentry{exception}!raising@\spxentry{raising}}\index{\_\_traceback\_\_ (exception attribute)@\spxentry{\_\_traceback\_\_}\spxextra{exception attribute}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-raise_stmt}}\production{raise\_stmt}{ "raise" {[}{\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} {[}"from" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}{]}{]}} \end{productionlist} If no expressions are present, {\hyperref[\detokenize{reference/simple_stmts:raise}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{raise}}}}} re\sphinxhyphen{}raises the exception that is currently being handled, which is also known as the \sphinxstyleemphasis{active exception}. If there isn't currently an active exception, a \sphinxcode{\sphinxupquote{RuntimeError}} exception is raised indicating that this is an error. そうでなければ、 {\hyperref[\detokenize{reference/simple_stmts:raise}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{raise}}}}} は最初の式を、例外オブジェクトとして評価します。これは、 \sphinxcode{\sphinxupquote{BaseException}} のサブクラスまたはインスタンスでなければなりません。クラスなら、例外インスタンスが必要なとき、クラスを無引数でインスタンス化することで得られます。 例外の \sphinxstyleemphasis{型} は例外インスタンスのクラスで、 \sphinxstyleemphasis{値} はインスタンスそのものです。 \index{オブジェクト@\spxentry{オブジェクト}!traceback@\spxentry{traceback}}\index{traceback@\spxentry{traceback}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces A traceback object is normally created automatically when an exception is raised and attached to it as the \sphinxcode{\sphinxupquote{\_\_traceback\_\_}} attribute, which is writable. You can create an exception and set your own traceback in one step using the \sphinxcode{\sphinxupquote{with\_traceback()}} exception method (which returns the same exception instance, with its traceback set to its argument), like so: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{raise} \PYG{n+ne}{Exception}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{foo occurred}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)}\PYG{o}{.}\PYG{n}{with\PYGZus{}traceback}\PYG{p}{(}\PYG{n}{tracebackobj}\PYG{p}{)} \end{sphinxVerbatim} \index{exception@\spxentry{exception}!chaining@\spxentry{chaining}}\index{chaining@\spxentry{chaining}!exception@\spxentry{exception}}\index{\_\_cause\_\_ (exception attribute)@\spxentry{\_\_cause\_\_}\spxextra{exception attribute}}\index{\_\_context\_\_ (exception attribute)@\spxentry{\_\_context\_\_}\spxextra{exception attribute}}\ignorespaces The \sphinxcode{\sphinxupquote{from}} clause is used for exception chaining: if given, the second \sphinxstyleemphasis{expression} must be another exception class or instance. If the second expression is an exception instance, it will be attached to the raised exception as the \sphinxcode{\sphinxupquote{\_\_cause\_\_}} attribute (which is writable). If the expression is an exception class, the class will be instantiated and the resulting exception instance will be attached to the raised exception as the \sphinxcode{\sphinxupquote{\_\_cause\_\_}} attribute. If the raised exception is not handled, both exceptions will be printed: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k}{try}\PYG{p}{:} \PYG{g+gp}{... } \PYG{n+nb}{print}\PYG{p}{(}\PYG{l+m+mi}{1} \PYG{o}{/} \PYG{l+m+mi}{0}\PYG{p}{)} \PYG{g+gp}{... }\PYG{k}{except} \PYG{n+ne}{Exception} \PYG{k}{as} \PYG{n}{exc}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{raise} \PYG{n+ne}{RuntimeError}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{Something bad happened}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} \PYG{k+kn}{from} \PYG{n+nn}{exc} \PYG{g+gp}{...} \PYG{g+gt}{Traceback (most recent call last):} File \PYG{n+nb}{\PYGZdq{}\PYGZlt{}stdin\PYGZgt{}\PYGZdq{}}, line \PYG{l+m}{2}, in \PYG{n}{\PYGZlt{}module\PYGZgt{}} \PYG{g+gr}{ZeroDivisionError}: \PYG{n}{division by zero} \PYG{g+go}{The above exception was the direct cause of the following exception:} \PYG{g+gt}{Traceback (most recent call last):} File \PYG{n+nb}{\PYGZdq{}\PYGZlt{}stdin\PYGZgt{}\PYGZdq{}}, line \PYG{l+m}{4}, in \PYG{n}{\PYGZlt{}module\PYGZgt{}} \PYG{g+gr}{RuntimeError}: \PYG{n}{Something bad happened} \end{sphinxVerbatim} A similar mechanism works implicitly if a new exception is raised when an exception is already being handled. An exception may be handled when an {\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}} or {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} clause, or a {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}} statement, is used. The previous exception is then attached as the new exception's \sphinxcode{\sphinxupquote{\_\_context\_\_}} attribute: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k}{try}\PYG{p}{:} \PYG{g+gp}{... } \PYG{n+nb}{print}\PYG{p}{(}\PYG{l+m+mi}{1} \PYG{o}{/} \PYG{l+m+mi}{0}\PYG{p}{)} \PYG{g+gp}{... }\PYG{k}{except}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{raise} \PYG{n+ne}{RuntimeError}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{Something bad happened}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} \PYG{g+gp}{...} \PYG{g+gt}{Traceback (most recent call last):} File \PYG{n+nb}{\PYGZdq{}\PYGZlt{}stdin\PYGZgt{}\PYGZdq{}}, line \PYG{l+m}{2}, in \PYG{n}{\PYGZlt{}module\PYGZgt{}} \PYG{g+gr}{ZeroDivisionError}: \PYG{n}{division by zero} \PYG{g+go}{During handling of the above exception, another exception occurred:} \PYG{g+gt}{Traceback (most recent call last):} File \PYG{n+nb}{\PYGZdq{}\PYGZlt{}stdin\PYGZgt{}\PYGZdq{}}, line \PYG{l+m}{4}, in \PYG{n}{\PYGZlt{}module\PYGZgt{}} \PYG{g+gr}{RuntimeError}: \PYG{n}{Something bad happened} \end{sphinxVerbatim} \sphinxcode{\sphinxupquote{from}} 節に \sphinxcode{\sphinxupquote{None}} を指定することで、例外の連鎖を明示的に非表示にできます: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k}{try}\PYG{p}{:} \PYG{g+gp}{... } \PYG{n+nb}{print}\PYG{p}{(}\PYG{l+m+mi}{1} \PYG{o}{/} \PYG{l+m+mi}{0}\PYG{p}{)} \PYG{g+gp}{... }\PYG{k}{except}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{raise} \PYG{n+ne}{RuntimeError}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{Something bad happened}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} \PYG{k+kn}{from} \PYG{n+nb+bp}{None} \PYG{g+gp}{...} \PYG{g+gt}{Traceback (most recent call last):} File \PYG{n+nb}{\PYGZdq{}\PYGZlt{}stdin\PYGZgt{}\PYGZdq{}}, line \PYG{l+m}{4}, in \PYG{n}{\PYGZlt{}module\PYGZgt{}} \PYG{g+gr}{RuntimeError}: \PYG{n}{Something bad happened} \end{sphinxVerbatim} 例外に関する追加情報は {\hyperref[\detokenize{reference/executionmodel:exceptions}]{\sphinxcrossref{\DUrole{std,std-ref}{例外}}}} 節にあります。また、例外処理に関する情報は {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\DUrole{std,std-ref}{try 文}}}} 節にあります。 \DUrole{versionmodified,changed}{バージョン 3.3 で変更: }\sphinxcode{\sphinxupquote{None}} が \sphinxcode{\sphinxupquote{raise X from Y}} の \sphinxcode{\sphinxupquote{Y}} として使えるようになりました。 \DUrole{versionmodified,added}{バージョン 3.3 で追加: }\sphinxcode{\sphinxupquote{\_\_suppress\_context\_\_}} 属性の設定で、例外のコンテキストが自動的に非表示になります。 \section{\sphinxstyleliteralintitle{\sphinxupquote{break}} 文} \label{\detokenize{reference/simple_stmts:the-break-statement}}\label{\detokenize{reference/simple_stmts:break}} \index{文@\spxentry{文}!break@\spxentry{break}|spxpagem}\index{break@\spxentry{break}!文@\spxentry{文}|spxpagem}\index{文@\spxentry{文}!for@\spxentry{for}}\index{for@\spxentry{for}!文@\spxentry{文}}\index{文@\spxentry{文}!while@\spxentry{while}}\index{while@\spxentry{while}!文@\spxentry{文}}\index{loop@\spxentry{loop}!statement@\spxentry{statement}}\index{statement@\spxentry{statement}!loop@\spxentry{loop}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-break_stmt}}\production{break\_stmt}{ "break"} \end{productionlist} {\hyperref[\detokenize{reference/simple_stmts:break}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{break}}}}} 文は、構文としては {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} ループや {\hyperref[\detokenize{reference/compound_stmts:while}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{while}}}}} ループの内側でのみ出現することができますが、ループ内の関数定義やクラス定義の内側には出現できません。 \index{キーワード@\spxentry{キーワード}!else@\spxentry{else}}\index{else@\spxentry{else}!キーワード@\spxentry{キーワード}}\index{loop control@\spxentry{loop control}!target@\spxentry{target}}\index{target@\spxentry{target}!loop control@\spxentry{loop control}}\ignorespaces {\hyperref[\detokenize{reference/simple_stmts:break}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{break}}}}} 文は、文を囲う最も内側のループを終了させ、ループにオプションの \sphinxcode{\sphinxupquote{else}} 節がある場合にはそれをスキップします。 {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} ループを {\hyperref[\detokenize{reference/simple_stmts:break}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{break}}}}} によって終了すると、ループ制御ターゲットはその時の値を保持します。 \index{キーワード@\spxentry{キーワード}!finally@\spxentry{finally}}\index{finally@\spxentry{finally}!キーワード@\spxentry{キーワード}}\ignorespaces {\hyperref[\detokenize{reference/simple_stmts:break}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{break}}}}} が {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節を伴う {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} 文の外側に処理を渡す際には、ループを実際に抜ける前にその \sphinxcode{\sphinxupquote{finally}} 節が実行されます。 \section{\sphinxstyleliteralintitle{\sphinxupquote{continue}} 文} \label{\detokenize{reference/simple_stmts:the-continue-statement}}\label{\detokenize{reference/simple_stmts:continue}} \index{文@\spxentry{文}!continue@\spxentry{continue}|spxpagem}\index{continue@\spxentry{continue}!文@\spxentry{文}|spxpagem}\index{文@\spxentry{文}!for@\spxentry{for}}\index{for@\spxentry{for}!文@\spxentry{文}}\index{文@\spxentry{文}!while@\spxentry{while}}\index{while@\spxentry{while}!文@\spxentry{文}}\index{loop@\spxentry{loop}!statement@\spxentry{statement}}\index{statement@\spxentry{statement}!loop@\spxentry{loop}}\index{キーワード@\spxentry{キーワード}!finally@\spxentry{finally}}\index{finally@\spxentry{finally}!キーワード@\spxentry{キーワード}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-continue_stmt}}\production{continue\_stmt}{ "continue"} \end{productionlist} {\hyperref[\detokenize{reference/simple_stmts:continue}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{continue}}}}} may only occur syntactically nested in a {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} or {\hyperref[\detokenize{reference/compound_stmts:while}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{while}}}}} loop, but not nested in a function or class definition within that loop. It continues with the next cycle of the nearest enclosing loop. {\hyperref[\detokenize{reference/simple_stmts:continue}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{continue}}}}} が {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 句を持った {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} 文を抜けるとき、その \sphinxcode{\sphinxupquote{finally}} 句が次のループサイクルを始める前に実行されます。 \section{\sphinxstyleliteralintitle{\sphinxupquote{import}} 文} \label{\detokenize{reference/simple_stmts:the-import-statement}}\label{\detokenize{reference/simple_stmts:from}}\label{\detokenize{reference/simple_stmts:import}} \index{文@\spxentry{文}!import@\spxentry{import}|spxpagem}\index{import@\spxentry{import}!文@\spxentry{文}|spxpagem}\index{module@\spxentry{module}!importing@\spxentry{importing}}\index{name@\spxentry{name}!binding@\spxentry{binding}}\index{binding@\spxentry{binding}!name@\spxentry{name}}\index{キーワード@\spxentry{キーワード}!from@\spxentry{from}}\index{from@\spxentry{from}!キーワード@\spxentry{キーワード}}\index{キーワード@\spxentry{キーワード}!as@\spxentry{as}}\index{as@\spxentry{as}!キーワード@\spxentry{キーワード}}\index{例外@\spxentry{例外}!ImportError@\spxentry{ImportError}}\index{ImportError@\spxentry{ImportError}!例外@\spxentry{例外}}\index{, (comma)@\spxentry{,}\spxextra{comma}!import statement@\spxentry{import statement}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-import_stmt}}\production{import\_stmt}{ "import" {\hyperref[\detokenize{reference/simple_stmts:grammar-token-module}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{module}}}}} {[}"as" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}{]} ("," {\hyperref[\detokenize{reference/simple_stmts:grammar-token-module}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{module}}}}} {[}"as" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}{]})*} \productioncont{ | "from" {\hyperref[\detokenize{reference/simple_stmts:grammar-token-relative-module}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{relative\_module}}}}} "import" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}} {[}"as" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}{]}} \productioncont{ ("," {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}} {[}"as" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}{]})*} \productioncont{ | "from" {\hyperref[\detokenize{reference/simple_stmts:grammar-token-relative-module}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{relative\_module}}}}} "import" "(" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}} {[}"as" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}{]}} \productioncont{ ("," {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}} {[}"as" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}{]})* {[}","{]} ")"} \productioncont{ | "from" {\hyperref[\detokenize{reference/simple_stmts:grammar-token-relative-module}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{relative\_module}}}}} "import" "*"} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-module}}\production{module}{ ({\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}} ".")* {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-relative_module}}\production{relative\_module}{ "."* {\hyperref[\detokenize{reference/simple_stmts:grammar-token-module}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{module}}}}} | "."+} \end{productionlist} ({\hyperref[\detokenize{reference/simple_stmts:from}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{from}}}}} 節が無い) 基本の import 文は 2 つのステップで実行されます: \begin{enumerate} \sphinxsetlistlabels{\arabic}{enumi}{enumii}{}{.}% \item {} モジュールを見付け出し、必要であればロードし初期化する \item {} {\hyperref[\detokenize{reference/simple_stmts:import}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{import}}}}} 文が表れるスコープのローカル名前空間で名前を定義する。 \end{enumerate} 文が (カンマで区切られた) 複数の節を含んでいるときは、ちょうどその節が個別の import 文に分割されたかのように、2つのステップが節ごとに個別に実行されます。 モジュールを見付け、ロードする 1 つ目のステップの詳細については、 {\hyperref[\detokenize{reference/import:importsystem}]{\sphinxcrossref{\DUrole{std,std-ref}{インポートシステム}}}} の節により詳しく書かれています。そこでは、インポートシステムの動作をカスタマイズするのに使える全てのフックの仕組みだけでなく、様々な種類のインポートできるパッケージとモジュールについても解説されています。このステップが失敗するということは、おそらくモジュールが見付からないか、 \sphinxstyleemphasis{あるいは} モジュールにあるコードの実行を含め、モジュールの初期化の途中でエラーが起きるかのどちらかが起きていることに注意してください。 要求したモジュールが無事に取得できた場合、次の 3 つのうちの 1 つの方法でローカル名前空間で使えるようになります: \index{as@\spxentry{as}!import statement@\spxentry{import statement}}\ignorespaces \begin{itemize} \item {} モジュール名の後に \sphinxcode{\sphinxupquote{as}} が続いていた場合は、 \sphinxcode{\sphinxupquote{as}} の後ろの名前を直接、インポートされたモジュールが束縛します。 \item {} 他の名前が指定されておらず、インポートされているモジュールが最上位のモジュールだった場合、そのモジュール名がインポートされたモジュールへの参照として、ローカル名前空間で束縛されます \item {} インポートされているモジュールが最上位のモジュール \sphinxstyleemphasis{でない} 場合、モジュールを含む最上位のパッケージ名が、そのパッケージへの参照として、ローカル名前空間で束縛されます。インポートされたモジュールには、直接ではなく完全修飾名を使ってアクセスしなければなりません \end{itemize} \index{name@\spxentry{name}!binding@\spxentry{binding}}\index{binding@\spxentry{binding}!name@\spxentry{name}}\index{from@\spxentry{from}!import statement@\spxentry{import statement}}\ignorespaces {\hyperref[\detokenize{reference/simple_stmts:from}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{from}}}}} 形式ではもう少し複雑な手順を踏みます: \begin{enumerate} \sphinxsetlistlabels{\arabic}{enumi}{enumii}{}{.}% \item {} {\hyperref[\detokenize{reference/simple_stmts:from}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{from}}}}} 節で指定されたモジュールを見付け出し、必要であればロードし初期化する; \item {} {\hyperref[\detokenize{reference/simple_stmts:import}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{import}}}}} 節で指定されたそれぞれの識別子に対し以下の処理を行う: \begin{enumerate} \sphinxsetlistlabels{\arabic}{enumii}{enumiii}{}{.}% \item {} インポートされたモジュールがその識別子名の属性を持っているかを確認する \item {} その識別子名の属性を持っていなかった場合は、その識別子名でサブモジュールのインポートを試み、インポートされたモジュールにその属性があるか再度確認する \item {} 属性が見付からない場合は、 \sphinxcode{\sphinxupquote{ImportError}} を送出する。 \item {} 属性が見付かった場合は、 \sphinxcode{\sphinxupquote{as}} 節があるならそこの名前、そうでないなら属性名を使って、その値への参照がローカル名前空間に保存される \end{enumerate} \end{enumerate} 例: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k+kn}{import} \PYG{n+nn}{foo} \PYG{c+c1}{\PYGZsh{} foo imported and bound locally} \PYG{k+kn}{import} \PYG{n+nn}{foo}\PYG{n+nn}{.}\PYG{n+nn}{bar}\PYG{n+nn}{.}\PYG{n+nn}{baz} \PYG{c+c1}{\PYGZsh{} foo, foo.bar, and foo.bar.baz imported, foo bound locally} \PYG{k+kn}{import} \PYG{n+nn}{foo}\PYG{n+nn}{.}\PYG{n+nn}{bar}\PYG{n+nn}{.}\PYG{n+nn}{baz} \PYG{k}{as} \PYG{n+nn}{fbb} \PYG{c+c1}{\PYGZsh{} foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as fbb} \PYG{k+kn}{from} \PYG{n+nn}{foo}\PYG{n+nn}{.}\PYG{n+nn}{bar} \PYG{k+kn}{import} \PYG{n}{baz} \PYG{c+c1}{\PYGZsh{} foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as baz} \PYG{k+kn}{from} \PYG{n+nn}{foo} \PYG{k+kn}{import} \PYG{n}{attr} \PYG{c+c1}{\PYGZsh{} foo imported and foo.attr bound as attr} \end{sphinxVerbatim} \index{* (asterisk)@\spxentry{*}\spxextra{asterisk}!import statement@\spxentry{import statement}}\ignorespaces 識別子のリストが星 (\sphinxcode{\sphinxupquote{'*'}}) に置き換わっている場合は、モジュールで定義されている公開された全ての名前が、 {\hyperref[\detokenize{reference/simple_stmts:import}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{import}}}}} 文がいるスコープのローカル名前空間に束縛されます。 \index{\_\_all\_\_ (optional module attribute)@\spxentry{\_\_all\_\_}\spxextra{optional module attribute}}\ignorespaces モジュールで定義される \sphinxstyleemphasis{公開された名前} は、モジュールの名前空間にある \sphinxcode{\sphinxupquote{\_\_all\_\_}} という名前の変数を調べることで決定されます; その変数が定義されている場合は、それはモジュールで定義されたかインポートされた名前からなる、文字列のシーケンスでなければいけません。\sphinxcode{\sphinxupquote{\_\_all\_\_}} で列挙された名前は、全て公開されていると見なされ、存在することが要求されます。\sphinxcode{\sphinxupquote{\_\_all\_\_}} が定義されていない場合、公開された名前とは、モジュールの名前空間で見付かった、アンダースコア文字 (\sphinxcode{\sphinxupquote{'\_'}}) で始まらない全ての名前のことです。\sphinxcode{\sphinxupquote{\_\_all\_\_}} は全ての公開 API を含むべきです。これは API の一部でないもの (そのモジュールでインポートされ使われているライブラリモジュールなど) をうっかり外部に公開してしまわないための仕組みです。 インポートのワイルドカード形式 \sphinxhyphen{}\sphinxhyphen{}\sphinxhyphen{} \sphinxcode{\sphinxupquote{from module import *}} \sphinxhyphen{}\sphinxhyphen{}\sphinxhyphen{} は、モジュールレベルでのみ許されます。クラスや関数定義でこの形式を使おうとすると、 \sphinxcode{\sphinxupquote{SyntaxError}} が送出されます。 \index{relative@\spxentry{relative}!import@\spxentry{import}}\ignorespaces インポートするモジュールを指定するとき、そのモジュールの絶対名 (absolute name) を指定する必要はありません。モジュールやパッケージが他のパッケージに含まれている場合、共通のトップパッケージからそのパッケージ名を記述することなく相対インポートすることができます。 {\hyperref[\detokenize{reference/simple_stmts:from}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{from}}}}} の後に指定されるモジュールやパッケージの先頭に複数個のドットを付けることで、正確な名前を指定することなしに現在のパッケージ階層からいくつ上の階層へ行くかを指定することができます。先頭のドットが 1 つの場合、 import をおこなっているモジュールが存在する現在のパッケージを示します。 3 つのドットは 2 つ上のレベルを示します。なので、 \sphinxcode{\sphinxupquote{pkg}} パッケージの中のモジュールで \sphinxcode{\sphinxupquote{from . import mod}} を実行すると、 \sphinxcode{\sphinxupquote{pkg.mod}} をインポートすることになります。 \sphinxcode{\sphinxupquote{pkg.subpkg1}} の中から \sphinxcode{\sphinxupquote{from ..subpkg2 import mod}} を実行すると、 \sphinxcode{\sphinxupquote{pkg.subpkg2.mod}} をインポートします。相対インポートの仕様は {\hyperref[\detokenize{reference/import:relativeimports}]{\sphinxcrossref{\DUrole{std,std-ref}{Package Relative Imports}}}} の節に含まれています。 どのモジュールがロードされるべきかを動的に決めたいアプリケーションのために、組み込み関数 \sphinxcode{\sphinxupquote{importlib.import\_module()}} が提供されています。 Raises an \DUrole{xref,std,std-ref}{auditing event} \sphinxcode{\sphinxupquote{import}} with arguments \sphinxcode{\sphinxupquote{module}}, \sphinxcode{\sphinxupquote{filename}}, \sphinxcode{\sphinxupquote{sys.path}}, \sphinxcode{\sphinxupquote{sys.meta\_path}}, \sphinxcode{\sphinxupquote{sys.path\_hooks}}. \subsection{future 文 (future statement)} \label{\detokenize{reference/simple_stmts:future-statements}}\label{\detokenize{reference/simple_stmts:future}} \index{future@\spxentry{future}!statement@\spxentry{statement}}\index{statement@\spxentry{statement}!future@\spxentry{future}}\index{\_\_future\_\_@\spxentry{\_\_future\_\_}!future statement@\spxentry{future statement}}\ignorespaces \sphinxstyleemphasis{future 文} は、将来の特定の新たな機能が標準化された Python のリリースで利用可能になるような構文や意味付けを使って、特定のモジュールをコンパイルさせるための、コンパイラに対する指示句 (directive) です。 future 文は互換性のない変更がされた将来の Python のバージョンに容易に移行するためのものです。future 文によって新機能が標準となるリリースの前にそれをモジュール単位で使用することが出来ます。 \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-future_stmt}}\production{future\_stmt}{ "from" "\_\_future\_\_" "import" {\hyperref[\detokenize{reference/simple_stmts:grammar-token-feature}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{feature}}}}} {[}"as" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}{]}} \productioncont{ ("," {\hyperref[\detokenize{reference/simple_stmts:grammar-token-feature}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{feature}}}}} {[}"as" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}{]})*} \productioncont{ | "from" "\_\_future\_\_" "import" "(" {\hyperref[\detokenize{reference/simple_stmts:grammar-token-feature}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{feature}}}}} {[}"as" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}{]}} \productioncont{ ("," {\hyperref[\detokenize{reference/simple_stmts:grammar-token-feature}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{feature}}}}} {[}"as" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}{]})* {[}","{]} ")"} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-feature}}\production{feature}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}} \end{productionlist} future 文は、モジュールの先頭周辺に書かなければなりません。 future 文の前に書いてよい内容は以下です : \begin{itemize} \item {} モジュールのドキュメンテーション文字列 ( あれば ) \item {} コメント , \item {} 空行 , \item {} その他の future 文。 \end{itemize} The only feature that requires using the future statement is \sphinxcode{\sphinxupquote{annotations}} (see \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 563@\spxentry{PEP 563}}\sphinxhref{https://www.python.org/dev/peps/pep-0563}{\sphinxstylestrong{PEP 563}}). future 文で有効にできる歴史的な機能は、今でも Python 3 が認識します。 そのリストは \sphinxcode{\sphinxupquote{absolute\_import}}, \sphinxcode{\sphinxupquote{division}}, \sphinxcode{\sphinxupquote{generator\_stop}}, \sphinxcode{\sphinxupquote{generators}}, \sphinxcode{\sphinxupquote{unicode\_literals}}, \sphinxcode{\sphinxupquote{print\_function}}, \sphinxcode{\sphinxupquote{nested\_scopes}}, \sphinxcode{\sphinxupquote{with\_statement}} です。 これらは既に全てが有効になっていて、後方互換性のためだけに残されているため、冗長なだけです。 future 文は、コンパイル時に特別なやり方で認識され、扱われます: 言語の中核をなす構文構成 (construct) に対する意味付けが変更されている場合、変更部分はしばしば異なるコードを生成することで実現されています。新たな機能によって、(新たな予約語のような) 互換性のない新たな構文が取り入れられることさえあります。この場合、コンパイラはモジュールを別のやりかたで解析する必要があるかもしれません。こうしたコード生成に関する決定は、実行時まで先延ばしすることはできません。 これまでの全てのリリースにおいて、コンパイラはどの機能が定義済みかを知っており、 future 文に未知の機能が含まれている場合にはコンパイル時エラーを送出します。 future 文の実行時における直接的な意味付けは、 import 文と同じです。標準モジュール \sphinxcode{\sphinxupquote{\_\_future\_\_}} があり、これについては後で述べます。 \sphinxcode{\sphinxupquote{\_\_future\_\_}} は、 future 文が実行される際に通常の方法で import されます。 future 文の実行時における特別な意味付けは、 future 文で有効化される特定の機能によって変わります。 以下の文には、何ら特殊な意味はないので注意してください: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k+kn}{import} \PYG{n+nn}{\PYGZus{}\PYGZus{}future\PYGZus{}\PYGZus{}} \PYG{p}{[}\PYG{k}{as} \PYG{n}{name}\PYG{p}{]} \end{sphinxVerbatim} これは future 文ではありません; この文は通常の import 文であり、その他の特殊な意味付けや構文的な制限はありません。 future 文の入ったモジュール \sphinxcode{\sphinxupquote{M}} 内で使われている組み込み関数 \sphinxcode{\sphinxupquote{exec()}} や \sphinxcode{\sphinxupquote{compile()}} によってコンパイルされるコードは、デフォルトの設定では、 future 文に関係する新たな構文や意味付けを使うようになっています。この仕様は \sphinxcode{\sphinxupquote{compile()}} のオプション引数で制御できます \sphinxhyphen{}\sphinxhyphen{}\sphinxhyphen{} 詳細はこの関数に関するドキュメントを参照してください。 対話的インタプリタのプロンプトでタイプ入力した future 文は、その後のインタプリタセッション中で有効になります。インタプリタを \sphinxcode{\sphinxupquote{\sphinxhyphen{}i}} オプションで起動して実行すべきスクリプト名を渡し、スクリプト中に future 文を入れておくと、新たな機能はスクリプトが実行された後に開始する対話セッションで有効になります。 \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 236@\spxentry{PEP 236}}\sphinxhref{https://www.python.org/dev/peps/pep-0236}{\sphinxstylestrong{PEP 236}} \sphinxhyphen{} Back to the \_\_future\_\_}] \leavevmode \_\_future\_\_ 機構の原案 \end{description} \section{\sphinxstyleliteralintitle{\sphinxupquote{global}} 文} \label{\detokenize{reference/simple_stmts:the-global-statement}}\label{\detokenize{reference/simple_stmts:global}} \index{文@\spxentry{文}!global@\spxentry{global}|spxpagem}\index{global@\spxentry{global}!文@\spxentry{文}|spxpagem}\index{global@\spxentry{global}!name binding@\spxentry{name} \spxentry{binding}}\index{name@\spxentry{name}!binding, global@\spxentry{binding}, \spxentry{global}}\index{binding@\spxentry{binding}!global name@\spxentry{global} \spxentry{name}}\index{, (comma)@\spxentry{,}\spxextra{comma}!identifier list@\spxentry{identifier list}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-global_stmt}}\production{global\_stmt}{ "global" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}} ("," {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}})*} \end{productionlist} {\hyperref[\detokenize{reference/simple_stmts:global}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{global}}}}} 文は、現在のコードブロック全体で維持される宣言文です。 {\hyperref[\detokenize{reference/simple_stmts:global}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{global}}}}} 文は、列挙した識別子をグローバル変数として解釈するよう指定することを意味します。 \sphinxcode{\sphinxupquote{global}} を使わずにグローバル変数に代入を行うことは不可能ですが、自由変数を使えばその変数をグローバルであると宣言せずにグローバル変数を参照することができます。 {\hyperref[\detokenize{reference/simple_stmts:global}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{global}}}}} 文で列挙する名前は、同じコードブロック中で、プログラムテキスト上 \sphinxcode{\sphinxupquote{global}} 文より前に使ってはなりません。 {\hyperref[\detokenize{reference/simple_stmts:global}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{global}}}}} 文で列挙する名前は、 {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} ループのループ制御ターゲットや、 {\hyperref[\detokenize{reference/compound_stmts:class}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{class}}}}} 定義、関数定義、 {\hyperref[\detokenize{reference/simple_stmts:import}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{import}}}}} 文、変数アノテーションで仮引数として使ってはなりません。 \sphinxstylestrong{CPython implementation detail:} 現在の実装では、これらの制限のうち幾つかについては強制していませんが、プログラムでこの緩和された仕様を乱用すべきではありません。将来の実装では、この制限を強制したり、暗黙のうちにプログラムの意味付けを変更したりする可能性があります。 \index{組み込み関数@\spxentry{組み込み関数}!exec@\spxentry{exec}}\index{exec@\spxentry{exec}!組み込み関数@\spxentry{組み込み関数}}\index{組み込み関数@\spxentry{組み込み関数}!eval@\spxentry{eval}}\index{eval@\spxentry{eval}!組み込み関数@\spxentry{組み込み関数}}\index{組み込み関数@\spxentry{組み込み関数}!compile@\spxentry{compile}}\index{compile@\spxentry{compile}!組み込み関数@\spxentry{組み込み関数}}\ignorespaces \sphinxstylestrong{プログラマのための注意点:} {\hyperref[\detokenize{reference/simple_stmts:global}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{global}}}}} はパーザに対する指示句 (directive) です。この指示句は、 \sphinxcode{\sphinxupquote{global}} 文と同時に読み込まれたコードに対してのみ適用されます。特に、組み込みの \sphinxcode{\sphinxupquote{exec()}} 関数内に入っている \sphinxcode{\sphinxupquote{global}} 文は、関数の呼び出しを \sphinxstyleemphasis{含んでいる} コードブロック内に効果を及ぼすことはなく、そのような文字列に含まれているコードは、関数の呼び出しを含むコード内の \sphinxcode{\sphinxupquote{global}} 文に影響を受けません。同様のことが、関数 \sphinxcode{\sphinxupquote{eval()}} および \sphinxcode{\sphinxupquote{compile()}} にも当てはまります。 \section{\sphinxstyleliteralintitle{\sphinxupquote{nonlocal}} 文} \label{\detokenize{reference/simple_stmts:the-nonlocal-statement}}\label{\detokenize{reference/simple_stmts:nonlocal}} \index{文@\spxentry{文}!nonlocal@\spxentry{nonlocal}}\index{nonlocal@\spxentry{nonlocal}!文@\spxentry{文}}\index{, (comma)@\spxentry{,}\spxextra{comma}!identifier list@\spxentry{identifier list}}\ignorespaces \begin{productionlist} \phantomsection\label{\detokenize{reference/simple_stmts:grammar-token-nonlocal_stmt}}\production{nonlocal\_stmt}{ "nonlocal" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}} ("," {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}})*} \end{productionlist} {\hyperref[\detokenize{reference/simple_stmts:nonlocal}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{nonlocal}}}}} 文は、列挙された識別子がグローバルを除く一つ外側のスコープで先に束縛された変数を参照するようにします。これは、束縛のデフォルトの動作がまずローカル名前空間を探索するので重要です。この文は、中にあるコードが、グローバル (モジュール) スコープ以外のローカルスコープの外側の変数を再束縛できるようにします。 {\hyperref[\detokenize{reference/simple_stmts:nonlocal}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{nonlocal}}}}} 文で列挙された名前は、 {\hyperref[\detokenize{reference/simple_stmts:global}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{global}}}}} 文で列挙された名前と違い、外側のスコープですでに存在する束縛を参照しなければなりません (新しい束縛が作られるべきスコープの選択が曖昧さを排除できません)。 {\hyperref[\detokenize{reference/simple_stmts:nonlocal}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{nonlocal}}}}} 文で列挙された名前は、ローカルスコープですでに存在する束縛と衝突してはなりません。 \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 3104@\spxentry{PEP 3104}}\sphinxhref{https://www.python.org/dev/peps/pep-3104}{\sphinxstylestrong{PEP 3104}} \sphinxhyphen{} Access to Names in Outer Scopes}] \leavevmode {\hyperref[\detokenize{reference/simple_stmts:nonlocal}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{nonlocal}}}}} 文の詳細。 \end{description} \chapter{複合文 (compound statement)} \label{\detokenize{reference/compound_stmts:compound-statements}}\label{\detokenize{reference/compound_stmts:compound}}\label{\detokenize{reference/compound_stmts::doc}} \index{compound@\spxentry{compound}!statement@\spxentry{statement}}\index{statement@\spxentry{statement}!compound@\spxentry{compound}}\ignorespaces 複合文には、他の文 (のグループ) が入ります; 複合文は、中に入っている他の文の実行の制御に何らかのやり方で影響を及ぼします。一般的には、複合文は複数行にまたがって書かれますが、全部の文を一行に連ねた単純な書き方もあります。 {\hyperref[\detokenize{reference/compound_stmts:if}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{if}}}}} 、 {\hyperref[\detokenize{reference/compound_stmts:while}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{while}}}}} 、および {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} 文は、伝統的な制御フロー構成を実現します。 {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} は例外処理および/または一連の文に対するクリーンアップコードを指定します。それに対して、 {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}} 文はコードのかたまりの前後でコードの初期化と終了処理を実行できるようにします。関数とクラス定義もまた、構文的には複合文です。 \index{clause@\spxentry{clause}}\index{suite@\spxentry{suite}}\index{; (semicolon)@\spxentry{;}\spxextra{semicolon}}\ignorespaces 複合文は、一つ以上の '節 (clause)' からなります。節は、ヘッダと 'スイート (suite)' からなります。一つの複合文を成す各節のヘッダは、全て同じインデントレベルに置かれます。各節のヘッダは一意に識別するキーワードで始まり、コロンで終わります。スイートは、節によって制御される文の集まりです。スイートは、ヘッダがある行のコロンの後にセミコロンで区切って置かれた一つ以上の単純文、または、ヘッダに続く行で一つ多くインデントされた文の集まりです。後者の形式のスイートに限り、さらに複合文をネストできます; 以下の文は、 {\hyperref[\detokenize{reference/compound_stmts:else}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{else}}}}} 節がどちらの {\hyperref[\detokenize{reference/compound_stmts:if}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{if}}}}} 節に属するかがはっきりしないなどの理由から不正になります: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{if} \PYG{n}{test1}\PYG{p}{:} \PYG{k}{if} \PYG{n}{test2}\PYG{p}{:} \PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)} \end{sphinxVerbatim} また、このコンテキスト中では、セミコロンによる結合はコロンより強いです。従って、以下の例では、 \sphinxcode{\sphinxupquote{print()}} の呼び出しはは全て実行されるか、全く実行されないかのどちらかです: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{if} \PYG{n}{x} \PYG{o}{\PYGZlt{}} \PYG{n}{y} \PYG{o}{\PYGZlt{}} \PYG{n}{z}\PYG{p}{:} \PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;} \PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{y}\PYG{p}{)}\PYG{p}{;} \PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{z}\PYG{p}{)} \end{sphinxVerbatim} まとめると、以下のようになります: \begin{productionlist} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-compound_stmt}}\production{compound\_stmt}{ {\hyperref[\detokenize{reference/compound_stmts:grammar-token-if-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{if\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-while-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{while\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-for-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-try-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-with-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-funcdef}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{funcdef}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-classdef}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{classdef}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-async-with-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async\_with\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-async-for-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async\_for\_stmt}}}}}} \productioncont{ | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-async-funcdef}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async\_funcdef}}}}}} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-suite}}\production{suite}{ {\hyperref[\detokenize{reference/compound_stmts:grammar-token-stmt-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{stmt\_list}}}}} NEWLINE | NEWLINE INDENT {\hyperref[\detokenize{reference/compound_stmts:grammar-token-statement}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{statement}}}}}+ DEDENT} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-statement}}\production{statement}{ {\hyperref[\detokenize{reference/compound_stmts:grammar-token-stmt-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{stmt\_list}}}}} NEWLINE | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-compound-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{compound\_stmt}}}}}} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-stmt_list}}\production{stmt\_list}{ {\hyperref[\detokenize{reference/simple_stmts:grammar-token-simple-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{simple\_stmt}}}}} (";" {\hyperref[\detokenize{reference/simple_stmts:grammar-token-simple-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{simple\_stmt}}}}})* {[}";"{]}} \end{productionlist} \index{NEWLINE token@\spxentry{NEWLINE token}}\index{DEDENT token@\spxentry{DEDENT token}}\index{dangling@\spxentry{dangling}!else@\spxentry{else}}\index{else@\spxentry{else}!dangling@\spxentry{dangling}}\ignorespaces なお、文は常に \sphinxcode{\sphinxupquote{NEWLINE}} か、その後に \sphinxcode{\sphinxupquote{DEDENT}} が続いたもので終了します。また、オプションの継続節は必ず、文を開始できない予約語で始まるので、曖昧さは存在しません。 (Python では、 'ぶら下がり (dangling) {\hyperref[\detokenize{reference/compound_stmts:else}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{else}}}}}' 問題は、ネストされた {\hyperref[\detokenize{reference/compound_stmts:if}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{if}}}}} 文をインデントさせることで解決されます)。 以下の節における文法規則の記述方式は、明確さのために、各節を別々の行に書くようにしています。 \section{\sphinxstyleliteralintitle{\sphinxupquote{if}} 文} \label{\detokenize{reference/compound_stmts:the-if-statement}}\label{\detokenize{reference/compound_stmts:else}}\label{\detokenize{reference/compound_stmts:elif}}\label{\detokenize{reference/compound_stmts:if}} \index{文@\spxentry{文}!if@\spxentry{if}|spxpagem}\index{if@\spxentry{if}!文@\spxentry{文}|spxpagem}\index{キーワード@\spxentry{キーワード}!elif@\spxentry{elif}}\index{elif@\spxentry{elif}!キーワード@\spxentry{キーワード}}\index{キーワード@\spxentry{キーワード}!else@\spxentry{else}}\index{else@\spxentry{else}!キーワード@\spxentry{キーワード}}\index{: (colon)@\spxentry{:}\spxextra{colon}!compound statement@\spxentry{compound statement}}\ignorespaces {\hyperref[\detokenize{reference/compound_stmts:if}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{if}}}}} 文は、条件分岐を実行するために使われます: \begin{productionlist} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-if_stmt}}\production{if\_stmt}{ "if" {\hyperref[\detokenize{reference/expressions:grammar-token-assignment-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{assignment\_expression}}}}} ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}} \productioncont{ ("elif" {\hyperref[\detokenize{reference/expressions:grammar-token-assignment-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{assignment\_expression}}}}} ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}})*} \productioncont{ {[}"else" ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}{]}} \end{productionlist} {\hyperref[\detokenize{reference/compound_stmts:if}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{if}}}}} 文は、式を一つ一つ評価してゆき、真になるまで続けて、真になった節のスイートだけを選択します (真: true と偽: false の定義については、 {\hyperref[\detokenize{reference/expressions:booleans}]{\sphinxcrossref{\DUrole{std,std-ref}{ブール演算 (boolean operation)}}}} 節を参照してください); 次に、選択したスイートを実行します (そして、 {\hyperref[\detokenize{reference/compound_stmts:if}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{if}}}}} 文の他の部分は、実行や評価をされません)。全ての式が偽になった場合、 {\hyperref[\detokenize{reference/compound_stmts:else}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{else}}}}} 節があれば、そのスイートが実行されます。 \section{\sphinxstyleliteralintitle{\sphinxupquote{while}} 文} \label{\detokenize{reference/compound_stmts:the-while-statement}}\label{\detokenize{reference/compound_stmts:while}} \index{文@\spxentry{文}!while@\spxentry{while}|spxpagem}\index{while@\spxentry{while}!文@\spxentry{文}|spxpagem}\index{キーワード@\spxentry{キーワード}!else@\spxentry{else}}\index{else@\spxentry{else}!キーワード@\spxentry{キーワード}}\index{loop@\spxentry{loop}!statement@\spxentry{statement}}\index{statement@\spxentry{statement}!loop@\spxentry{loop}}\index{: (colon)@\spxentry{:}\spxextra{colon}!compound statement@\spxentry{compound statement}}\ignorespaces {\hyperref[\detokenize{reference/compound_stmts:while}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{while}}}}} 文は、式の値が真である間、実行を繰り返すために使われます: \begin{productionlist} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-while_stmt}}\production{while\_stmt}{ "while" {\hyperref[\detokenize{reference/expressions:grammar-token-assignment-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{assignment\_expression}}}}} ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}} \productioncont{ {[}"else" ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}{]}} \end{productionlist} {\hyperref[\detokenize{reference/compound_stmts:while}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{while}}}}} 文は式を繰り返し真偽評価し、真であれば最初のスイートを実行します。式が偽であれば (最初から偽になっていることもありえます)、 \sphinxcode{\sphinxupquote{else}} 節がある場合にはそれを実行し、ループを終了します。 \index{文@\spxentry{文}!break@\spxentry{break}}\index{break@\spxentry{break}!文@\spxentry{文}}\index{文@\spxentry{文}!continue@\spxentry{continue}}\index{continue@\spxentry{continue}!文@\spxentry{文}}\ignorespaces 最初のスイート内で {\hyperref[\detokenize{reference/simple_stmts:break}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{break}}}}} 文が実行されると、 \sphinxcode{\sphinxupquote{else}} 節のスイートを実行することなくループを終了します。 {\hyperref[\detokenize{reference/simple_stmts:continue}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{continue}}}}} 文が最初のスイート内で実行されると、スイート内にある残りの文の実行をスキップして、式の真偽評価に戻ります。 \section{\sphinxstyleliteralintitle{\sphinxupquote{for}} 文} \label{\detokenize{reference/compound_stmts:the-for-statement}}\label{\detokenize{reference/compound_stmts:for}} \index{文@\spxentry{文}!for@\spxentry{for}|spxpagem}\index{for@\spxentry{for}!文@\spxentry{文}|spxpagem}\index{キーワード@\spxentry{キーワード}!in@\spxentry{in}}\index{in@\spxentry{in}!キーワード@\spxentry{キーワード}}\index{キーワード@\spxentry{キーワード}!else@\spxentry{else}}\index{else@\spxentry{else}!キーワード@\spxentry{キーワード}}\index{target@\spxentry{target}!list@\spxentry{list}}\index{list@\spxentry{list}!target@\spxentry{target}}\index{loop@\spxentry{loop}!statement@\spxentry{statement}}\index{statement@\spxentry{statement}!loop@\spxentry{loop}}\index{オブジェクト@\spxentry{オブジェクト}!sequence@\spxentry{sequence}}\index{sequence@\spxentry{sequence}!オブジェクト@\spxentry{オブジェクト}}\index{: (colon)@\spxentry{:}\spxextra{colon}!compound statement@\spxentry{compound statement}}\ignorespaces {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} 文は、シーケンス (文字列、タプルまたはリスト) や、その他の反復可能なオブジェクト (iterable object) 内の要素に渡って反復処理を行うために使われます: \begin{productionlist} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-for_stmt}}\production{for\_stmt}{ "for" {\hyperref[\detokenize{reference/simple_stmts:grammar-token-target-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{target\_list}}}}} "in" {\hyperref[\detokenize{reference/expressions:grammar-token-expression-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression\_list}}}}} ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}} \productioncont{ {[}"else" ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}{]}} \end{productionlist} 式リストは一度だけ評価されます。その結果はイテラブルオブジェクトにならなければなりません。 \sphinxcode{\sphinxupquote{expression\_list}} の結果に対するイテレータが生成されます。 その後、イテレータが与えるそれぞれの要素に対して、イテレータから返された順に一度づつ、スイートが実行されます。 それぞれの要素は標準の代入規則 ({\hyperref[\detokenize{reference/simple_stmts:assignment}]{\sphinxcrossref{\DUrole{std,std-ref}{代入文 (assignment statement)}}}} を参照してください) で target\_list に代入され、その後、スイートが実行されます。 全ての要素を使い切ったとき (シーケンスが空であったり、イテレータが \sphinxcode{\sphinxupquote{StopIteration}} 例外を送出したときは、即座に)、 \sphinxcode{\sphinxupquote{else}} 節があればそれが実行され、ループは終了します。 \index{文@\spxentry{文}!break@\spxentry{break}}\index{break@\spxentry{break}!文@\spxentry{文}}\index{文@\spxentry{文}!continue@\spxentry{continue}}\index{continue@\spxentry{continue}!文@\spxentry{文}}\ignorespaces 最初のスイートの中で {\hyperref[\detokenize{reference/simple_stmts:break}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{break}}}}} 文が実行されると、 \sphinxcode{\sphinxupquote{else}} 節のスイートを実行することなくループを終了します。 {\hyperref[\detokenize{reference/simple_stmts:continue}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{continue}}}}} 文が最初のスイート内で実行されると、スイート内にある残りの文の実行をスキップして、次の要素の処理に移るか、これ以上次の要素が無い場合は \sphinxcode{\sphinxupquote{else}} 節の処理に移ります。 for ループはターゲットリスト内の変数への代入を行います。 これにより、for ループ内も含めて、それ以前の全ての代入は上書きされます: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{for} \PYG{n}{i} \PYG{o+ow}{in} \PYG{n+nb}{range}\PYG{p}{(}\PYG{l+m+mi}{10}\PYG{p}{)}\PYG{p}{:} \PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{i}\PYG{p}{)} \PYG{n}{i} \PYG{o}{=} \PYG{l+m+mi}{5} \PYG{c+c1}{\PYGZsh{} this will not affect the for\PYGZhy{}loop} \PYG{c+c1}{\PYGZsh{} because i will be overwritten with the next} \PYG{c+c1}{\PYGZsh{} index in the range} \end{sphinxVerbatim} \index{組み込み関数@\spxentry{組み込み関数}!range@\spxentry{range}}\index{range@\spxentry{range}!組み込み関数@\spxentry{組み込み関数}}\ignorespaces ループが終了してもターゲットリスト内の名前は削除されませんが、イテラブルが空の場合には、ループでの代入は全く行われません。ヒント: 組み込み関数 \sphinxcode{\sphinxupquote{range()}} は、 Pascal の \sphinxcode{\sphinxupquote{for i := a to b do}} の効果をエミュレートするのに適した、整数のイテレータを返します; すなわち、 \sphinxcode{\sphinxupquote{list(range(3))}} はリスト \sphinxcode{\sphinxupquote{{[}0, 1, 2{]}}} を返します。 \begin{sphinxadmonition}{note}{注釈:} \index{loop@\spxentry{loop}!over mutable sequence@\spxentry{over mutable sequence}}\index{mutable sequence@\spxentry{mutable sequence}!loop over@\spxentry{loop over}}\ignorespaces ループ中でのシーケンスの変更には微妙な問題があります (これはミュータブルなシーケンスのみ、例えばリストで起こり得ます)。 どの要素が次に使われるかを追跡するために、内部的なカウンタが使われており、このカウンタは反復のたびに加算されます。 このカウンタがシーケンスの長さに達すると、ループは終了します。 このことから、スイートの中でシーケンスから現在の (または以前の) 要素を除去すると、(次の要素の位置が、既に処理済みの現在の要素のインデックスになるために) 次の要素が飛ばされることになります。 同様に、スイートの中でシーケンス中の現在の要素以前に要素を挿入すると、現在の要素がループの次の週で再度扱われることになります。 こうした仕様は、厄介なバグにつながります。 これは、シーケンス全体のスライスを使って一時的なコピーを作ることで避けられます。 例えば次のようにします: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{for} \PYG{n}{x} \PYG{o+ow}{in} \PYG{n}{a}\PYG{p}{[}\PYG{p}{:}\PYG{p}{]}\PYG{p}{:} \PYG{k}{if} \PYG{n}{x} \PYG{o}{\PYGZlt{}} \PYG{l+m+mi}{0}\PYG{p}{:} \PYG{n}{a}\PYG{o}{.}\PYG{n}{remove}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)} \end{sphinxVerbatim} \end{sphinxadmonition} \section{\sphinxstyleliteralintitle{\sphinxupquote{try}} 文} \label{\detokenize{reference/compound_stmts:the-try-statement}}\label{\detokenize{reference/compound_stmts:finally}}\label{\detokenize{reference/compound_stmts:except}}\label{\detokenize{reference/compound_stmts:try}} \index{文@\spxentry{文}!try@\spxentry{try}|spxpagem}\index{try@\spxentry{try}!文@\spxentry{文}|spxpagem}\index{キーワード@\spxentry{キーワード}!except@\spxentry{except}}\index{except@\spxentry{except}!キーワード@\spxentry{キーワード}}\index{キーワード@\spxentry{キーワード}!finally@\spxentry{finally}}\index{finally@\spxentry{finally}!キーワード@\spxentry{キーワード}}\index{キーワード@\spxentry{キーワード}!else@\spxentry{else}}\index{else@\spxentry{else}!キーワード@\spxentry{キーワード}}\index{キーワード@\spxentry{キーワード}!as@\spxentry{as}}\index{as@\spxentry{as}!キーワード@\spxentry{キーワード}}\index{: (colon)@\spxentry{:}\spxextra{colon}!compound statement@\spxentry{compound statement}}\ignorespaces {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} 文は、ひとまとめの文に対して、例外処理および/またはクリーンアップコードを指定します: \begin{productionlist} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-try_stmt}}\production{try\_stmt}{ {\hyperref[\detokenize{reference/compound_stmts:grammar-token-try1-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try1\_stmt}}}}} | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-try2-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try2\_stmt}}}}}} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-try1_stmt}}\production{try1\_stmt}{ "try" ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}} \productioncont{ ("except" {[}{\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} {[}"as" {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}{]}{]} ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}})+} \productioncont{ {[}"else" ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}{]}} \productioncont{ {[}"finally" ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}{]}} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-try2_stmt}}\production{try2\_stmt}{ "try" ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}} \productioncont{ "finally" ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}} \end{productionlist} The {\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}} clause(s) specify one or more exception handlers. When no exception occurs in the {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} clause, no exception handler is executed. When an exception occurs in the \sphinxcode{\sphinxupquote{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\sphinxhyphen{}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 {\hyperref[\detokenize{glossary:term-abstract-base-class}]{\sphinxtermref{\DUrole{xref,std,std-term}{non\sphinxhyphen{}virtual base class}}}} of the exception object, or a tuple containing an item that is the class or a non\sphinxhyphen{}virtual base class of the exception object. 例外がどの {\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}} 節にも合致しなかった場合、現在のコードを囲うさらに外側、そして呼び出しスタックへと検索を続けます。 % \begin{footnote}[1]\sphinxAtStartFootnote 例外は、別の例外を送出するような {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節が無い場合にのみ呼び出しスタックへ伝わります。新しい例外によって、古い例外は失われます。 % \end{footnote} {\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}} 節のヘッダにある式を値評価するときに例外が発生すると、元々のハンドラ検索はキャンセルされ、新たな例外に対する例外ハンドラの検索を現在の {\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}} 節の外側のコードや呼び出しスタックに対して行います ({\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} 文全体が例外を発行したかのように扱われます)。 \index{as@\spxentry{as}!except clause@\spxentry{except clause}}\ignorespaces 対応する except 節が見つかると、except 節のスイートが実行されます。その際、 \sphinxcode{\sphinxupquote{as}} キーワードが存在すれば、その後で指定されているターゲットに例外が代入されます。全ての {\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}} 節は実行可能なブロックを持っていなければなりません。このブロックの末尾に到達すると、通常は {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} 文全体の直後から実行を継続します。(このことは、ネストされた二つの例外ハンドラが同じ例外に対して存在し、内側のハンドラ内の {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} 節で例外が発生した場合、外側のハンドラはその例外を処理しないことを意味します。) 例外が \sphinxcode{\sphinxupquote{as target}} を使って代入されたとき、それは except 節の終わりに消去されます。これはちょうど、以下のコード: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{except} \PYG{n}{E} \PYG{k}{as} \PYG{n}{N}\PYG{p}{:} \PYG{n}{foo} \end{sphinxVerbatim} が、以下のコードに翻訳されたかのようなものです: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{except} \PYG{n}{E} \PYG{k}{as} \PYG{n}{N}\PYG{p}{:} \PYG{k}{try}\PYG{p}{:} \PYG{n}{foo} \PYG{k}{finally}\PYG{p}{:} \PYG{k}{del} \PYG{n}{N} \end{sphinxVerbatim} よって、例外を except 節以降で参照できるようにするためには、別の名前に代入されなければなりません。例外が削除されるのは、トレースバックが付与されると、そのスタックフレームと循環参照を形作り、次のガベージ収集までそのフレーム内のすべての局所変数を生存させてしまうからです。 \index{モジュール@\spxentry{モジュール}!sys@\spxentry{sys}}\index{sys@\spxentry{sys}!モジュール@\spxentry{モジュール}}\index{オブジェクト@\spxentry{オブジェクト}!traceback@\spxentry{traceback}}\index{traceback@\spxentry{traceback}!オブジェクト@\spxentry{オブジェクト}}\ignorespaces {\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}} 節のスイートが実行される前に、例外に関する詳細が \sphinxcode{\sphinxupquote{sys}} モジュールに保存され、 \sphinxcode{\sphinxupquote{sys.exc\_info()}} からアクセスできます。 \sphinxcode{\sphinxupquote{sys.exc\_info()}} は、例外クラス、例外インスタンス、そして例外が発生したプログラム上の位置を識別するトレースバックオブジェクト ({\hyperref[\detokenize{reference/datamodel:types}]{\sphinxcrossref{\DUrole{std,std-ref}{標準型の階層}}}} を参照してください) の 3 要素からなるタプルを返します。 \sphinxcode{\sphinxupquote{sys.exc\_info()}} の値は、例外を処理した関数から戻るときに、以前 (関数呼び出し前) の値に戻されます。 \index{キーワード@\spxentry{キーワード}!else@\spxentry{else}}\index{else@\spxentry{else}!キーワード@\spxentry{キーワード}}\index{文@\spxentry{文}!return@\spxentry{return}}\index{return@\spxentry{return}!文@\spxentry{文}}\index{文@\spxentry{文}!break@\spxentry{break}}\index{break@\spxentry{break}!文@\spxentry{文}}\index{文@\spxentry{文}!continue@\spxentry{continue}}\index{continue@\spxentry{continue}!文@\spxentry{文}}\ignorespaces オプションの \sphinxcode{\sphinxupquote{else}} 節は、コントロールフローが {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} スイートを抜け、例外が送出されず、 {\hyperref[\detokenize{reference/simple_stmts:return}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{return}}}}} 文、 {\hyperref[\detokenize{reference/simple_stmts:continue}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{continue}}}}} 文、 {\hyperref[\detokenize{reference/simple_stmts:break}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{break}}}}} 文のいずれもが実行されなかった場合に実行されます。 \sphinxcode{\sphinxupquote{else}} 節で起きた例外は、手前にある {\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}} 節では処理されません。 \index{キーワード@\spxentry{キーワード}!finally@\spxentry{finally}}\index{finally@\spxentry{finally}!キーワード@\spxentry{キーワード}}\ignorespaces {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節がある場合は、 '後始末' の対処を指定します。まず {\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}} 節や {\hyperref[\detokenize{reference/compound_stmts:else}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{else}}}}} 節を含め、 {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} 節が実行されます。それらの節の中で例外が起き、その例外が処理されていない場合には、例外は一時的に保存されます。次に {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節が実行されます。保存された例外があった場合は、 {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節の末尾で再送出されます。 {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節で別の例外が送出される場合は、保存されていた例外は新しい例外のコンテキストとして設定されます。 {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節で {\hyperref[\detokenize{reference/simple_stmts:return}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{return}}}}} 文あるいは {\hyperref[\detokenize{reference/simple_stmts:break}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{break}}}}} 文を実行した場合は、保存された例外は破棄されます: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k}{def} \PYG{n+nf}{f}\PYG{p}{(}\PYG{p}{)}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{try}\PYG{p}{:} \PYG{g+gp}{... } \PYG{l+m+mi}{1}\PYG{o}{/}\PYG{l+m+mi}{0} \PYG{g+gp}{... } \PYG{k}{finally}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{return} \PYG{l+m+mi}{42} \PYG{g+gp}{...} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{f}\PYG{p}{(}\PYG{p}{)} \PYG{g+go}{42} \end{sphinxVerbatim} {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節を実行している間は、プログラムからは例外情報は利用できません。 \index{文@\spxentry{文}!return@\spxentry{return}}\index{return@\spxentry{return}!文@\spxentry{文}}\index{文@\spxentry{文}!break@\spxentry{break}}\index{break@\spxentry{break}!文@\spxentry{文}}\index{文@\spxentry{文}!continue@\spxentry{continue}}\index{continue@\spxentry{continue}!文@\spxentry{文}}\ignorespaces {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}}...{\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 文の {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} スイート内で {\hyperref[\detokenize{reference/simple_stmts:return}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{return}}}}} 、 {\hyperref[\detokenize{reference/simple_stmts:break}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{break}}}}} 、または {\hyperref[\detokenize{reference/simple_stmts:continue}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{continue}}}}} 文が実行された場合、 {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節も、この文を '抜け出る途中に' 実行されます。 関数の返り値は最後に実行された {\hyperref[\detokenize{reference/simple_stmts:return}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{return}}}}} 文によって決まります。 {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節は必ず実行されるため、\sphinxcode{\sphinxupquote{finally}} 節で実行された \sphinxcode{\sphinxupquote{return}} 文は常に最後に実行されることになります: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k}{def} \PYG{n+nf}{foo}\PYG{p}{(}\PYG{p}{)}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{try}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{return} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{try}\PYG{l+s+s1}{\PYGZsq{}} \PYG{g+gp}{... } \PYG{k}{finally}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{return} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{finally}\PYG{l+s+s1}{\PYGZsq{}} \PYG{g+gp}{...} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{foo}\PYG{p}{(}\PYG{p}{)} \PYG{g+go}{\PYGZsq{}finally\PYGZsq{}} \end{sphinxVerbatim} 例外に関するその他の情報は {\hyperref[\detokenize{reference/executionmodel:exceptions}]{\sphinxcrossref{\DUrole{std,std-ref}{例外}}}} 節にあります。また、 {\hyperref[\detokenize{reference/simple_stmts:raise}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{raise}}}}} 文の使用による例外の生成に関する情報は、 {\hyperref[\detokenize{reference/simple_stmts:raise}]{\sphinxcrossref{\DUrole{std,std-ref}{raise 文}}}} 節にあります。 \DUrole{versionmodified,changed}{バージョン 3.8 で変更: }Python3.8 以前では、実装上の問題により {\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 節での {\hyperref[\detokenize{reference/simple_stmts:continue}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{continue}}}}} 文は不正でした。 \section{\sphinxstyleliteralintitle{\sphinxupquote{with}} 文} \label{\detokenize{reference/compound_stmts:the-with-statement}}\label{\detokenize{reference/compound_stmts:as}}\label{\detokenize{reference/compound_stmts:with}} \index{文@\spxentry{文}!with@\spxentry{with}|spxpagem}\index{with@\spxentry{with}!文@\spxentry{文}|spxpagem}\index{キーワード@\spxentry{キーワード}!as@\spxentry{as}}\index{as@\spxentry{as}!キーワード@\spxentry{キーワード}}\index{as@\spxentry{as}!with statement@\spxentry{with statement}}\index{, (comma)@\spxentry{,}\spxextra{comma}!with statement@\spxentry{with statement}}\index{: (colon)@\spxentry{:}\spxextra{colon}!compound statement@\spxentry{compound statement}}\ignorespaces {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}} 文は、ブロックの実行を、コンテキストマネージャによって定義されたメソッドでラップするために使われます ({\hyperref[\detokenize{reference/datamodel:context-managers}]{\sphinxcrossref{\DUrole{std,std-ref}{with文とコンテキストマネージャ}}}} セクションを参照してください)。これにより、よくある {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}}...{\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}}...{\hyperref[\detokenize{reference/compound_stmts:finally}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{finally}}}}} 利用パターンをカプセル化して便利に再利用することができます。 \begin{productionlist} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-with_stmt}}\production{with\_stmt}{ "with" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-with-item}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with\_item}}}}} ("," {\hyperref[\detokenize{reference/compound_stmts:grammar-token-with-item}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with\_item}}}}})* ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-with_item}}\production{with\_item}{ {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}} {[}"as" {\hyperref[\detokenize{reference/simple_stmts:grammar-token-target}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{target}}}}}{]}} \end{productionlist} 一つの "要素" を持つ {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}} 文の実行は以下のように進行します: \begin{enumerate} \sphinxsetlistlabels{\arabic}{enumi}{enumii}{}{.}% \item {} コンテキスト式 ({\hyperref[\detokenize{reference/compound_stmts:grammar-token-with-item}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with\_item}}}}} で与えられた式) を評価することで、コンテキストマネージャを取得します。 \item {} コンテキストマネージャの {\hyperref[\detokenize{reference/datamodel:object.__enter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_enter\_\_()}}}}} メソッドが、後で使うためにロードされます。 \item {} コンテキストマネージャの {\hyperref[\detokenize{reference/datamodel:object.__exit__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_exit\_\_()}}}}} メソッドが、後で使うためにロードされます。 \item {} コンテキストマネージャの {\hyperref[\detokenize{reference/datamodel:object.__enter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_enter\_\_()}}}}} メソッドが呼ばれます。 \item {} {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}} 文にターゲットが含まれていたら、それに {\hyperref[\detokenize{reference/datamodel:object.__enter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_enter\_\_()}}}}} からの戻り値が代入されます。 \begin{sphinxadmonition}{note}{注釈:} {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}} 文は、 {\hyperref[\detokenize{reference/datamodel:object.__enter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_enter\_\_()}}}}} メソッドがエラーなく終了した場合には {\hyperref[\detokenize{reference/datamodel:object.__exit__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_exit\_\_()}}}}} が常に呼ばれることを保証します。ですので、もしターゲットリストへの代入中にエラーが発生した場合には、これはそのスイートの中で発生したエラーと同じように扱われます。以下のステップ 6 を参照してください。 \end{sphinxadmonition} \item {} スイートが実行されます。 \item {} コンテキストマネージャの {\hyperref[\detokenize{reference/datamodel:object.__exit__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_exit\_\_()}}}}} メソッドが呼ばれます。スイートが例外によって終了されたのなら、その例外の型、値、トレースバックが {\hyperref[\detokenize{reference/datamodel:object.__exit__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_exit\_\_()}}}}} に引数として渡されます。そうでなければ、 3 つの \sphinxcode{\sphinxupquote{None}} 引数が与えられます。 スイートが例外により終了され、 {\hyperref[\detokenize{reference/datamodel:object.__exit__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_exit\_\_()}}}}} メソッドからの戻り値が偽(false)ならば、例外が再送出されます。この戻り値が真(true)ならば例外は抑制され、実行は {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}} 文の次の文から続きます。 もしそのスイートが例外でない何らかの理由で終了した場合、その {\hyperref[\detokenize{reference/datamodel:object.__exit__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_exit\_\_()}}}}} からの戻り値は無視されて、実行は発生した終了の種類に応じた通常の位置から継続します。 \end{enumerate} 以下のコード: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{with} \PYG{n}{EXPRESSION} \PYG{k}{as} \PYG{n}{TARGET}\PYG{p}{:} \PYG{n}{SUITE} \end{sphinxVerbatim} これは次と等価です: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{manager} \PYG{o}{=} \PYG{p}{(}\PYG{n}{EXPRESSION}\PYG{p}{)} \PYG{n}{enter} \PYG{o}{=} \PYG{n+nb}{type}\PYG{p}{(}\PYG{n}{manager}\PYG{p}{)}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}enter\PYGZus{}\PYGZus{}} \PYG{n}{exit} \PYG{o}{=} \PYG{n+nb}{type}\PYG{p}{(}\PYG{n}{manager}\PYG{p}{)}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}exit\PYGZus{}\PYGZus{}} \PYG{n}{value} \PYG{o}{=} \PYG{n}{enter}\PYG{p}{(}\PYG{n}{manager}\PYG{p}{)} \PYG{n}{hit\PYGZus{}except} \PYG{o}{=} \PYG{k+kc}{False} \PYG{k}{try}\PYG{p}{:} \PYG{n}{TARGET} \PYG{o}{=} \PYG{n}{value} \PYG{n}{SUITE} \PYG{k}{except}\PYG{p}{:} \PYG{n}{hit\PYGZus{}except} \PYG{o}{=} \PYG{k+kc}{True} \PYG{k}{if} \PYG{o+ow}{not} \PYG{n}{exit}\PYG{p}{(}\PYG{n}{manager}\PYG{p}{,} \PYG{o}{*}\PYG{n}{sys}\PYG{o}{.}\PYG{n}{exc\PYGZus{}info}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{:} \PYG{k}{raise} \PYG{k}{finally}\PYG{p}{:} \PYG{k}{if} \PYG{o+ow}{not} \PYG{n}{hit\PYGZus{}except}\PYG{p}{:} \PYG{n}{exit}\PYG{p}{(}\PYG{n}{manager}\PYG{p}{,} \PYG{k+kc}{None}\PYG{p}{,} \PYG{k+kc}{None}\PYG{p}{,} \PYG{k+kc}{None}\PYG{p}{)} \end{sphinxVerbatim} 複数の要素があるとき、コンテキストマネージャは複数の {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}} 文がネストされたかのように進行します: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{with} \PYG{n}{A}\PYG{p}{(}\PYG{p}{)} \PYG{k}{as} \PYG{n}{a}\PYG{p}{,} \PYG{n}{B}\PYG{p}{(}\PYG{p}{)} \PYG{k}{as} \PYG{n}{b}\PYG{p}{:} \PYG{n}{SUITE} \end{sphinxVerbatim} これは次と等価です: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{with} \PYG{n}{A}\PYG{p}{(}\PYG{p}{)} \PYG{k}{as} \PYG{n}{a}\PYG{p}{:} \PYG{k}{with} \PYG{n}{B}\PYG{p}{(}\PYG{p}{)} \PYG{k}{as} \PYG{n}{b}\PYG{p}{:} \PYG{n}{SUITE} \end{sphinxVerbatim} \DUrole{versionmodified,changed}{バージョン 3.1 で変更: }複数のコンテキスト式をサポートしました。 \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 343@\spxentry{PEP 343}}\sphinxhref{https://www.python.org/dev/peps/pep-0343}{\sphinxstylestrong{PEP 343}} \sphinxhyphen{} "with" ステートメント}] \leavevmode Python の {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}} 文の仕様、背景、および例が記載されています。 \end{description} \index{parameter@\spxentry{parameter}!function definition@\spxentry{function definition}}\ignorespaces \section{関数定義} \label{\detokenize{reference/compound_stmts:function-definitions}}\label{\detokenize{reference/compound_stmts:def}}\label{\detokenize{reference/compound_stmts:function}}\label{\detokenize{reference/compound_stmts:index-18}} \index{文@\spxentry{文}!def@\spxentry{def}}\index{def@\spxentry{def}!文@\spxentry{文}}\index{function@\spxentry{function}!definition@\spxentry{definition}}\index{definition@\spxentry{definition}!function@\spxentry{function}}\index{function@\spxentry{function}!name@\spxentry{name}}\index{name@\spxentry{name}!function@\spxentry{function}}\index{name@\spxentry{name}!binding@\spxentry{binding}}\index{binding@\spxentry{binding}!name@\spxentry{name}}\index{オブジェクト@\spxentry{オブジェクト}!user\sphinxhyphen{}defined function@\spxentry{user\sphinxhyphen{}defined function}}\index{user\sphinxhyphen{}defined function@\spxentry{user\sphinxhyphen{}defined function}!オブジェクト@\spxentry{オブジェクト}}\index{オブジェクト@\spxentry{オブジェクト}!function@\spxentry{function}}\index{function@\spxentry{function}!オブジェクト@\spxentry{オブジェクト}}\index{function@\spxentry{function}!name@\spxentry{name}}\index{name@\spxentry{name}!function@\spxentry{function}}\index{name@\spxentry{name}!binding@\spxentry{binding}}\index{binding@\spxentry{binding}!name@\spxentry{name}}\index{() (parentheses)@\spxentry{()}\spxextra{parentheses}!function definition@\spxentry{function definition}}\index{, (comma)@\spxentry{,}\spxextra{comma}!parameter list@\spxentry{parameter list}}\index{: (colon)@\spxentry{:}\spxextra{colon}!compound statement@\spxentry{compound statement}}\ignorespaces 関数定義は、ユーザ定義関数オブジェクトを定義します ({\hyperref[\detokenize{reference/datamodel:types}]{\sphinxcrossref{\DUrole{std,std-ref}{標準型の階層}}}} 節参照): \begin{productionlist} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-funcdef}}\production{funcdef}{ {[}{\hyperref[\detokenize{reference/compound_stmts:grammar-token-decorators}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{decorators}}}}}{]} "def" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-funcname}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{funcname}}}}} "(" {[}{\hyperref[\detokenize{reference/compound_stmts:grammar-token-parameter-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{parameter\_list}}}}}{]} ")"} \productioncont{ {[}"\sphinxhyphen{}>" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}{]} ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-decorators}}\production{decorators}{ {\hyperref[\detokenize{reference/compound_stmts:grammar-token-decorator}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{decorator}}}}}+} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-decorator}}\production{decorator}{ "@" {\hyperref[\detokenize{reference/expressions:grammar-token-assignment-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{assignment\_expression}}}}} NEWLINE} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-parameter_list}}\production{parameter\_list}{ {\hyperref[\detokenize{reference/compound_stmts:grammar-token-defparameter}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{defparameter}}}}} ("," {\hyperref[\detokenize{reference/compound_stmts:grammar-token-defparameter}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{defparameter}}}}})* "," "/" {[}"," {[}{\hyperref[\detokenize{reference/compound_stmts:grammar-token-parameter-list-no-posonly}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{parameter\_list\_no\_posonly}}}}}{]}{]}} \productioncont{ | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-parameter-list-no-posonly}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{parameter\_list\_no\_posonly}}}}}} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-parameter_list_no_posonly}}\production{parameter\_list\_no\_posonly}{ {\hyperref[\detokenize{reference/compound_stmts:grammar-token-defparameter}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{defparameter}}}}} ("," {\hyperref[\detokenize{reference/compound_stmts:grammar-token-defparameter}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{defparameter}}}}})* {[}"," {[}{\hyperref[\detokenize{reference/compound_stmts:grammar-token-parameter-list-starargs}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{parameter\_list\_starargs}}}}}{]}{]}} \productioncont{ | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-parameter-list-starargs}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{parameter\_list\_starargs}}}}}} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-parameter_list_starargs}}\production{parameter\_list\_starargs}{ "*" {[}{\hyperref[\detokenize{reference/compound_stmts:grammar-token-parameter}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{parameter}}}}}{]} ("," {\hyperref[\detokenize{reference/compound_stmts:grammar-token-defparameter}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{defparameter}}}}})* {[}"," {[}"**" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-parameter}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{parameter}}}}} {[}","{]}{]}{]}} \productioncont{ | "**" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-parameter}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{parameter}}}}} {[}","{]}} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-parameter}}\production{parameter}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}} {[}":" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}{]}} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-defparameter}}\production{defparameter}{ {\hyperref[\detokenize{reference/compound_stmts:grammar-token-parameter}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{parameter}}}}} {[}"=" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}{]}} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-funcname}}\production{funcname}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}} \end{productionlist} 関数定義は実行可能な文です。関数定義を実行すると、現在のローカルな名前空間内で関数名を関数オブジェクト (関数の実行可能コードをくるむラッパー) に束縛します。この関数オブジェクトには、関数が呼び出された際に使われるグローバルな名前空間として、現在のグローバルな名前空間への参照が入っています。 関数定義は関数本体を実行しません; 関数本体は関数が呼び出された時にのみ実行されます。 % \begin{footnote}[2]\sphinxAtStartFootnote 関数の本体の最初の文として現われる文字列リテラルは、その関数の \sphinxcode{\sphinxupquote{\_\_doc\_\_}} 属性に変換され、その関数の {\hyperref[\detokenize{glossary:term-docstring}]{\sphinxtermref{\DUrole{xref,std,std-term}{ドキュメンテーション文字列}}}} になります。 % \end{footnote} \index{"@ (at)@\spxentry{"@}\spxextra{at}!function definition@\spxentry{function definition}}\ignorespaces 関数定義は一つ以上の {\hyperref[\detokenize{glossary:term-decorator}]{\sphinxtermref{\DUrole{xref,std,std-term}{デコレータ}}}} 式でラップできます。デコレータ式は関数を定義するとき、関数定義の入っているスコープで評価されます。その結果は、関数オブジェクトを唯一の引数にとる呼び出し可能オブジェクトでなければなりません。関数オブジェクトの代わりに、返された値が関数名に束縛されます。複数のデコレータはネストして適用されます。例えば、以下のようなコード: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n+nd}{@f1}\PYG{p}{(}\PYG{n}{arg}\PYG{p}{)} \PYG{n+nd}{@f2} \PYG{k}{def} \PYG{n+nf}{func}\PYG{p}{(}\PYG{p}{)}\PYG{p}{:} \PYG{k}{pass} \end{sphinxVerbatim} は、だいたい次と等価です \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{def} \PYG{n+nf}{func}\PYG{p}{(}\PYG{p}{)}\PYG{p}{:} \PYG{k}{pass} \PYG{n}{func} \PYG{o}{=} \PYG{n}{f1}\PYG{p}{(}\PYG{n}{arg}\PYG{p}{)}\PYG{p}{(}\PYG{n}{f2}\PYG{p}{(}\PYG{n}{func}\PYG{p}{)}\PYG{p}{)} \end{sphinxVerbatim} ただし、前者のコードでは元々の関数を \sphinxcode{\sphinxupquote{func}} という名前へ一時的に束縛することはない、というところを除きます。 \DUrole{versionmodified,changed}{バージョン 3.9 で変更: }Functions may be decorated with any valid {\hyperref[\detokenize{reference/expressions:grammar-token-assignment-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{assignment\_expression}}}}}. Previously, the grammar was much more restrictive; see \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 614@\spxentry{PEP 614}}\sphinxhref{https://www.python.org/dev/peps/pep-0614}{\sphinxstylestrong{PEP 614}} for details. \index{default@\spxentry{default}!parameter value@\spxentry{parameter} \spxentry{value}}\index{parameter@\spxentry{parameter}!value, default@\spxentry{value}, \spxentry{default}}\index{value@\spxentry{value}!default parameter@\spxentry{default} \spxentry{parameter}}\index{argument@\spxentry{argument}!function definition@\spxentry{function definition}}\index{= (equals)@\spxentry{=}\spxextra{equals}!function definition@\spxentry{function definition}}\ignorespaces 1 つ以上の {\hyperref[\detokenize{glossary:term-parameter}]{\sphinxtermref{\DUrole{xref,std,std-term}{仮引数}}}} が \sphinxstyleemphasis{parameter} \sphinxcode{\sphinxupquote{=}} \sphinxstyleemphasis{expression} の形を取っているとき、関数は "デフォルト引数値" を持つと言います。デフォルト値を持つ仮引数では、呼び出し時にそれに対応する {\hyperref[\detokenize{glossary:term-argument}]{\sphinxtermref{\DUrole{xref,std,std-term}{実引数}}}} は省略でき、その場合は仮引数のデフォルト値が使われます。ある引数がデフォルト値を持っている場合、それ以降 "\sphinxcode{\sphinxupquote{*}}" が出てくるまでの引数は全てデフォルト値を持っていなければなりません \sphinxhyphen{}\sphinxhyphen{} これは文法定義では表現されていない構文的制限です。 \sphinxstylestrong{デフォルト引数値は関数定義が実行されるときに左から右へ評価されます。} これは、デフォルト引数の式は関数が定義されるときにただ一度だけ評価され、同じ "計算済みの" 値が呼び出しのたびに使用されることを意味します。この仕様を理解しておくことは特に、デフォルト引数値がリストや辞書のようなミュータブルなオブジェクトであるときに重要です: 関数がこのオブジェクトを変更 (例えばリストに要素を追加) すると、このデフォルト値が変更の影響を受けてしまします。一般には、これは意図しない動作です。このような動作を避けるには、デフォルト値として \sphinxcode{\sphinxupquote{None}} を使い、この値を関数本体の中で明示的にテストします。例えば以下のようにします: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{def} \PYG{n+nf}{whats\PYGZus{}on\PYGZus{}the\PYGZus{}telly}\PYG{p}{(}\PYG{n}{penguin}\PYG{o}{=}\PYG{k+kc}{None}\PYG{p}{)}\PYG{p}{:} \PYG{k}{if} \PYG{n}{penguin} \PYG{o+ow}{is} \PYG{k+kc}{None}\PYG{p}{:} \PYG{n}{penguin} \PYG{o}{=} \PYG{p}{[}\PYG{p}{]} \PYG{n}{penguin}\PYG{o}{.}\PYG{n}{append}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}}\PYG{l+s+s2}{property of the zoo}\PYG{l+s+s2}{\PYGZdq{}}\PYG{p}{)} \PYG{k}{return} \PYG{n}{penguin} \end{sphinxVerbatim} \index{/ (slash)@\spxentry{/}\spxextra{slash}!function definition@\spxentry{function definition}}\index{* (asterisk)@\spxentry{*}\spxextra{asterisk}!function definition@\spxentry{function definition}}\index{**@\spxentry{**}!function definition@\spxentry{function definition}}\ignorespaces 関数呼び出しの意味付けに関する詳細は、 {\hyperref[\detokenize{reference/expressions:calls}]{\sphinxcrossref{\DUrole{std,std-ref}{呼び出し (call)}}}} 節で述べられています。 関数呼び出しを行うと、パラメタリストに記述された全てのパラメタに、位置引数、キーワード引数、デフォルト値のいずれかから値が代入されます。 "\sphinxcode{\sphinxupquote{*identifier}}" 形式が存在すれば、余ったすべての位置引数を受け取ったタプルに初期化されます。 このデフォルト値は空のタプルです。 "\sphinxcode{\sphinxupquote{**identifier}}" 形式が存在すれば、余ったすべてのキーワード引数を受け取った順序付きのマッピングオブジェクトに初期化されます。 このデフォルト値は同じ型の空のマッピングオブジェクトです。 "\sphinxcode{\sphinxupquote{*}}" や "\sphinxcode{\sphinxupquote{*identifier}}" の後のパラメタはキーワード専用パラメータで、キーワード引数によってのみ渡されます。 "\sphinxcode{\sphinxupquote{/}}" の前のパラメタは位置専用パラメータで、位置引数によってのみ渡されます。 \DUrole{versionmodified,changed}{バージョン 3.8 で変更: }The \sphinxcode{\sphinxupquote{/}} function parameter syntax may be used to indicate positional\sphinxhyphen{}only parameters. See \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 570@\spxentry{PEP 570}}\sphinxhref{https://www.python.org/dev/peps/pep-0570}{\sphinxstylestrong{PEP 570}} for details. \index{function@\spxentry{function}!annotations@\spxentry{annotations}}\index{annotations@\spxentry{annotations}!function@\spxentry{function}}\index{\sphinxhyphen{}>@\spxentry{\sphinxhyphen{}>}!function annotations@\spxentry{function annotations}}\index{: (colon)@\spxentry{:}\spxextra{colon}!function annotations@\spxentry{function annotations}}\ignorespaces 引数には、引数名に続けて "\sphinxcode{\sphinxupquote{: expression}}" 形式の {\hyperref[\detokenize{glossary:term-function-annotation}]{\sphinxtermref{\DUrole{xref,std,std-term}{アノテーション}}}} を付けられます。 \sphinxcode{\sphinxupquote{*identifier}} や \sphinxcode{\sphinxupquote{**identifier}} の形式でも、すべての引数にはアノテーションをつけられます。 関数には、引数リストの後に "\sphinxcode{\sphinxupquote{\sphinxhyphen{}> expression}}" 形式の "return" アノテーションをつけられます。これらのアノテーションは、任意の有効な Python の式が使えます。 アノテーションがあっても、関数の意味論は変わりません。 アノテーションの値は、関数オブジェクトの \sphinxcode{\sphinxupquote{\_\_annotations\_\_}} 属性の、引数名をキーとする値として得られます。 \sphinxcode{\sphinxupquote{\_\_future\_\_}} の \sphinxcode{\sphinxupquote{annotations}} インポートを使った場合は、アノテーションは実行時には文字列として保持され、これにより評価の遅延が可能になっています。 そうでない場合は、アノテーションは関数定義が実行されたときに評価されます。 このケースでは、アノテーションはソースコードに現れたのとは違う順序で評価されることがあります。 \index{lambda@\spxentry{lambda}!expression@\spxentry{expression}}\index{expression@\spxentry{expression}!lambda@\spxentry{lambda}}\ignorespaces 式を即時に使用するために、無名関数 (名前に束縛されていない関数) を作成することもできます。 これは {\hyperref[\detokenize{reference/expressions:lambda}]{\sphinxcrossref{\DUrole{std,std-ref}{ラムダ (lambda)}}}} の節で解説されているラムダ式を使います。 ラムダ式は簡略化された関数定義の簡略表現に過ぎないことに注意してください; "{\hyperref[\detokenize{reference/compound_stmts:def}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{def}}}}}" 文で定義された関数もラムダ式で作成された関数のように、引数として渡せたり、他の名前に割り当てることができます。 複数の式とアノテーションが実行できるので、 "\sphinxcode{\sphinxupquote{def}}" 形式の方がより強力です。 \sphinxstylestrong{プログラマへのメモ:} 関数は第一級オブジェクトです。関数定義内で実行された "\sphinxcode{\sphinxupquote{def}}" 文は、返り値や引数として渡せるローカル関数を定義します。ネストした関数内で使われる自由変数は、 def を含んでいる関数のローカル変数にアクセスできます。詳細は {\hyperref[\detokenize{reference/executionmodel:naming}]{\sphinxcrossref{\DUrole{std,std-ref}{名前づけと束縛 (naming and binding)}}}} 節を参照してください。 \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 3107@\spxentry{PEP 3107}}\sphinxhref{https://www.python.org/dev/peps/pep-3107}{\sphinxstylestrong{PEP 3107}} \sphinxhyphen{} Function Annotations}] \leavevmode 関数アノテーションの元の仕様書。 \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 484@\spxentry{PEP 484}}\sphinxhref{https://www.python.org/dev/peps/pep-0484}{\sphinxstylestrong{PEP 484}} \sphinxhyphen{} 型ヒント}] \leavevmode アノテーションの標準的な意味付けである型ヒントの定義。 \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 526@\spxentry{PEP 526}}\sphinxhref{https://www.python.org/dev/peps/pep-0526}{\sphinxstylestrong{PEP 526}} \sphinxhyphen{} Syntax for Variable Annotations}] \leavevmode クラス変数とインスタンス変数を含む変数に型ヒントが宣言できる機能 \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 563@\spxentry{PEP 563}}\sphinxhref{https://www.python.org/dev/peps/pep-0563}{\sphinxstylestrong{PEP 563}} \sphinxhyphen{} アノテーションの遅延評価}] \leavevmode 実行時にアノテーションを貪欲評価するのではなく文字列形式で保持することによる、アノテーションにおける前方参照のサポート \end{description} \section{クラス定義} \label{\detokenize{reference/compound_stmts:class-definitions}}\label{\detokenize{reference/compound_stmts:class}} \index{オブジェクト@\spxentry{オブジェクト}!class@\spxentry{class}}\index{class@\spxentry{class}!オブジェクト@\spxentry{オブジェクト}}\index{文@\spxentry{文}!class@\spxentry{class}}\index{class@\spxentry{class}!文@\spxentry{文}}\index{class@\spxentry{class}!definition@\spxentry{definition}}\index{definition@\spxentry{definition}!class@\spxentry{class}}\index{class@\spxentry{class}!name@\spxentry{name}}\index{name@\spxentry{name}!class@\spxentry{class}}\index{name@\spxentry{name}!binding@\spxentry{binding}}\index{binding@\spxentry{binding}!name@\spxentry{name}}\index{execution@\spxentry{execution}!frame@\spxentry{frame}}\index{frame@\spxentry{frame}!execution@\spxentry{execution}}\index{inheritance@\spxentry{inheritance}}\index{docstring@\spxentry{docstring}}\index{() (parentheses)@\spxentry{()}\spxextra{parentheses}!class definition@\spxentry{class definition}}\index{, (comma)@\spxentry{,}\spxextra{comma}!expression list@\spxentry{expression list}}\index{: (colon)@\spxentry{:}\spxextra{colon}!compound statement@\spxentry{compound statement}}\ignorespaces クラス定義は、クラスオブジェクトを定義します ({\hyperref[\detokenize{reference/datamodel:types}]{\sphinxcrossref{\DUrole{std,std-ref}{標準型の階層}}}} 節参照): \begin{productionlist} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-classdef}}\production{classdef}{ {[}{\hyperref[\detokenize{reference/compound_stmts:grammar-token-decorators}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{decorators}}}}}{]} "class" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-classname}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{classname}}}}} {[}{\hyperref[\detokenize{reference/compound_stmts:grammar-token-inheritance}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{inheritance}}}}}{]} ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-inheritance}}\production{inheritance}{ "(" {[}{\hyperref[\detokenize{reference/expressions:grammar-token-argument-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{argument\_list}}}}}{]} ")"} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-classname}}\production{classname}{ {\hyperref[\detokenize{reference/lexical_analysis:grammar-token-identifier}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{identifier}}}}}} \end{productionlist} クラス定義は実行可能な文です。継承リストは通常、基底クラスリストを与えます (より高度な使い方は、 {\hyperref[\detokenize{reference/datamodel:metaclasses}]{\sphinxcrossref{\DUrole{std,std-ref}{メタクラス}}}} を参照してください)。ですから、リストのそれぞれの要素の評価はサブクラス化しても良いクラスであるべきです。継承リストのないクラスは、デフォルトで、基底クラス \sphinxcode{\sphinxupquote{object}} を継承するので: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{class} \PYG{n+nc}{Foo}\PYG{p}{:} \PYG{k}{pass} \end{sphinxVerbatim} は、以下と同等です \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{class} \PYG{n+nc}{Foo}\PYG{p}{(}\PYG{n+nb}{object}\PYG{p}{)}\PYG{p}{:} \PYG{k}{pass} \end{sphinxVerbatim} 次にクラスのスイートが、新たな実行フレーム ({\hyperref[\detokenize{reference/executionmodel:naming}]{\sphinxcrossref{\DUrole{std,std-ref}{名前づけと束縛 (naming and binding)}}}} を参照してください) 内で、新たに作られたローカル名前空間と元々のグローバル名前空間を使って実行されます (通常、このスイートには主に関数定義が含まれます)。クラスのスイートが実行し終えると、実行フレームは破棄されますが、ローカルな名前空間は保存されます。% \begin{footnote}[3]\sphinxAtStartFootnote クラスの本体の最初の文として現われる文字列リテラルは、その名前空間の \sphinxcode{\sphinxupquote{\_\_doc\_\_}} 要素となり、そのクラスの {\hyperref[\detokenize{glossary:term-docstring}]{\sphinxtermref{\DUrole{xref,std,std-term}{ドキュメンテーション文字列}}}} になります。 % \end{footnote} 次に、継承リストを基底クラスに、保存されたローカル名前空間を属性値辞書に、それぞれ使ってクラスオブジェクトが生成されます。最後に、もとのローカル名前空間において、クラス名がこのクラスオブジェクトに束縛されます。 クラス本体で属性が定義された順序は新しいクラスの \sphinxcode{\sphinxupquote{\_\_dict\_\_}} に保持されます。 この性質が期待できるのは、クラスが作られた直後かつ定義構文を使って定義されたクラスであるときのみです。 クラス作成は、 {\hyperref[\detokenize{reference/datamodel:metaclasses}]{\sphinxcrossref{\DUrole{std,std-ref}{メタクラス}}}} を利用して大幅にカスタマイズできます。 \index{"@ (at)@\spxentry{"@}\spxextra{at}!class definition@\spxentry{class definition}}\ignorespaces 関数をデコレートするのと同じように、クラスもデコレートすることが出来ます、 \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n+nd}{@f1}\PYG{p}{(}\PYG{n}{arg}\PYG{p}{)} \PYG{n+nd}{@f2} \PYG{k}{class} \PYG{n+nc}{Foo}\PYG{p}{:} \PYG{k}{pass} \end{sphinxVerbatim} は、だいたい次と等価です \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{class} \PYG{n+nc}{Foo}\PYG{p}{:} \PYG{k}{pass} \PYG{n}{Foo} \PYG{o}{=} \PYG{n}{f1}\PYG{p}{(}\PYG{n}{arg}\PYG{p}{)}\PYG{p}{(}\PYG{n}{f2}\PYG{p}{(}\PYG{n}{Foo}\PYG{p}{)}\PYG{p}{)} \end{sphinxVerbatim} デコレータ式の評価規則は関数デコレータと同じです。結果はクラス名に束縛されます。 \DUrole{versionmodified,changed}{バージョン 3.9 で変更: }Classes may be decorated with any valid {\hyperref[\detokenize{reference/expressions:grammar-token-assignment-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{assignment\_expression}}}}}. Previously, the grammar was much more restrictive; see \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 614@\spxentry{PEP 614}}\sphinxhref{https://www.python.org/dev/peps/pep-0614}{\sphinxstylestrong{PEP 614}} for details. \sphinxstylestrong{プログラマのための注釈:} クラス定義内で定義された変数はクラス属性であり、全てのインスタンス間で共有されます。インスタンス属性は、メソッドの中で \sphinxcode{\sphinxupquote{self.name = value}} とすることで設定できます。クラス属性もインスタンス属性も "\sphinxcode{\sphinxupquote{self.name}}" 表記でアクセスでき、この表記でアクセスしたとき、インスタンス属性は同名のクラス属性を隠蔽します。クラス属性は、インスタンス属性のデフォルト値として使えますが、そこにミュータブルな値を使うと予期せぬ結果につながります。 {\hyperref[\detokenize{reference/datamodel:descriptors}]{\sphinxcrossref{\DUrole{std,std-ref}{記述子}}}} を使うと、詳細な実装が異なるインスタンス変数を作成できます。 \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 3115@\spxentry{PEP 3115}}\sphinxhref{https://www.python.org/dev/peps/pep-3115}{\sphinxstylestrong{PEP 3115}} \sphinxhyphen{} Metaclasses in Python 3000}] \leavevmode メタクラスの宣言を現在の文法と、メタクラス付きのクラスがどのように構築されるかの意味論を変更した提案 \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 3129@\spxentry{PEP 3129}}\sphinxhref{https://www.python.org/dev/peps/pep-3129}{\sphinxstylestrong{PEP 3129}} \sphinxhyphen{} クラスデコレータ}] \leavevmode クラスデコレータを追加した提案。 関数デコレータとメソッドデコレータは \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 318@\spxentry{PEP 318}}\sphinxhref{https://www.python.org/dev/peps/pep-0318}{\sphinxstylestrong{PEP 318}} で導入されました。 \end{description} \section{コルーチン} \label{\detokenize{reference/compound_stmts:coroutines}}\label{\detokenize{reference/compound_stmts:async}} \DUrole{versionmodified,added}{バージョン 3.5 で追加.} \index{文@\spxentry{文}!async def@\spxentry{async def}}\index{async def@\spxentry{async def}!文@\spxentry{文}}\ignorespaces \subsection{コルーチン関数定義} \label{\detokenize{reference/compound_stmts:coroutine-function-definition}}\label{\detokenize{reference/compound_stmts:async-def}}\label{\detokenize{reference/compound_stmts:index-37}} \begin{productionlist} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-async_funcdef}}\production{async\_funcdef}{ {[}{\hyperref[\detokenize{reference/compound_stmts:grammar-token-decorators}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{decorators}}}}}{]} "async" "def" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-funcname}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{funcname}}}}} "(" {[}{\hyperref[\detokenize{reference/compound_stmts:grammar-token-parameter-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{parameter\_list}}}}}{]} ")"} \productioncont{ {[}"\sphinxhyphen{}>" {\hyperref[\detokenize{reference/expressions:grammar-token-expression}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression}}}}}{]} ":" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-suite}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{suite}}}}}} \end{productionlist} \index{キーワード@\spxentry{キーワード}!async@\spxentry{async}}\index{async@\spxentry{async}!キーワード@\spxentry{キーワード}}\index{キーワード@\spxentry{キーワード}!await@\spxentry{await}}\index{await@\spxentry{await}!キーワード@\spxentry{キーワード}}\ignorespaces Python で実行しているコルーチンは多くの時点で一時停止と再開ができます ({\hyperref[\detokenize{glossary:term-coroutine}]{\sphinxtermref{\DUrole{xref,std,std-term}{コルーチン}}}} を参照してください)。 コルーチン関数の本体では、 \sphinxcode{\sphinxupquote{await}} 識別子と \sphinxcode{\sphinxupquote{async}} 識別子は予約語になります; {\hyperref[\detokenize{reference/expressions:await}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{await}}}}} 式である {\hyperref[\detokenize{reference/compound_stmts:async-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async for}}}}} と {\hyperref[\detokenize{reference/compound_stmts:async-with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async with}}}}} はコルーチン関数の本体でしか使えません。 Functions defined with \sphinxcode{\sphinxupquote{async def}} syntax are always coroutine functions, even if they do not contain \sphinxcode{\sphinxupquote{await}} or \sphinxcode{\sphinxupquote{async}} keywords. コルーチン関数の本体の中で \sphinxcode{\sphinxupquote{yield from}} 式を使用すると \sphinxcode{\sphinxupquote{SyntaxError}} になります。 コルーチン関数の例: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{async} \PYG{k}{def} \PYG{n+nf}{func}\PYG{p}{(}\PYG{n}{param1}\PYG{p}{,} \PYG{n}{param2}\PYG{p}{)}\PYG{p}{:} \PYG{n}{do\PYGZus{}stuff}\PYG{p}{(}\PYG{p}{)} \PYG{k}{await} \PYG{n}{some\PYGZus{}coroutine}\PYG{p}{(}\PYG{p}{)} \end{sphinxVerbatim} \index{文@\spxentry{文}!async for@\spxentry{async for}}\index{async for@\spxentry{async for}!文@\spxentry{文}}\ignorespaces \subsection{\sphinxstyleliteralintitle{\sphinxupquote{async for}} 文} \label{\detokenize{reference/compound_stmts:the-async-for-statement}}\label{\detokenize{reference/compound_stmts:async-for}}\label{\detokenize{reference/compound_stmts:index-39}} \begin{productionlist} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-async_for_stmt}}\production{async\_for\_stmt}{ "async" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-for-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for\_stmt}}}}}} \end{productionlist} {\hyperref[\detokenize{glossary:term-asynchronous-iterable}]{\sphinxtermref{\DUrole{xref,std,std-term}{asynchronous iterable}}}} は、その \sphinxcode{\sphinxupquote{\_\_anext\_\_}} メソッドで非同期なコードを実行可能な、{\hyperref[\detokenize{glossary:term-asynchronous-iterator}]{\sphinxtermref{\DUrole{xref,std,std-term}{asynchronous iterator}}}} を直接返す \sphinxcode{\sphinxupquote{\_\_aiter\_\_}} メソッドを提供しています。 \sphinxcode{\sphinxupquote{async for}} 文によって非同期なイテラブルを簡単にイテレーションすることができます。 以下のコード: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{async} \PYG{k}{for} \PYG{n}{TARGET} \PYG{o+ow}{in} \PYG{n}{ITER}\PYG{p}{:} \PYG{n}{SUITE} \PYG{k}{else}\PYG{p}{:} \PYG{n}{SUITE2} \end{sphinxVerbatim} は意味論的に以下と等価です: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n+nb}{iter} \PYG{o}{=} \PYG{p}{(}\PYG{n}{ITER}\PYG{p}{)} \PYG{n+nb}{iter} \PYG{o}{=} \PYG{n+nb}{type}\PYG{p}{(}\PYG{n+nb}{iter}\PYG{p}{)}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}aiter\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n+nb}{iter}\PYG{p}{)} \PYG{n}{running} \PYG{o}{=} \PYG{k+kc}{True} \PYG{k}{while} \PYG{n}{running}\PYG{p}{:} \PYG{k}{try}\PYG{p}{:} \PYG{n}{TARGET} \PYG{o}{=} \PYG{k}{await} \PYG{n+nb}{type}\PYG{p}{(}\PYG{n+nb}{iter}\PYG{p}{)}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}anext\PYGZus{}\PYGZus{}}\PYG{p}{(}\PYG{n+nb}{iter}\PYG{p}{)} \PYG{k}{except} \PYG{n+ne}{StopAsyncIteration}\PYG{p}{:} \PYG{n}{running} \PYG{o}{=} \PYG{k+kc}{False} \PYG{k}{else}\PYG{p}{:} \PYG{n}{SUITE} \PYG{k}{else}\PYG{p}{:} \PYG{n}{SUITE2} \end{sphinxVerbatim} 詳細は {\hyperref[\detokenize{reference/datamodel:object.__aiter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_aiter\_\_()}}}}} や {\hyperref[\detokenize{reference/datamodel:object.__anext__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_anext\_\_()}}}}} を参照してください。 コルーチン関数の本体の外で \sphinxcode{\sphinxupquote{async for}} 文を使用すると \sphinxcode{\sphinxupquote{SyntaxError}} になります。 \index{文@\spxentry{文}!async with@\spxentry{async with}}\index{async with@\spxentry{async with}!文@\spxentry{文}}\ignorespaces \subsection{\sphinxstyleliteralintitle{\sphinxupquote{async with}} 文} \label{\detokenize{reference/compound_stmts:the-async-with-statement}}\label{\detokenize{reference/compound_stmts:async-with}}\label{\detokenize{reference/compound_stmts:index-40}} \begin{productionlist} \phantomsection\label{\detokenize{reference/compound_stmts:grammar-token-async_with_stmt}}\production{async\_with\_stmt}{ "async" {\hyperref[\detokenize{reference/compound_stmts:grammar-token-with-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with\_stmt}}}}}} \end{productionlist} {\hyperref[\detokenize{glossary:term-asynchronous-context-manager}]{\sphinxtermref{\DUrole{xref,std,std-term}{asynchronous context manager}}}} は、 \sphinxstyleemphasis{enter} メソッドと \sphinxstyleemphasis{exit} メソッド内部で実行を一時停止できる {\hyperref[\detokenize{glossary:term-context-manager}]{\sphinxtermref{\DUrole{xref,std,std-term}{context manager}}}} です。 以下のコード: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{async} \PYG{k}{with} \PYG{n}{EXPRESSION} \PYG{k}{as} \PYG{n}{TARGET}\PYG{p}{:} \PYG{n}{SUITE} \end{sphinxVerbatim} これは次と等価です: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{manager} \PYG{o}{=} \PYG{p}{(}\PYG{n}{EXPRESSION}\PYG{p}{)} \PYG{n}{aenter} \PYG{o}{=} \PYG{n+nb}{type}\PYG{p}{(}\PYG{n}{manager}\PYG{p}{)}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}aenter\PYGZus{}\PYGZus{}} \PYG{n}{aexit} \PYG{o}{=} \PYG{n+nb}{type}\PYG{p}{(}\PYG{n}{manager}\PYG{p}{)}\PYG{o}{.}\PYG{n+nf+fm}{\PYGZus{}\PYGZus{}aexit\PYGZus{}\PYGZus{}} \PYG{n}{value} \PYG{o}{=} \PYG{k}{await} \PYG{n}{aenter}\PYG{p}{(}\PYG{n}{manager}\PYG{p}{)} \PYG{n}{hit\PYGZus{}except} \PYG{o}{=} \PYG{k+kc}{False} \PYG{k}{try}\PYG{p}{:} \PYG{n}{TARGET} \PYG{o}{=} \PYG{n}{value} \PYG{n}{SUITE} \PYG{k}{except}\PYG{p}{:} \PYG{n}{hit\PYGZus{}except} \PYG{o}{=} \PYG{k+kc}{True} \PYG{k}{if} \PYG{o+ow}{not} \PYG{k}{await} \PYG{n}{aexit}\PYG{p}{(}\PYG{n}{manager}\PYG{p}{,} \PYG{o}{*}\PYG{n}{sys}\PYG{o}{.}\PYG{n}{exc\PYGZus{}info}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{:} \PYG{k}{raise} \PYG{k}{finally}\PYG{p}{:} \PYG{k}{if} \PYG{o+ow}{not} \PYG{n}{hit\PYGZus{}except}\PYG{p}{:} \PYG{k}{await} \PYG{n}{aexit}\PYG{p}{(}\PYG{n}{manager}\PYG{p}{,} \PYG{k+kc}{None}\PYG{p}{,} \PYG{k+kc}{None}\PYG{p}{,} \PYG{k+kc}{None}\PYG{p}{)} \end{sphinxVerbatim} 詳細は {\hyperref[\detokenize{reference/datamodel:object.__aenter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_aenter\_\_()}}}}} や {\hyperref[\detokenize{reference/datamodel:object.__aexit__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_aexit\_\_()}}}}} を参照してください。 コルーチン関数の本体の外で \sphinxcode{\sphinxupquote{async with}} 文を使用すると \sphinxcode{\sphinxupquote{SyntaxError}} になります。 \sphinxstrong{参考:} \begin{description} \item[{\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 492@\spxentry{PEP 492}}\sphinxhref{https://www.python.org/dev/peps/pep-0492}{\sphinxstylestrong{PEP 492}} \sphinxhyphen{} async 構文および await 構文付きのコルーチン}] \leavevmode コルーチンを Python のまともな独り立ちした概念にし、サポートする構文を追加した提案。 \end{description} \subsubsection*{脚注} \chapter{トップレベル要素} \label{\detokenize{reference/toplevel_components:top-level-components}}\label{\detokenize{reference/toplevel_components:top-level}}\label{\detokenize{reference/toplevel_components::doc}} \index{interpreter@\spxentry{interpreter}}\ignorespaces Python インタプリタは、標準入力や、プログラムの引数として与えられたスクリプト、対話的にタイプ入力された命令、モジュールのソースファイルなど、様々な入力源から入力を得ることができます。この章では、それぞれの場合に用いられる構文法について説明しています。 \section{完全な Python プログラム} \label{\detokenize{reference/toplevel_components:complete-python-programs}}\label{\detokenize{reference/toplevel_components:programs}} \index{program@\spxentry{program}}\ignorespaces \index{モジュール@\spxentry{モジュール}!sys@\spxentry{sys}}\index{sys@\spxentry{sys}!モジュール@\spxentry{モジュール}}\index{モジュール@\spxentry{モジュール}!\_\_main\_\_@\spxentry{\_\_main\_\_}}\index{\_\_main\_\_@\spxentry{\_\_main\_\_}!モジュール@\spxentry{モジュール}}\index{モジュール@\spxentry{モジュール}!builtins@\spxentry{builtins}}\index{builtins@\spxentry{builtins}!モジュール@\spxentry{モジュール}}\ignorespaces 言語仕様の中では、その言語を処理するインタプリタがどのように起動されるかまで規定する必要はないのですが、完全な Python プログラムの概念を知っておくと役に立ちます。完全な Python プログラムは、最小限に初期化された環境: 全ての組み込み変数と標準モジュールが利用可能で、かつ \sphinxcode{\sphinxupquote{sys}} (様々なシステムサービス)、 \sphinxcode{\sphinxupquote{builtins}} (組み込み関数、例外、および \sphinxcode{\sphinxupquote{None}})、 \sphinxcode{\sphinxupquote{\_\_main\_\_}} の 3 つを除く全てのモジュールが初期化されていない状態で動作します。 \sphinxcode{\sphinxupquote{\_\_main\_\_}} は、完全なプログラムを実行する際に、ローカルおよびグローバルな名前空間を提供するために用いられます。 完全な Python プログラムの構文は、下の節で述べるファイル入力のためのものです。 \index{interactive mode@\spxentry{interactive mode}}\index{モジュール@\spxentry{モジュール}!\_\_main\_\_@\spxentry{\_\_main\_\_}}\index{\_\_main\_\_@\spxentry{\_\_main\_\_}!モジュール@\spxentry{モジュール}}\ignorespaces インタプリタは、対話的モード (interactive mode) で起動されることもあります; この場合、インタプリタは完全なプログラムを読んで実行するのではなく、一度に単一の実行文 (複合文のときもあります) を読み込んで実行します。初期状態の環境は、完全なプログラムを実行するときの環境と同じです; 各実行文は、 \sphinxcode{\sphinxupquote{\_\_main\_\_}} の名前空間内で実行されます。 \index{UNIX@\spxentry{UNIX}}\index{Windows@\spxentry{Windows}}\index{command line@\spxentry{command line}}\index{standard input@\spxentry{standard input}}\ignorespaces 完全なプログラムは3つの形式でインタープリタに渡せます: \sphinxcode{\sphinxupquote{\sphinxhyphen{}c}} \sphinxstyleemphasis{string} コマンドラインオプションで、コマンドラインの第 1 引数で渡されるファイル、あるいは標準入力として渡します。 ファイルや標準入力が tty デバイスだった場合、インタープリタは対話モードに入ります。 それ以外の場合は、ファイルを完全なプログラムとして実行します。 \section{ファイル入力} \label{\detokenize{reference/toplevel_components:file-input}}\label{\detokenize{reference/toplevel_components:id1}} 非対話的なファイルから読み出された入力は、全て同じ形式: \begin{productionlist} \phantomsection\label{\detokenize{reference/toplevel_components:grammar-token-file_input}}\production{file\_input}{ (NEWLINE | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-statement}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{statement}}}}})*} \end{productionlist} をとります。この構文法は、以下の状況で用いられます: \begin{itemize} \item {} (ファイルや文字列内の) 完全な Python プログラムを構文解析するとき; \item {} モジュールを構文解析するとき; \item {} \sphinxcode{\sphinxupquote{exec()}} で渡された文字列を構文解析するとき; \end{itemize} \section{対話的入力} \label{\detokenize{reference/toplevel_components:interactive-input}}\label{\detokenize{reference/toplevel_components:interactive}} 対話モードでの入力は、以下の文法の下に構文解析されます: \begin{productionlist} \phantomsection\label{\detokenize{reference/toplevel_components:grammar-token-interactive_input}}\production{interactive\_input}{ {[}{\hyperref[\detokenize{reference/compound_stmts:grammar-token-stmt-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{stmt\_list}}}}}{]} NEWLINE | {\hyperref[\detokenize{reference/compound_stmts:grammar-token-compound-stmt}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{compound\_stmt}}}}} NEWLINE} \end{productionlist} 対話モードでは、(トップレベルの) 複合文の最後に空白行を入れなくてはならないことに注意してください; これは、複合文の終端をパーザが検出するための手がかりとして必要です。 \section{式入力} \label{\detokenize{reference/toplevel_components:expression-input}}\label{\detokenize{reference/toplevel_components:id2}} \index{input@\spxentry{input}}\ignorespaces \index{組み込み関数@\spxentry{組み込み関数}!eval@\spxentry{eval}}\index{eval@\spxentry{eval}!組み込み関数@\spxentry{組み込み関数}}\ignorespaces 式入力には \sphinxcode{\sphinxupquote{eval()}} が使われます。これは先頭の空白を無視します。 \sphinxcode{\sphinxupquote{eval()}} に対する文字列引数は、以下の形式をとらなければなりません: \begin{productionlist} \phantomsection\label{\detokenize{reference/toplevel_components:grammar-token-eval_input}}\production{eval\_input}{ {\hyperref[\detokenize{reference/expressions:grammar-token-expression-list}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{expression\_list}}}}} NEWLINE*} \end{productionlist} \chapter{完全な文法仕様} \label{\detokenize{reference/grammar:full-grammar-specification}}\label{\detokenize{reference/grammar::doc}} 以下に示すのは Python の完全な文法です。CPython のパーサを生成するための文法定義から直接導かれたものです (\sphinxhref{https://github.com/python/cpython/tree/3.9/Grammar/python.gram}{Grammar/python.gram} を参照のこと)。ここに示すのは、コード生成およびエラー処理に関係する部分を省略したバージョンです。 The notation is a mixture of \sphinxhref{https://en.wikipedia.org/wiki/Extended\_Backus\%E2\%80\%93Naur\_form}{EBNF} and \sphinxhref{https://en.wikipedia.org/wiki/Parsing\_expression\_grammar}{PEG}. In particular, \sphinxcode{\sphinxupquote{\&}} followed by a symbol, token or parenthesized group indicates a positive lookahead (i.e., is required to match but not consumed), while \sphinxcode{\sphinxupquote{!}} indicates a negative lookahead (i.e., is required \_not\_ to match). We use the \sphinxcode{\sphinxupquote{|}} separator to mean PEG's "ordered choice" (written as \sphinxcode{\sphinxupquote{/}} in traditional PEG grammars). \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{c+cSingleline}{\PYGZsh{} PEG grammar for Python} \PYG{n+nf}{file}\PYG{p}{:} \PYG{p}{[}\PYG{n+nf}{statements}\PYG{p}{]} ENDMARKER \PYG{n+nf}{interactive}\PYG{p}{:} \PYG{n+nf}{statement\PYGZus{}newline} \PYG{n+nf}{eval}\PYG{p}{:} \PYG{n+nf}{expressions} NEWLINE\PYG{o}{*} ENDMARKER \PYG{n+nf}{func\PYGZus{}type}\PYG{p}{:} \PYGZsq{}(\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{type\PYGZus{}expressions}\PYG{p}{]} \PYGZsq{})\PYGZsq{} \PYGZsq{}\PYGZhy{}\PYGZgt{}\PYGZsq{} \PYG{n+nf}{expression} NEWLINE\PYG{o}{*} ENDMARKER \PYG{n+nf}{fstring}\PYG{p}{:} \PYG{n+nf}{star\PYGZus{}expressions} \PYG{c+cSingleline}{\PYGZsh{} type\PYGZus{}expressions allow */** but ignore them} \PYG{n+nf}{type\PYGZus{}expressions}\PYG{p}{:} \PYG{o}{|} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{expression}\PYG{o}{+} \PYGZsq{},\PYGZsq{} \PYGZsq{}*\PYGZsq{} \PYG{n+nf}{expression} \PYGZsq{},\PYGZsq{} \PYGZsq{}**\PYGZsq{} \PYG{n+nf}{expression} \PYG{o}{|} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{expression}\PYG{o}{+} \PYGZsq{},\PYGZsq{} \PYGZsq{}*\PYGZsq{} \PYG{n+nf}{expression} \PYG{o}{|} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{expression}\PYG{o}{+} \PYGZsq{},\PYGZsq{} \PYGZsq{}**\PYGZsq{} \PYG{n+nf}{expression} \PYG{o}{|} \PYGZsq{}*\PYGZsq{} \PYG{n+nf}{expression} \PYGZsq{},\PYGZsq{} \PYGZsq{}**\PYGZsq{} \PYG{n+nf}{expression} \PYG{o}{|} \PYGZsq{}*\PYGZsq{} \PYG{n+nf}{expression} \PYG{o}{|} \PYGZsq{}**\PYGZsq{} \PYG{n+nf}{expression} \PYG{o}{|} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{expression}\PYG{o}{+} \PYG{n+nf}{statements}\PYG{p}{:} \PYG{n+nf}{statement}\PYG{o}{+} \PYG{n+nf}{statement}\PYG{p}{:} \PYG{n+nf}{compound\PYGZus{}stmt} \PYG{o}{|} \PYG{n+nf}{simple\PYGZus{}stmt} \PYG{n+nf}{statement\PYGZus{}newline}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{compound\PYGZus{}stmt} NEWLINE \PYG{o}{|} \PYG{n+nf}{simple\PYGZus{}stmt} \PYG{o}{|} NEWLINE \PYG{o}{|} ENDMARKER \PYG{n+nf}{simple\PYGZus{}stmt}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{small\PYGZus{}stmt} !\PYGZsq{};\PYGZsq{} NEWLINE \PYG{c+cSingleline}{\PYGZsh{} Not needed, there for speedup} \PYG{o}{|} \PYGZsq{};\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{small\PYGZus{}stmt}\PYG{o}{+} \PYG{p}{[}\PYGZsq{};\PYGZsq{}\PYG{p}{]} NEWLINE \PYG{c+cSingleline}{\PYGZsh{} NOTE: assignment MUST precede expression, else parsing a simple assignment} \PYG{c+cSingleline}{\PYGZsh{} will throw a SyntaxError.} \PYG{n+nf}{small\PYGZus{}stmt}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{assignment} \PYG{o}{|} \PYG{n+nf}{star\PYGZus{}expressions} \PYG{o}{|} \PYG{n+nf}{return\PYGZus{}stmt} \PYG{o}{|} \PYG{n+nf}{import\PYGZus{}stmt} \PYG{o}{|} \PYG{n+nf}{raise\PYGZus{}stmt} \PYG{o}{|} \PYG{k}{\PYGZsq{}pass\PYGZsq{}} \PYG{o}{|} \PYG{n+nf}{del\PYGZus{}stmt} \PYG{o}{|} \PYG{n+nf}{yield\PYGZus{}stmt} \PYG{o}{|} \PYG{n+nf}{assert\PYGZus{}stmt} \PYG{o}{|} \PYG{k}{\PYGZsq{}break\PYGZsq{}} \PYG{o}{|} \PYG{k}{\PYGZsq{}continue\PYGZsq{}} \PYG{o}{|} \PYG{n+nf}{global\PYGZus{}stmt} \PYG{o}{|} \PYG{n+nf}{nonlocal\PYGZus{}stmt} \PYG{n+nf}{compound\PYGZus{}stmt}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{function\PYGZus{}def} \PYG{o}{|} \PYG{n+nf}{if\PYGZus{}stmt} \PYG{o}{|} \PYG{n+nf}{class\PYGZus{}def} \PYG{o}{|} \PYG{n+nf}{with\PYGZus{}stmt} \PYG{o}{|} \PYG{n+nf}{for\PYGZus{}stmt} \PYG{o}{|} \PYG{n+nf}{try\PYGZus{}stmt} \PYG{o}{|} \PYG{n+nf}{while\PYGZus{}stmt} \PYG{c+cSingleline}{\PYGZsh{} NOTE: annotated\PYGZus{}rhs may start with \PYGZsq{}yield\PYGZsq{}; yield\PYGZus{}expr must start with \PYGZsq{}yield\PYGZsq{}} \PYG{n+nf}{assignment}\PYG{p}{:} \PYG{o}{|} NAME \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{expression} \PYG{p}{[}\PYGZsq{}=\PYGZsq{} \PYG{n+nf}{annotated\PYGZus{}rhs} \PYG{p}{]} \PYG{o}{|} \PYG{p}{(}\PYGZsq{}(\PYGZsq{} \PYG{n+nf}{single\PYGZus{}target} \PYGZsq{})\PYGZsq{} \PYG{o}{|} \PYG{n+nf}{single\PYGZus{}subscript\PYGZus{}attribute\PYGZus{}target}\PYG{p}{)} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{expression} \PYG{p}{[}\PYGZsq{}=\PYGZsq{} \PYG{n+nf}{annotated\PYGZus{}rhs} \PYG{p}{]} \PYG{o}{|} \PYG{p}{(}\PYG{n+nf}{star\PYGZus{}targets} \PYGZsq{}=\PYGZsq{} \PYG{p}{)}\PYG{o}{+} \PYG{p}{(}\PYG{n+nf}{yield\PYGZus{}expr} \PYG{o}{|} \PYG{n+nf}{star\PYGZus{}expressions}\PYG{p}{)} !\PYGZsq{}=\PYGZsq{} \PYG{p}{[}TYPE\PYGZus{}COMMENT\PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{single\PYGZus{}target} \PYG{n+nf}{augassign} \PYGZti{} \PYG{p}{(}\PYG{n+nf}{yield\PYGZus{}expr} \PYG{o}{|} \PYG{n+nf}{star\PYGZus{}expressions}\PYG{p}{)} \PYG{n+nf}{augassign}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}+=\PYGZsq{} \PYG{o}{|} \PYGZsq{}\PYGZhy{}=\PYGZsq{} \PYG{o}{|} \PYGZsq{}*=\PYGZsq{} \PYG{o}{|} \PYGZsq{}@=\PYGZsq{} \PYG{o}{|} \PYGZsq{}/=\PYGZsq{} \PYG{o}{|} \PYGZsq{}\PYGZpc{}=\PYGZsq{} \PYG{o}{|} \PYGZsq{}\PYGZam{}=\PYGZsq{} \PYG{o}{|} \PYGZsq{}|=\PYGZsq{} \PYG{o}{|} \PYGZsq{}\PYGZca{}=\PYGZsq{} \PYG{o}{|} \PYGZsq{}\PYGZlt{}\PYGZlt{}=\PYGZsq{} \PYG{o}{|} \PYGZsq{}\PYGZgt{}\PYGZgt{}=\PYGZsq{} \PYG{o}{|} \PYGZsq{}**=\PYGZsq{} \PYG{o}{|} \PYGZsq{}//=\PYGZsq{} \PYG{n+nf}{global\PYGZus{}stmt}\PYG{p}{:} \PYG{k}{\PYGZsq{}global\PYGZsq{}} \PYGZsq{},\PYGZsq{}\PYG{o}{.}NAME\PYG{o}{+} \PYG{n+nf}{nonlocal\PYGZus{}stmt}\PYG{p}{:} \PYG{k}{\PYGZsq{}nonlocal\PYGZsq{}} \PYGZsq{},\PYGZsq{}\PYG{o}{.}NAME\PYG{o}{+} \PYG{n+nf}{yield\PYGZus{}stmt}\PYG{p}{:} \PYG{n+nf}{yield\PYGZus{}expr} \PYG{n+nf}{assert\PYGZus{}stmt}\PYG{p}{:} \PYG{k}{\PYGZsq{}assert\PYGZsq{}} \PYG{n+nf}{expression} \PYG{p}{[}\PYGZsq{},\PYGZsq{} \PYG{n+nf}{expression} \PYG{p}{]} \PYG{n+nf}{del\PYGZus{}stmt}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}del\PYGZsq{}} \PYG{n+nf}{del\PYGZus{}targets} \PYGZam{}\PYG{p}{(}\PYGZsq{};\PYGZsq{} \PYG{o}{|} NEWLINE\PYG{p}{)} \PYG{n+nf}{import\PYGZus{}stmt}\PYG{p}{:} \PYG{n+nf}{import\PYGZus{}name} \PYG{o}{|} \PYG{n+nf}{import\PYGZus{}from} \PYG{n+nf}{import\PYGZus{}name}\PYG{p}{:} \PYG{k}{\PYGZsq{}import\PYGZsq{}} \PYG{n+nf}{dotted\PYGZus{}as\PYGZus{}names} \PYG{c+cSingleline}{\PYGZsh{} note below: the (\PYGZsq{}.\PYGZsq{} | \PYGZsq{}...\PYGZsq{}) is necessary because \PYGZsq{}...\PYGZsq{} is tokenized as ELLIPSIS} \PYG{n+nf}{import\PYGZus{}from}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}from\PYGZsq{}} \PYG{p}{(}\PYGZsq{}.\PYGZsq{} \PYG{o}{|} \PYGZsq{}...\PYGZsq{}\PYG{p}{)}\PYG{o}{*} \PYG{n+nf}{dotted\PYGZus{}name} \PYG{k}{\PYGZsq{}import\PYGZsq{}} \PYG{n+nf}{import\PYGZus{}from\PYGZus{}targets} \PYG{o}{|} \PYG{k}{\PYGZsq{}from\PYGZsq{}} \PYG{p}{(}\PYGZsq{}.\PYGZsq{} \PYG{o}{|} \PYGZsq{}...\PYGZsq{}\PYG{p}{)}\PYG{o}{+} \PYG{k}{\PYGZsq{}import\PYGZsq{}} \PYG{n+nf}{import\PYGZus{}from\PYGZus{}targets} \PYG{n+nf}{import\PYGZus{}from\PYGZus{}targets}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}(\PYGZsq{} \PYG{n+nf}{import\PYGZus{}from\PYGZus{}as\PYGZus{}names} \PYG{p}{[}\PYGZsq{},\PYGZsq{}\PYG{p}{]} \PYGZsq{})\PYGZsq{} \PYG{o}{|} \PYG{n+nf}{import\PYGZus{}from\PYGZus{}as\PYGZus{}names} !\PYGZsq{},\PYGZsq{} \PYG{o}{|} \PYGZsq{}*\PYGZsq{} \PYG{n+nf}{import\PYGZus{}from\PYGZus{}as\PYGZus{}names}\PYG{p}{:} \PYG{o}{|} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{import\PYGZus{}from\PYGZus{}as\PYGZus{}name}\PYG{o}{+} \PYG{n+nf}{import\PYGZus{}from\PYGZus{}as\PYGZus{}name}\PYG{p}{:} \PYG{o}{|} NAME \PYG{p}{[}\PYG{k}{\PYGZsq{}as\PYGZsq{}} NAME \PYG{p}{]} \PYG{n+nf}{dotted\PYGZus{}as\PYGZus{}names}\PYG{p}{:} \PYG{o}{|} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{dotted\PYGZus{}as\PYGZus{}name}\PYG{o}{+} \PYG{n+nf}{dotted\PYGZus{}as\PYGZus{}name}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{dotted\PYGZus{}name} \PYG{p}{[}\PYG{k}{\PYGZsq{}as\PYGZsq{}} NAME \PYG{p}{]} \PYG{n+nf}{dotted\PYGZus{}name}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{dotted\PYGZus{}name} \PYGZsq{}.\PYGZsq{} NAME \PYG{o}{|} NAME \PYG{n+nf}{if\PYGZus{}stmt}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}if\PYGZsq{}} \PYG{n+nf}{named\PYGZus{}expression} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{block} \PYG{n+nf}{elif\PYGZus{}stmt} \PYG{o}{|} \PYG{k}{\PYGZsq{}if\PYGZsq{}} \PYG{n+nf}{named\PYGZus{}expression} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{block} \PYG{p}{[}\PYG{n+nf}{else\PYGZus{}block}\PYG{p}{]} \PYG{n+nf}{elif\PYGZus{}stmt}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}elif\PYGZsq{}} \PYG{n+nf}{named\PYGZus{}expression} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{block} \PYG{n+nf}{elif\PYGZus{}stmt} \PYG{o}{|} \PYG{k}{\PYGZsq{}elif\PYGZsq{}} \PYG{n+nf}{named\PYGZus{}expression} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{block} \PYG{p}{[}\PYG{n+nf}{else\PYGZus{}block}\PYG{p}{]} \PYG{n+nf}{else\PYGZus{}block}\PYG{p}{:} \PYG{k}{\PYGZsq{}else\PYGZsq{}} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{block} \PYG{n+nf}{while\PYGZus{}stmt}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}while\PYGZsq{}} \PYG{n+nf}{named\PYGZus{}expression} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{block} \PYG{p}{[}\PYG{n+nf}{else\PYGZus{}block}\PYG{p}{]} \PYG{n+nf}{for\PYGZus{}stmt}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}for\PYGZsq{}} \PYG{n+nf}{star\PYGZus{}targets} \PYG{k}{\PYGZsq{}in\PYGZsq{}} \PYGZti{} \PYG{n+nf}{star\PYGZus{}expressions} \PYGZsq{}:\PYGZsq{} \PYG{p}{[}TYPE\PYGZus{}COMMENT\PYG{p}{]} \PYG{n+nf}{block} \PYG{p}{[}\PYG{n+nf}{else\PYGZus{}block}\PYG{p}{]} \PYG{o}{|} ASYNC \PYG{k}{\PYGZsq{}for\PYGZsq{}} \PYG{n+nf}{star\PYGZus{}targets} \PYG{k}{\PYGZsq{}in\PYGZsq{}} \PYGZti{} \PYG{n+nf}{star\PYGZus{}expressions} \PYGZsq{}:\PYGZsq{} \PYG{p}{[}TYPE\PYGZus{}COMMENT\PYG{p}{]} \PYG{n+nf}{block} \PYG{p}{[}\PYG{n+nf}{else\PYGZus{}block}\PYG{p}{]} \PYG{n+nf}{with\PYGZus{}stmt}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}with\PYGZsq{}} \PYGZsq{}(\PYGZsq{} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{with\PYGZus{}item}\PYG{o}{+} \PYGZsq{},\PYGZsq{}\PYG{o}{?} \PYGZsq{})\PYGZsq{} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{block} \PYG{o}{|} \PYG{k}{\PYGZsq{}with\PYGZsq{}} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{with\PYGZus{}item}\PYG{o}{+} \PYGZsq{}:\PYGZsq{} \PYG{p}{[}TYPE\PYGZus{}COMMENT\PYG{p}{]} \PYG{n+nf}{block} \PYG{o}{|} ASYNC \PYG{k}{\PYGZsq{}with\PYGZsq{}} \PYGZsq{}(\PYGZsq{} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{with\PYGZus{}item}\PYG{o}{+} \PYGZsq{},\PYGZsq{}\PYG{o}{?} \PYGZsq{})\PYGZsq{} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{block} \PYG{o}{|} ASYNC \PYG{k}{\PYGZsq{}with\PYGZsq{}} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{with\PYGZus{}item}\PYG{o}{+} \PYGZsq{}:\PYGZsq{} \PYG{p}{[}TYPE\PYGZus{}COMMENT\PYG{p}{]} \PYG{n+nf}{block} \PYG{n+nf}{with\PYGZus{}item}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{expression} \PYG{k}{\PYGZsq{}as\PYGZsq{}} \PYG{n+nf}{star\PYGZus{}target} \PYGZam{}\PYG{p}{(}\PYGZsq{},\PYGZsq{} \PYG{o}{|} \PYGZsq{})\PYGZsq{} \PYG{o}{|} \PYGZsq{}:\PYGZsq{}\PYG{p}{)} \PYG{o}{|} \PYG{n+nf}{expression} \PYG{n+nf}{try\PYGZus{}stmt}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}try\PYGZsq{}} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{block} \PYG{n+nf}{finally\PYGZus{}block} \PYG{o}{|} \PYG{k}{\PYGZsq{}try\PYGZsq{}} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{block} \PYG{n+nf}{except\PYGZus{}block}\PYG{o}{+} \PYG{p}{[}\PYG{n+nf}{else\PYGZus{}block}\PYG{p}{]} \PYG{p}{[}\PYG{n+nf}{finally\PYGZus{}block}\PYG{p}{]} \PYG{n+nf}{except\PYGZus{}block}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}except\PYGZsq{}} \PYG{n+nf}{expression} \PYG{p}{[}\PYG{k}{\PYGZsq{}as\PYGZsq{}} NAME \PYG{p}{]} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{block} \PYG{o}{|} \PYG{k}{\PYGZsq{}except\PYGZsq{}} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{block} \PYG{n+nf}{finally\PYGZus{}block}\PYG{p}{:} \PYG{k}{\PYGZsq{}finally\PYGZsq{}} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{block} \PYG{n+nf}{return\PYGZus{}stmt}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}return\PYGZsq{}} \PYG{p}{[}\PYG{n+nf}{star\PYGZus{}expressions}\PYG{p}{]} \PYG{n+nf}{raise\PYGZus{}stmt}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}raise\PYGZsq{}} \PYG{n+nf}{expression} \PYG{p}{[}\PYG{k}{\PYGZsq{}from\PYGZsq{}} \PYG{n+nf}{expression} \PYG{p}{]} \PYG{o}{|} \PYG{k}{\PYGZsq{}raise\PYGZsq{}} \PYG{n+nf}{function\PYGZus{}def}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{decorators} \PYG{n+nf}{function\PYGZus{}def\PYGZus{}raw} \PYG{o}{|} \PYG{n+nf}{function\PYGZus{}def\PYGZus{}raw} \PYG{n+nf}{function\PYGZus{}def\PYGZus{}raw}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}def\PYGZsq{}} NAME \PYGZsq{}(\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{params}\PYG{p}{]} \PYGZsq{})\PYGZsq{} \PYG{p}{[}\PYGZsq{}\PYGZhy{}\PYGZgt{}\PYGZsq{} \PYG{n+nf}{expression} \PYG{p}{]} \PYGZsq{}:\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{func\PYGZus{}type\PYGZus{}comment}\PYG{p}{]} \PYG{n+nf}{block} \PYG{o}{|} ASYNC \PYG{k}{\PYGZsq{}def\PYGZsq{}} NAME \PYGZsq{}(\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{params}\PYG{p}{]} \PYGZsq{})\PYGZsq{} \PYG{p}{[}\PYGZsq{}\PYGZhy{}\PYGZgt{}\PYGZsq{} \PYG{n+nf}{expression} \PYG{p}{]} \PYGZsq{}:\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{func\PYGZus{}type\PYGZus{}comment}\PYG{p}{]} \PYG{n+nf}{block} \PYG{n+nf}{func\PYGZus{}type\PYGZus{}comment}\PYG{p}{:} \PYG{o}{|} NEWLINE TYPE\PYGZus{}COMMENT \PYGZam{}\PYG{p}{(}NEWLINE INDENT\PYG{p}{)} \PYG{c+cSingleline}{\PYGZsh{} Must be followed by indented block} \PYG{o}{|} TYPE\PYGZus{}COMMENT \PYG{n+nf}{params}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{parameters} \PYG{n+nf}{parameters}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{slash\PYGZus{}no\PYGZus{}default} \PYG{n+nf}{param\PYGZus{}no\PYGZus{}default}\PYG{o}{*} \PYG{n+nf}{param\PYGZus{}with\PYGZus{}default}\PYG{o}{*} \PYG{p}{[}\PYG{n+nf}{star\PYGZus{}etc}\PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{slash\PYGZus{}with\PYGZus{}default} \PYG{n+nf}{param\PYGZus{}with\PYGZus{}default}\PYG{o}{*} \PYG{p}{[}\PYG{n+nf}{star\PYGZus{}etc}\PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{param\PYGZus{}no\PYGZus{}default}\PYG{o}{+} \PYG{n+nf}{param\PYGZus{}with\PYGZus{}default}\PYG{o}{*} \PYG{p}{[}\PYG{n+nf}{star\PYGZus{}etc}\PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{param\PYGZus{}with\PYGZus{}default}\PYG{o}{+} \PYG{p}{[}\PYG{n+nf}{star\PYGZus{}etc}\PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{star\PYGZus{}etc} \PYG{c+cSingleline}{\PYGZsh{} Some duplication here because we can\PYGZsq{}t write (\PYGZsq{},\PYGZsq{} | \PYGZam{}\PYGZsq{})\PYGZsq{}),} \PYG{c+cSingleline}{\PYGZsh{} which is because we don\PYGZsq{}t support empty alternatives (yet).} \PYG{c+cSingleline}{\PYGZsh{}} \PYG{n+nf}{slash\PYGZus{}no\PYGZus{}default}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{param\PYGZus{}no\PYGZus{}default}\PYG{o}{+} \PYGZsq{}/\PYGZsq{} \PYGZsq{},\PYGZsq{} \PYG{o}{|} \PYG{n+nf}{param\PYGZus{}no\PYGZus{}default}\PYG{o}{+} \PYGZsq{}/\PYGZsq{} \PYGZam{}\PYGZsq{})\PYGZsq{} \PYG{n+nf}{slash\PYGZus{}with\PYGZus{}default}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{param\PYGZus{}no\PYGZus{}default}\PYG{o}{*} \PYG{n+nf}{param\PYGZus{}with\PYGZus{}default}\PYG{o}{+} \PYGZsq{}/\PYGZsq{} \PYGZsq{},\PYGZsq{} \PYG{o}{|} \PYG{n+nf}{param\PYGZus{}no\PYGZus{}default}\PYG{o}{*} \PYG{n+nf}{param\PYGZus{}with\PYGZus{}default}\PYG{o}{+} \PYGZsq{}/\PYGZsq{} \PYGZam{}\PYGZsq{})\PYGZsq{} \PYG{n+nf}{star\PYGZus{}etc}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}*\PYGZsq{} \PYG{n+nf}{param\PYGZus{}no\PYGZus{}default} \PYG{n+nf}{param\PYGZus{}maybe\PYGZus{}default}\PYG{o}{*} \PYG{p}{[}\PYG{n+nf}{kwds}\PYG{p}{]} \PYG{o}{|} \PYGZsq{}*\PYGZsq{} \PYGZsq{},\PYGZsq{} \PYG{n+nf}{param\PYGZus{}maybe\PYGZus{}default}\PYG{o}{+} \PYG{p}{[}\PYG{n+nf}{kwds}\PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{kwds} \PYG{n+nf}{kwds}\PYG{p}{:} \PYGZsq{}**\PYGZsq{} \PYG{n+nf}{param\PYGZus{}no\PYGZus{}default} \PYG{c+cSingleline}{\PYGZsh{} One parameter. This *includes* a following comma and type comment.} \PYG{c+cSingleline}{\PYGZsh{}} \PYG{c+cSingleline}{\PYGZsh{} There are three styles:} \PYG{c+cSingleline}{\PYGZsh{} \PYGZhy{} No default} \PYG{c+cSingleline}{\PYGZsh{} \PYGZhy{} With default} \PYG{c+cSingleline}{\PYGZsh{} \PYGZhy{} Maybe with default} \PYG{c+cSingleline}{\PYGZsh{}} \PYG{c+cSingleline}{\PYGZsh{} There are two alternative forms of each, to deal with type comments:} \PYG{c+cSingleline}{\PYGZsh{} \PYGZhy{} Ends in a comma followed by an optional type comment} \PYG{c+cSingleline}{\PYGZsh{} \PYGZhy{} No comma, optional type comment, must be followed by close paren} \PYG{c+cSingleline}{\PYGZsh{} The latter form is for a final parameter without trailing comma.} \PYG{c+cSingleline}{\PYGZsh{}} \PYG{n+nf}{param\PYGZus{}no\PYGZus{}default}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{param} \PYGZsq{},\PYGZsq{} TYPE\PYGZus{}COMMENT\PYG{o}{?} \PYG{o}{|} \PYG{n+nf}{param} TYPE\PYGZus{}COMMENT\PYG{o}{?} \PYGZam{}\PYGZsq{})\PYGZsq{} \PYG{n+nf}{param\PYGZus{}with\PYGZus{}default}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{param} \PYG{n+nf}{default} \PYGZsq{},\PYGZsq{} TYPE\PYGZus{}COMMENT\PYG{o}{?} \PYG{o}{|} \PYG{n+nf}{param} \PYG{n+nf}{default} TYPE\PYGZus{}COMMENT\PYG{o}{?} \PYGZam{}\PYGZsq{})\PYGZsq{} \PYG{n+nf}{param\PYGZus{}maybe\PYGZus{}default}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{param} \PYG{n+nf}{default}\PYG{o}{?} \PYGZsq{},\PYGZsq{} TYPE\PYGZus{}COMMENT\PYG{o}{?} \PYG{o}{|} \PYG{n+nf}{param} \PYG{n+nf}{default}\PYG{o}{?} TYPE\PYGZus{}COMMENT\PYG{o}{?} \PYGZam{}\PYGZsq{})\PYGZsq{} \PYG{n+nf}{param}\PYG{p}{:} NAME \PYG{n+nf}{annotation}\PYG{o}{?} \PYG{n+nf}{annotation}\PYG{p}{:} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{expression} \PYG{n+nf}{default}\PYG{p}{:} \PYGZsq{}=\PYGZsq{} \PYG{n+nf}{expression} \PYG{n+nf}{decorators}\PYG{p}{:} \PYG{p}{(}\PYGZsq{}@\PYGZsq{} \PYG{n+nf}{named\PYGZus{}expression} NEWLINE \PYG{p}{)}\PYG{o}{+} \PYG{n+nf}{class\PYGZus{}def}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{decorators} \PYG{n+nf}{class\PYGZus{}def\PYGZus{}raw} \PYG{o}{|} \PYG{n+nf}{class\PYGZus{}def\PYGZus{}raw} \PYG{n+nf}{class\PYGZus{}def\PYGZus{}raw}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}class\PYGZsq{}} NAME \PYG{p}{[}\PYGZsq{}(\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{arguments}\PYG{p}{]} \PYGZsq{})\PYGZsq{} \PYG{p}{]} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{block} \PYG{n+nf}{block}\PYG{p}{:} \PYG{o}{|} NEWLINE INDENT \PYG{n+nf}{statements} DEDENT \PYG{o}{|} \PYG{n+nf}{simple\PYGZus{}stmt} \PYG{n+nf}{star\PYGZus{}expressions}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{star\PYGZus{}expression} \PYG{p}{(}\PYGZsq{},\PYGZsq{} \PYG{n+nf}{star\PYGZus{}expression} \PYG{p}{)}\PYG{o}{+} \PYG{p}{[}\PYGZsq{},\PYGZsq{}\PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{star\PYGZus{}expression} \PYGZsq{},\PYGZsq{} \PYG{o}{|} \PYG{n+nf}{star\PYGZus{}expression} \PYG{n+nf}{star\PYGZus{}expression}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}*\PYGZsq{} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{o}{|} \PYG{n+nf}{expression} \PYG{n+nf}{star\PYGZus{}named\PYGZus{}expressions}\PYG{p}{:} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{star\PYGZus{}named\PYGZus{}expression}\PYG{o}{+} \PYG{p}{[}\PYGZsq{},\PYGZsq{}\PYG{p}{]} \PYG{n+nf}{star\PYGZus{}named\PYGZus{}expression}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}*\PYGZsq{} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{o}{|} \PYG{n+nf}{named\PYGZus{}expression} \PYG{n+nf}{named\PYGZus{}expression}\PYG{p}{:} \PYG{o}{|} NAME \PYGZsq{}:=\PYGZsq{} \PYGZti{} \PYG{n+nf}{expression} \PYG{o}{|} \PYG{n+nf}{expression} !\PYGZsq{}:=\PYGZsq{} \PYG{n+nf}{annotated\PYGZus{}rhs}\PYG{p}{:} \PYG{n+nf}{yield\PYGZus{}expr} \PYG{o}{|} \PYG{n+nf}{star\PYGZus{}expressions} \PYG{n+nf}{expressions}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{expression} \PYG{p}{(}\PYGZsq{},\PYGZsq{} \PYG{n+nf}{expression} \PYG{p}{)}\PYG{o}{+} \PYG{p}{[}\PYGZsq{},\PYGZsq{}\PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{expression} \PYGZsq{},\PYGZsq{} \PYG{o}{|} \PYG{n+nf}{expression} \PYG{n+nf}{expression}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{disjunction} \PYG{k}{\PYGZsq{}if\PYGZsq{}} \PYG{n+nf}{disjunction} \PYG{k}{\PYGZsq{}else\PYGZsq{}} \PYG{n+nf}{expression} \PYG{o}{|} \PYG{n+nf}{disjunction} \PYG{o}{|} \PYG{n+nf}{lambdef} \PYG{n+nf}{lambdef}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}lambda\PYGZsq{}} \PYG{p}{[}\PYG{n+nf}{lambda\PYGZus{}params}\PYG{p}{]} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{expression} \PYG{n+nf}{lambda\PYGZus{}params}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}parameters} \PYG{c+cSingleline}{\PYGZsh{} lambda\PYGZus{}parameters etc. duplicates parameters but without annotations} \PYG{c+cSingleline}{\PYGZsh{} or type comments, and if there\PYGZsq{}s no comma after a parameter, we expect} \PYG{c+cSingleline}{\PYGZsh{} a colon, not a close parenthesis. (For more, see parameters above.)} \PYG{c+cSingleline}{\PYGZsh{}} \PYG{n+nf}{lambda\PYGZus{}parameters}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}slash\PYGZus{}no\PYGZus{}default} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}no\PYGZus{}default}\PYG{o}{*} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}with\PYGZus{}default}\PYG{o}{*} \PYG{p}{[}\PYG{n+nf}{lambda\PYGZus{}star\PYGZus{}etc}\PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}slash\PYGZus{}with\PYGZus{}default} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}with\PYGZus{}default}\PYG{o}{*} \PYG{p}{[}\PYG{n+nf}{lambda\PYGZus{}star\PYGZus{}etc}\PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}no\PYGZus{}default}\PYG{o}{+} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}with\PYGZus{}default}\PYG{o}{*} \PYG{p}{[}\PYG{n+nf}{lambda\PYGZus{}star\PYGZus{}etc}\PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}with\PYGZus{}default}\PYG{o}{+} \PYG{p}{[}\PYG{n+nf}{lambda\PYGZus{}star\PYGZus{}etc}\PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}star\PYGZus{}etc} \PYG{n+nf}{lambda\PYGZus{}slash\PYGZus{}no\PYGZus{}default}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}no\PYGZus{}default}\PYG{o}{+} \PYGZsq{}/\PYGZsq{} \PYGZsq{},\PYGZsq{} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}no\PYGZus{}default}\PYG{o}{+} \PYGZsq{}/\PYGZsq{} \PYGZam{}\PYGZsq{}:\PYGZsq{} \PYG{n+nf}{lambda\PYGZus{}slash\PYGZus{}with\PYGZus{}default}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}no\PYGZus{}default}\PYG{o}{*} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}with\PYGZus{}default}\PYG{o}{+} \PYGZsq{}/\PYGZsq{} \PYGZsq{},\PYGZsq{} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}no\PYGZus{}default}\PYG{o}{*} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}with\PYGZus{}default}\PYG{o}{+} \PYGZsq{}/\PYGZsq{} \PYGZam{}\PYGZsq{}:\PYGZsq{} \PYG{n+nf}{lambda\PYGZus{}star\PYGZus{}etc}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}*\PYGZsq{} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}no\PYGZus{}default} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}maybe\PYGZus{}default}\PYG{o}{*} \PYG{p}{[}\PYG{n+nf}{lambda\PYGZus{}kwds}\PYG{p}{]} \PYG{o}{|} \PYGZsq{}*\PYGZsq{} \PYGZsq{},\PYGZsq{} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}maybe\PYGZus{}default}\PYG{o}{+} \PYG{p}{[}\PYG{n+nf}{lambda\PYGZus{}kwds}\PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}kwds} \PYG{n+nf}{lambda\PYGZus{}kwds}\PYG{p}{:} \PYGZsq{}**\PYGZsq{} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}no\PYGZus{}default} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}no\PYGZus{}default}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}param} \PYGZsq{},\PYGZsq{} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}param} \PYGZam{}\PYGZsq{}:\PYGZsq{} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}with\PYGZus{}default}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}param} \PYG{n+nf}{default} \PYGZsq{},\PYGZsq{} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}param} \PYG{n+nf}{default} \PYGZam{}\PYGZsq{}:\PYGZsq{} \PYG{n+nf}{lambda\PYGZus{}param\PYGZus{}maybe\PYGZus{}default}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}param} \PYG{n+nf}{default}\PYG{o}{?} \PYGZsq{},\PYGZsq{} \PYG{o}{|} \PYG{n+nf}{lambda\PYGZus{}param} \PYG{n+nf}{default}\PYG{o}{?} \PYGZam{}\PYGZsq{}:\PYGZsq{} \PYG{n+nf}{lambda\PYGZus{}param}\PYG{p}{:} NAME \PYG{n+nf}{disjunction}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{conjunction} \PYG{p}{(}\PYG{k}{\PYGZsq{}or\PYGZsq{}} \PYG{n+nf}{conjunction} \PYG{p}{)}\PYG{o}{+} \PYG{o}{|} \PYG{n+nf}{conjunction} \PYG{n+nf}{conjunction}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{inversion} \PYG{p}{(}\PYG{k}{\PYGZsq{}and\PYGZsq{}} \PYG{n+nf}{inversion} \PYG{p}{)}\PYG{o}{+} \PYG{o}{|} \PYG{n+nf}{inversion} \PYG{n+nf}{inversion}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}not\PYGZsq{}} \PYG{n+nf}{inversion} \PYG{o}{|} \PYG{n+nf}{comparison} \PYG{n+nf}{comparison}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{n+nf}{compare\PYGZus{}op\PYGZus{}bitwise\PYGZus{}or\PYGZus{}pair}\PYG{o}{+} \PYG{o}{|} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{n+nf}{compare\PYGZus{}op\PYGZus{}bitwise\PYGZus{}or\PYGZus{}pair}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{eq\PYGZus{}bitwise\PYGZus{}or} \PYG{o}{|} \PYG{n+nf}{noteq\PYGZus{}bitwise\PYGZus{}or} \PYG{o}{|} \PYG{n+nf}{lte\PYGZus{}bitwise\PYGZus{}or} \PYG{o}{|} \PYG{n+nf}{lt\PYGZus{}bitwise\PYGZus{}or} \PYG{o}{|} \PYG{n+nf}{gte\PYGZus{}bitwise\PYGZus{}or} \PYG{o}{|} \PYG{n+nf}{gt\PYGZus{}bitwise\PYGZus{}or} \PYG{o}{|} \PYG{n+nf}{notin\PYGZus{}bitwise\PYGZus{}or} \PYG{o}{|} \PYG{n+nf}{in\PYGZus{}bitwise\PYGZus{}or} \PYG{o}{|} \PYG{n+nf}{isnot\PYGZus{}bitwise\PYGZus{}or} \PYG{o}{|} \PYG{n+nf}{is\PYGZus{}bitwise\PYGZus{}or} \PYG{n+nf}{eq\PYGZus{}bitwise\PYGZus{}or}\PYG{p}{:} \PYGZsq{}==\PYGZsq{} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{n+nf}{noteq\PYGZus{}bitwise\PYGZus{}or}\PYG{p}{:} \PYG{o}{|} \PYG{p}{(}\PYGZsq{}!=\PYGZsq{} \PYG{p}{)} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{n+nf}{lte\PYGZus{}bitwise\PYGZus{}or}\PYG{p}{:} \PYGZsq{}\PYGZlt{}=\PYGZsq{} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{n+nf}{lt\PYGZus{}bitwise\PYGZus{}or}\PYG{p}{:} \PYGZsq{}\PYGZlt{}\PYGZsq{} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{n+nf}{gte\PYGZus{}bitwise\PYGZus{}or}\PYG{p}{:} \PYGZsq{}\PYGZgt{}=\PYGZsq{} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{n+nf}{gt\PYGZus{}bitwise\PYGZus{}or}\PYG{p}{:} \PYGZsq{}\PYGZgt{}\PYGZsq{} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{n+nf}{notin\PYGZus{}bitwise\PYGZus{}or}\PYG{p}{:} \PYG{k}{\PYGZsq{}not\PYGZsq{}} \PYG{k}{\PYGZsq{}in\PYGZsq{}} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{n+nf}{in\PYGZus{}bitwise\PYGZus{}or}\PYG{p}{:} \PYG{k}{\PYGZsq{}in\PYGZsq{}} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{n+nf}{isnot\PYGZus{}bitwise\PYGZus{}or}\PYG{p}{:} \PYG{k}{\PYGZsq{}is\PYGZsq{}} \PYG{k}{\PYGZsq{}not\PYGZsq{}} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{n+nf}{is\PYGZus{}bitwise\PYGZus{}or}\PYG{p}{:} \PYG{k}{\PYGZsq{}is\PYGZsq{}} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{n+nf}{bitwise\PYGZus{}or}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{bitwise\PYGZus{}or} \PYGZsq{}|\PYGZsq{} \PYG{n+nf}{bitwise\PYGZus{}xor} \PYG{o}{|} \PYG{n+nf}{bitwise\PYGZus{}xor} \PYG{n+nf}{bitwise\PYGZus{}xor}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{bitwise\PYGZus{}xor} \PYGZsq{}\PYGZca{}\PYGZsq{} \PYG{n+nf}{bitwise\PYGZus{}and} \PYG{o}{|} \PYG{n+nf}{bitwise\PYGZus{}and} \PYG{n+nf}{bitwise\PYGZus{}and}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{bitwise\PYGZus{}and} \PYGZsq{}\PYGZam{}\PYGZsq{} \PYG{n+nf}{shift\PYGZus{}expr} \PYG{o}{|} \PYG{n+nf}{shift\PYGZus{}expr} \PYG{n+nf}{shift\PYGZus{}expr}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{shift\PYGZus{}expr} \PYGZsq{}\PYGZlt{}\PYGZlt{}\PYGZsq{} \PYG{n+nf}{sum} \PYG{o}{|} \PYG{n+nf}{shift\PYGZus{}expr} \PYGZsq{}\PYGZgt{}\PYGZgt{}\PYGZsq{} \PYG{n+nf}{sum} \PYG{o}{|} \PYG{n+nf}{sum} \PYG{n+nf}{sum}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{sum} \PYGZsq{}+\PYGZsq{} \PYG{n+nf}{term} \PYG{o}{|} \PYG{n+nf}{sum} \PYGZsq{}\PYGZhy{}\PYGZsq{} \PYG{n+nf}{term} \PYG{o}{|} \PYG{n+nf}{term} \PYG{n+nf}{term}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{term} \PYGZsq{}*\PYGZsq{} \PYG{n+nf}{factor} \PYG{o}{|} \PYG{n+nf}{term} \PYGZsq{}/\PYGZsq{} \PYG{n+nf}{factor} \PYG{o}{|} \PYG{n+nf}{term} \PYGZsq{}//\PYGZsq{} \PYG{n+nf}{factor} \PYG{o}{|} \PYG{n+nf}{term} \PYGZsq{}\PYGZpc{}\PYGZsq{} \PYG{n+nf}{factor} \PYG{o}{|} \PYG{n+nf}{term} \PYGZsq{}@\PYGZsq{} \PYG{n+nf}{factor} \PYG{o}{|} \PYG{n+nf}{factor} \PYG{n+nf}{factor}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}+\PYGZsq{} \PYG{n+nf}{factor} \PYG{o}{|} \PYGZsq{}\PYGZhy{}\PYGZsq{} \PYG{n+nf}{factor} \PYG{o}{|} \PYGZsq{}\PYGZti{}\PYGZsq{} \PYG{n+nf}{factor} \PYG{o}{|} \PYG{n+nf}{power} \PYG{n+nf}{power}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{await\PYGZus{}primary} \PYGZsq{}**\PYGZsq{} \PYG{n+nf}{factor} \PYG{o}{|} \PYG{n+nf}{await\PYGZus{}primary} \PYG{n+nf}{await\PYGZus{}primary}\PYG{p}{:} \PYG{o}{|} AWAIT \PYG{n+nf}{primary} \PYG{o}{|} \PYG{n+nf}{primary} \PYG{n+nf}{primary}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{primary} \PYGZsq{}.\PYGZsq{} NAME \PYG{o}{|} \PYG{n+nf}{primary} \PYG{n+nf}{genexp} \PYG{o}{|} \PYG{n+nf}{primary} \PYGZsq{}(\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{arguments}\PYG{p}{]} \PYGZsq{})\PYGZsq{} \PYG{o}{|} \PYG{n+nf}{primary} \PYGZsq{}[\PYGZsq{} \PYG{n+nf}{slices} \PYGZsq{}]\PYGZsq{} \PYG{o}{|} \PYG{n+nf}{atom} \PYG{n+nf}{slices}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{slice} !\PYGZsq{},\PYGZsq{} \PYG{o}{|} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{slice}\PYG{o}{+} \PYG{p}{[}\PYGZsq{},\PYGZsq{}\PYG{p}{]} \PYG{n+nf}{slice}\PYG{p}{:} \PYG{o}{|} \PYG{p}{[}\PYG{n+nf}{expression}\PYG{p}{]} \PYGZsq{}:\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{expression}\PYG{p}{]} \PYG{p}{[}\PYGZsq{}:\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{expression}\PYG{p}{]} \PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{expression} \PYG{n+nf}{atom}\PYG{p}{:} \PYG{o}{|} NAME \PYG{o}{|} \PYG{k}{\PYGZsq{}True\PYGZsq{}} \PYG{o}{|} \PYG{k}{\PYGZsq{}False\PYGZsq{}} \PYG{o}{|} \PYG{k}{\PYGZsq{}None\PYGZsq{}} \PYG{o}{|} \PYG{k}{\PYGZsq{}\PYGZus{}\PYGZus{}peg\PYGZus{}parser\PYGZus{}\PYGZus{}\PYGZsq{}} \PYG{o}{|} \PYG{n+nf}{strings} \PYG{o}{|} NUMBER \PYG{o}{|} \PYG{p}{(}\PYG{n+nf}{tuple} \PYG{o}{|} \PYG{n+nf}{group} \PYG{o}{|} \PYG{n+nf}{genexp}\PYG{p}{)} \PYG{o}{|} \PYG{p}{(}\PYG{n+nf}{list} \PYG{o}{|} \PYG{n+nf}{listcomp}\PYG{p}{)} \PYG{o}{|} \PYG{p}{(}\PYG{n+nf}{dict} \PYG{o}{|} \PYG{n+nf}{set} \PYG{o}{|} \PYG{n+nf}{dictcomp} \PYG{o}{|} \PYG{n+nf}{setcomp}\PYG{p}{)} \PYG{o}{|} \PYGZsq{}...\PYGZsq{} \PYG{n+nf}{strings}\PYG{p}{:} STRING\PYG{o}{+} \PYG{n+nf}{list}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}[\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{star\PYGZus{}named\PYGZus{}expressions}\PYG{p}{]} \PYGZsq{}]\PYGZsq{} \PYG{n+nf}{listcomp}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}[\PYGZsq{} \PYG{n+nf}{named\PYGZus{}expression} \PYGZti{} \PYG{n+nf}{for\PYGZus{}if\PYGZus{}clauses} \PYGZsq{}]\PYGZsq{} \PYG{n+nf}{tuple}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}(\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{star\PYGZus{}named\PYGZus{}expression} \PYGZsq{},\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{star\PYGZus{}named\PYGZus{}expressions}\PYG{p}{]} \PYG{p}{]} \PYGZsq{})\PYGZsq{} \PYG{n+nf}{group}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}(\PYGZsq{} \PYG{p}{(}\PYG{n+nf}{yield\PYGZus{}expr} \PYG{o}{|} \PYG{n+nf}{named\PYGZus{}expression}\PYG{p}{)} \PYGZsq{})\PYGZsq{} \PYG{n+nf}{genexp}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}(\PYGZsq{} \PYG{n+nf}{named\PYGZus{}expression} \PYGZti{} \PYG{n+nf}{for\PYGZus{}if\PYGZus{}clauses} \PYGZsq{})\PYGZsq{} \PYG{n+nf}{set}\PYG{p}{:} \PYGZsq{}\PYGZob{}\PYGZsq{} \PYG{n+nf}{star\PYGZus{}named\PYGZus{}expressions} \PYGZsq{}\PYGZcb{}\PYGZsq{} \PYG{n+nf}{setcomp}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}\PYGZob{}\PYGZsq{} \PYG{n+nf}{named\PYGZus{}expression} \PYGZti{} \PYG{n+nf}{for\PYGZus{}if\PYGZus{}clauses} \PYGZsq{}\PYGZcb{}\PYGZsq{} \PYG{n+nf}{dict}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}\PYGZob{}\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{double\PYGZus{}starred\PYGZus{}kvpairs}\PYG{p}{]} \PYGZsq{}\PYGZcb{}\PYGZsq{} \PYG{n+nf}{dictcomp}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}\PYGZob{}\PYGZsq{} \PYG{n+nf}{kvpair} \PYG{n+nf}{for\PYGZus{}if\PYGZus{}clauses} \PYGZsq{}\PYGZcb{}\PYGZsq{} \PYG{n+nf}{double\PYGZus{}starred\PYGZus{}kvpairs}\PYG{p}{:} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{double\PYGZus{}starred\PYGZus{}kvpair}\PYG{o}{+} \PYG{p}{[}\PYGZsq{},\PYGZsq{}\PYG{p}{]} \PYG{n+nf}{double\PYGZus{}starred\PYGZus{}kvpair}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}**\PYGZsq{} \PYG{n+nf}{bitwise\PYGZus{}or} \PYG{o}{|} \PYG{n+nf}{kvpair} \PYG{n+nf}{kvpair}\PYG{p}{:} \PYG{n+nf}{expression} \PYGZsq{}:\PYGZsq{} \PYG{n+nf}{expression} \PYG{n+nf}{for\PYGZus{}if\PYGZus{}clauses}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{for\PYGZus{}if\PYGZus{}clause}\PYG{o}{+} \PYG{n+nf}{for\PYGZus{}if\PYGZus{}clause}\PYG{p}{:} \PYG{o}{|} ASYNC \PYG{k}{\PYGZsq{}for\PYGZsq{}} \PYG{n+nf}{star\PYGZus{}targets} \PYG{k}{\PYGZsq{}in\PYGZsq{}} \PYGZti{} \PYG{n+nf}{disjunction} \PYG{p}{(}\PYG{k}{\PYGZsq{}if\PYGZsq{}} \PYG{n+nf}{disjunction} \PYG{p}{)}\PYG{o}{*} \PYG{o}{|} \PYG{k}{\PYGZsq{}for\PYGZsq{}} \PYG{n+nf}{star\PYGZus{}targets} \PYG{k}{\PYGZsq{}in\PYGZsq{}} \PYGZti{} \PYG{n+nf}{disjunction} \PYG{p}{(}\PYG{k}{\PYGZsq{}if\PYGZsq{}} \PYG{n+nf}{disjunction} \PYG{p}{)}\PYG{o}{*} \PYG{n+nf}{yield\PYGZus{}expr}\PYG{p}{:} \PYG{o}{|} \PYG{k}{\PYGZsq{}yield\PYGZsq{}} \PYG{k}{\PYGZsq{}from\PYGZsq{}} \PYG{n+nf}{expression} \PYG{o}{|} \PYG{k}{\PYGZsq{}yield\PYGZsq{}} \PYG{p}{[}\PYG{n+nf}{star\PYGZus{}expressions}\PYG{p}{]} \PYG{n+nf}{arguments}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{args} \PYG{p}{[}\PYGZsq{},\PYGZsq{}\PYG{p}{]} \PYGZam{}\PYGZsq{})\PYGZsq{} \PYG{n+nf}{args}\PYG{p}{:} \PYG{o}{|} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{p}{(}\PYG{n+nf}{starred\PYGZus{}expression} \PYG{o}{|} \PYG{n+nf}{named\PYGZus{}expression} !\PYGZsq{}=\PYGZsq{}\PYG{p}{)}\PYG{o}{+} \PYG{p}{[}\PYGZsq{},\PYGZsq{} \PYG{n+nf}{kwargs} \PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{kwargs} \PYG{n+nf}{kwargs}\PYG{p}{:} \PYG{o}{|} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{kwarg\PYGZus{}or\PYGZus{}starred}\PYG{o}{+} \PYGZsq{},\PYGZsq{} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{kwarg\PYGZus{}or\PYGZus{}double\PYGZus{}starred}\PYG{o}{+} \PYG{o}{|} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{kwarg\PYGZus{}or\PYGZus{}starred}\PYG{o}{+} \PYG{o}{|} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{kwarg\PYGZus{}or\PYGZus{}double\PYGZus{}starred}\PYG{o}{+} \PYG{n+nf}{starred\PYGZus{}expression}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}*\PYGZsq{} \PYG{n+nf}{expression} \PYG{n+nf}{kwarg\PYGZus{}or\PYGZus{}starred}\PYG{p}{:} \PYG{o}{|} NAME \PYGZsq{}=\PYGZsq{} \PYG{n+nf}{expression} \PYG{o}{|} \PYG{n+nf}{starred\PYGZus{}expression} \PYG{n+nf}{kwarg\PYGZus{}or\PYGZus{}double\PYGZus{}starred}\PYG{p}{:} \PYG{o}{|} NAME \PYGZsq{}=\PYGZsq{} \PYG{n+nf}{expression} \PYG{o}{|} \PYGZsq{}**\PYGZsq{} \PYG{n+nf}{expression} \PYG{c+cSingleline}{\PYGZsh{} NOTE: star\PYGZus{}targets may contain *bitwise\PYGZus{}or, targets may not.} \PYG{n+nf}{star\PYGZus{}targets}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{star\PYGZus{}target} !\PYGZsq{},\PYGZsq{} \PYG{o}{|} \PYG{n+nf}{star\PYGZus{}target} \PYG{p}{(}\PYGZsq{},\PYGZsq{} \PYG{n+nf}{star\PYGZus{}target} \PYG{p}{)}\PYG{o}{*} \PYG{p}{[}\PYGZsq{},\PYGZsq{}\PYG{p}{]} \PYG{n+nf}{star\PYGZus{}targets\PYGZus{}list\PYGZus{}seq}\PYG{p}{:} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{star\PYGZus{}target}\PYG{o}{+} \PYG{p}{[}\PYGZsq{},\PYGZsq{}\PYG{p}{]} \PYG{n+nf}{star\PYGZus{}targets\PYGZus{}tuple\PYGZus{}seq}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{star\PYGZus{}target} \PYG{p}{(}\PYGZsq{},\PYGZsq{} \PYG{n+nf}{star\PYGZus{}target} \PYG{p}{)}\PYG{o}{+} \PYG{p}{[}\PYGZsq{},\PYGZsq{}\PYG{p}{]} \PYG{o}{|} \PYG{n+nf}{star\PYGZus{}target} \PYGZsq{},\PYGZsq{} \PYG{n+nf}{star\PYGZus{}target}\PYG{p}{:} \PYG{o}{|} \PYGZsq{}*\PYGZsq{} \PYG{p}{(}!\PYGZsq{}*\PYGZsq{} \PYG{n+nf}{star\PYGZus{}target}\PYG{p}{)} \PYG{o}{|} \PYG{n+nf}{target\PYGZus{}with\PYGZus{}star\PYGZus{}atom} \PYG{n+nf}{target\PYGZus{}with\PYGZus{}star\PYGZus{}atom}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{t\PYGZus{}primary} \PYGZsq{}.\PYGZsq{} NAME !\PYG{n+nf}{t\PYGZus{}lookahead} \PYG{o}{|} \PYG{n+nf}{t\PYGZus{}primary} \PYGZsq{}[\PYGZsq{} \PYG{n+nf}{slices} \PYGZsq{}]\PYGZsq{} !\PYG{n+nf}{t\PYGZus{}lookahead} \PYG{o}{|} \PYG{n+nf}{star\PYGZus{}atom} \PYG{n+nf}{star\PYGZus{}atom}\PYG{p}{:} \PYG{o}{|} NAME \PYG{o}{|} \PYGZsq{}(\PYGZsq{} \PYG{n+nf}{target\PYGZus{}with\PYGZus{}star\PYGZus{}atom} \PYGZsq{})\PYGZsq{} \PYG{o}{|} \PYGZsq{}(\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{star\PYGZus{}targets\PYGZus{}tuple\PYGZus{}seq}\PYG{p}{]} \PYGZsq{})\PYGZsq{} \PYG{o}{|} \PYGZsq{}[\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{star\PYGZus{}targets\PYGZus{}list\PYGZus{}seq}\PYG{p}{]} \PYGZsq{}]\PYGZsq{} \PYG{n+nf}{single\PYGZus{}target}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{single\PYGZus{}subscript\PYGZus{}attribute\PYGZus{}target} \PYG{o}{|} NAME \PYG{o}{|} \PYGZsq{}(\PYGZsq{} \PYG{n+nf}{single\PYGZus{}target} \PYGZsq{})\PYGZsq{} \PYG{n+nf}{single\PYGZus{}subscript\PYGZus{}attribute\PYGZus{}target}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{t\PYGZus{}primary} \PYGZsq{}.\PYGZsq{} NAME !\PYG{n+nf}{t\PYGZus{}lookahead} \PYG{o}{|} \PYG{n+nf}{t\PYGZus{}primary} \PYGZsq{}[\PYGZsq{} \PYG{n+nf}{slices} \PYGZsq{}]\PYGZsq{} !\PYG{n+nf}{t\PYGZus{}lookahead} \PYG{n+nf}{del\PYGZus{}targets}\PYG{p}{:} \PYGZsq{},\PYGZsq{}\PYG{o}{.}\PYG{n+nf}{del\PYGZus{}target}\PYG{o}{+} \PYG{p}{[}\PYGZsq{},\PYGZsq{}\PYG{p}{]} \PYG{n+nf}{del\PYGZus{}target}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{t\PYGZus{}primary} \PYGZsq{}.\PYGZsq{} NAME !\PYG{n+nf}{t\PYGZus{}lookahead} \PYG{o}{|} \PYG{n+nf}{t\PYGZus{}primary} \PYGZsq{}[\PYGZsq{} \PYG{n+nf}{slices} \PYGZsq{}]\PYGZsq{} !\PYG{n+nf}{t\PYGZus{}lookahead} \PYG{o}{|} \PYG{n+nf}{del\PYGZus{}t\PYGZus{}atom} \PYG{n+nf}{del\PYGZus{}t\PYGZus{}atom}\PYG{p}{:} \PYG{o}{|} NAME \PYG{o}{|} \PYGZsq{}(\PYGZsq{} \PYG{n+nf}{del\PYGZus{}target} \PYGZsq{})\PYGZsq{} \PYG{o}{|} \PYGZsq{}(\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{del\PYGZus{}targets}\PYG{p}{]} \PYGZsq{})\PYGZsq{} \PYG{o}{|} \PYGZsq{}[\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{del\PYGZus{}targets}\PYG{p}{]} \PYGZsq{}]\PYGZsq{} \PYG{n+nf}{t\PYGZus{}primary}\PYG{p}{:} \PYG{o}{|} \PYG{n+nf}{t\PYGZus{}primary} \PYGZsq{}.\PYGZsq{} NAME \PYGZam{}\PYG{n+nf}{t\PYGZus{}lookahead} \PYG{o}{|} \PYG{n+nf}{t\PYGZus{}primary} \PYGZsq{}[\PYGZsq{} \PYG{n+nf}{slices} \PYGZsq{}]\PYGZsq{} \PYGZam{}\PYG{n+nf}{t\PYGZus{}lookahead} \PYG{o}{|} \PYG{n+nf}{t\PYGZus{}primary} \PYG{n+nf}{genexp} \PYGZam{}\PYG{n+nf}{t\PYGZus{}lookahead} \PYG{o}{|} \PYG{n+nf}{t\PYGZus{}primary} \PYGZsq{}(\PYGZsq{} \PYG{p}{[}\PYG{n+nf}{arguments}\PYG{p}{]} \PYGZsq{})\PYGZsq{} \PYGZam{}\PYG{n+nf}{t\PYGZus{}lookahead} \PYG{o}{|} \PYG{n+nf}{atom} \PYGZam{}\PYG{n+nf}{t\PYGZus{}lookahead} \PYG{n+nf}{t\PYGZus{}lookahead}\PYG{p}{:} \PYGZsq{}(\PYGZsq{} \PYG{o}{|} \PYGZsq{}[\PYGZsq{} \PYG{o}{|} \PYGZsq{}.\PYGZsq{} \end{sphinxVerbatim} \appendix \phantomsection\label{\detokenize{glossary::doc}} \chapter{用語集} \label{\detokenize{glossary:glossary}}\label{\detokenize{glossary:id1}}\begin{description} \item[{\sphinxcode{\sphinxupquote{>>>}}\index{>>>@\spxentry{>>>}|spxpagem}\phantomsection\label{\detokenize{glossary:term-0}}}] \leavevmode インタラクティブシェルにおけるデフォルトの Python プロンプトです。インタプリタでインタラクティブに実行されるコード例でよく出てきます。 \item[{\sphinxcode{\sphinxupquote{...}}\index{...@\spxentry{...}|spxpagem}\phantomsection\label{\detokenize{glossary:term-1}}}] \leavevmode 次のものが考えられます: \begin{itemize} \item {} インタラクティブシェルにおいて、インデントされたコードブロック、対応する左右の区切り文字の組 (丸括弧、角括弧、波括弧、三重引用符) の内側、デコレーターの後に、コードを入力する際に表示されるデフォルトの Python プロンプトです。 \item {} 組み込みの定数 \sphinxcode{\sphinxupquote{Ellipsis}} 。 \end{itemize} \item[{2to3\index{2to3@\spxentry{2to3}|spxpagem}\phantomsection\label{\detokenize{glossary:term-2to3}}}] \leavevmode Python 2.x のコードを Python 3.x のコードに変換するツールです。ソースコードを解析してその解析木を巡回 (traverse) することで検知できる、非互換性の大部分を処理します。 2to3 は標準ライブラリの \sphinxcode{\sphinxupquote{lib2to3}} として利用できます。単体のツールとして使えるスクリプトが \sphinxcode{\sphinxupquote{Tools/scripts/2to3}} として提供されています。 \DUrole{xref,std,std-ref}{2to3\sphinxhyphen{}reference} を参照してください。 \item[{abstract base class\index{abstract base class@\spxentry{abstract base class}|spxpagem}\phantomsection\label{\detokenize{glossary:term-abstract-base-class}}}] \leavevmode (抽象基底クラス) 抽象基底クラスは {\hyperref[\detokenize{glossary:term-duck-typing}]{\sphinxtermref{\DUrole{xref,std,std-term}{duck\sphinxhyphen{}typing}}}} を補完するもので、 \sphinxcode{\sphinxupquote{hasattr()}} などの別のテクニックでは不恰好であったり微妙に誤る (例えば {\hyperref[\detokenize{reference/datamodel:special-lookup}]{\sphinxcrossref{\DUrole{std,std-ref}{magic methods}}}} の場合) 場合にインターフェースを定義する方法を提供します。ABC は仮想 (virtual) サブクラスを導入します。これは親クラスから継承しませんが、それでも \sphinxcode{\sphinxupquote{isinstance()}} や \sphinxcode{\sphinxupquote{issubclass()}} に認識されます; \sphinxcode{\sphinxupquote{abc}} モジュールのドキュメントを参照してください。Python には、多くの組み込み ABC が同梱されています。その対象は、(\sphinxcode{\sphinxupquote{collections.abc}} モジュールで) データ構造、(\sphinxcode{\sphinxupquote{numbers}} モジュールで) 数、(\sphinxcode{\sphinxupquote{io}} モジュールで) ストリーム、(\sphinxcode{\sphinxupquote{importlib.abc}} モジュールで) インポートファインダ及びローダーです。 \sphinxcode{\sphinxupquote{abc}} モジュールを利用して独自の ABC を作成できます。 \item[{annotation\index{annotation@\spxentry{annotation}|spxpagem}\phantomsection\label{\detokenize{glossary:term-annotation}}}] \leavevmode (アノテーション) 変数、クラス属性、関数のパラメータや返り値に関係するラベルです。 慣例により {\hyperref[\detokenize{glossary:term-type-hint}]{\sphinxtermref{\DUrole{xref,std,std-term}{type hint}}}} として使われています。 ローカル変数のアノテーションは実行時にはアクセスできませんが、グローバル変数、クラス属性、関数のアノテーションはそれぞれモジュール、クラス、関数の \sphinxcode{\sphinxupquote{\_\_annotations\_\_}} 特殊属性に保持されています。 機能の説明がある {\hyperref[\detokenize{glossary:term-variable-annotation}]{\sphinxtermref{\DUrole{xref,std,std-term}{variable annotation}}}}, {\hyperref[\detokenize{glossary:term-function-annotation}]{\sphinxtermref{\DUrole{xref,std,std-term}{function annotation}}}}, \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 484@\spxentry{PEP 484}}\sphinxhref{https://www.python.org/dev/peps/pep-0484}{\sphinxstylestrong{PEP 484}}, \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 526@\spxentry{PEP 526}}\sphinxhref{https://www.python.org/dev/peps/pep-0526}{\sphinxstylestrong{PEP 526}} を参照してください。 \item[{argument\index{argument@\spxentry{argument}|spxpagem}\phantomsection\label{\detokenize{glossary:term-argument}}}] \leavevmode (実引数) 関数を呼び出す際に、 {\hyperref[\detokenize{glossary:term-function}]{\sphinxtermref{\DUrole{xref,std,std-term}{関数}}}} (または {\hyperref[\detokenize{glossary:term-method}]{\sphinxtermref{\DUrole{xref,std,std-term}{メソッド}}}}) に渡す値です。実引数には2種類あります: \begin{itemize} \item {} \sphinxstyleemphasis{キーワード引数}: 関数呼び出しの際に引数の前に識別子がついたもの (例: \sphinxcode{\sphinxupquote{name=}}) や、 \sphinxcode{\sphinxupquote{**}} に続けた辞書の中の値として渡された引数。例えば、次の \sphinxcode{\sphinxupquote{complex()}} の呼び出しでは、 \sphinxcode{\sphinxupquote{3}} と \sphinxcode{\sphinxupquote{5}} がキーワード引数です: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n+nb}{complex}\PYG{p}{(}\PYG{n}{real}\PYG{o}{=}\PYG{l+m+mi}{3}\PYG{p}{,} \PYG{n}{imag}\PYG{o}{=}\PYG{l+m+mi}{5}\PYG{p}{)} \PYG{n+nb}{complex}\PYG{p}{(}\PYG{o}{*}\PYG{o}{*}\PYG{p}{\PYGZob{}}\PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{real}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{:} \PYG{l+m+mi}{3}\PYG{p}{,} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{imag}\PYG{l+s+s1}{\PYGZsq{}}\PYG{p}{:} \PYG{l+m+mi}{5}\PYG{p}{\PYGZcb{}}\PYG{p}{)} \end{sphinxVerbatim} \item {} \sphinxstyleemphasis{位置引数}: キーワード引数以外の引数。位置引数は引数リストの先頭に書くことができ、また \sphinxcode{\sphinxupquote{*}} に続けた {\hyperref[\detokenize{glossary:term-iterable}]{\sphinxtermref{\DUrole{xref,std,std-term}{iterable}}}} の要素として渡すことができます。例えば、次の例では \sphinxcode{\sphinxupquote{3}} と \sphinxcode{\sphinxupquote{5}} は両方共位置引数です: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n+nb}{complex}\PYG{p}{(}\PYG{l+m+mi}{3}\PYG{p}{,} \PYG{l+m+mi}{5}\PYG{p}{)} \PYG{n+nb}{complex}\PYG{p}{(}\PYG{o}{*}\PYG{p}{(}\PYG{l+m+mi}{3}\PYG{p}{,} \PYG{l+m+mi}{5}\PYG{p}{)}\PYG{p}{)} \end{sphinxVerbatim} \end{itemize} 実引数は関数の実体において名前付きのローカル変数に割り当てられます。割り当てを行う規則については {\hyperref[\detokenize{reference/expressions:calls}]{\sphinxcrossref{\DUrole{std,std-ref}{呼び出し (call)}}}} を参照してください。シンタックスにおいて実引数を表すためにあらゆる式を使うことが出来ます。評価された値はローカル変数に割り当てられます。 {\hyperref[\detokenize{glossary:term-parameter}]{\sphinxtermref{\DUrole{xref,std,std-term}{仮引数}}}} 、FAQ の \DUrole{xref,std,std-ref}{実引数と仮引数の違いは何ですか?} 、\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 362@\spxentry{PEP 362}}\sphinxhref{https://www.python.org/dev/peps/pep-0362}{\sphinxstylestrong{PEP 362}} を参照してください。 \item[{asynchronous context manager\index{asynchronous context manager@\spxentry{asynchronous context manager}|spxpagem}\phantomsection\label{\detokenize{glossary:term-asynchronous-context-manager}}}] \leavevmode (非同期コンテキストマネージャ) {\hyperref[\detokenize{reference/datamodel:object.__aenter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_aenter\_\_()}}}}} と {\hyperref[\detokenize{reference/datamodel:object.__aexit__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_aexit\_\_()}}}}} メソッドを定義することで {\hyperref[\detokenize{reference/compound_stmts:async-with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async with}}}}} 文内の環境を管理するオブジェクトです。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 492@\spxentry{PEP 492}}\sphinxhref{https://www.python.org/dev/peps/pep-0492}{\sphinxstylestrong{PEP 492}} で導入されました。 \item[{asynchronous generator\index{asynchronous generator@\spxentry{asynchronous generator}|spxpagem}\phantomsection\label{\detokenize{glossary:term-asynchronous-generator}}}] \leavevmode (非同期ジェネレータ) {\hyperref[\detokenize{glossary:term-asynchronous-generator-iterator}]{\sphinxtermref{\DUrole{xref,std,std-term}{asynchronous generator iterator}}}} を返す関数です。 {\hyperref[\detokenize{reference/compound_stmts:async-def}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async def}}}}} で定義されたコルーチン関数に似ていますが、 {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} 式を持つ点で異なります。 {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} 式は {\hyperref[\detokenize{reference/compound_stmts:async-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async for}}}}} ループで使用できる値の並びを生成するのに使用されます。 通常は非同期ジェネレータ関数を指しますが、文脈によっては \sphinxstyleemphasis{非同期ジェネレータイテレータ} を指す場合があります。 意図された意味が明らかでない場合、 明瞭化のために完全な単語を使用します。 非同期ジェネレータ関数には、 {\hyperref[\detokenize{reference/compound_stmts:async-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async for}}}}} 文や {\hyperref[\detokenize{reference/compound_stmts:async-with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async with}}}}} 文だけでなく {\hyperref[\detokenize{reference/expressions:await}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{await}}}}} 式もあることがあります。 \item[{asynchronous generator iterator\index{asynchronous generator iterator@\spxentry{asynchronous generator iterator}|spxpagem}\phantomsection\label{\detokenize{glossary:term-asynchronous-generator-iterator}}}] \leavevmode (非同期ジェネレータイテレータ) {\hyperref[\detokenize{glossary:term-asynchronous-generator}]{\sphinxtermref{\DUrole{xref,std,std-term}{asynchronous generator}}}} 関数で生成されるオブジェクトです。 これは、 {\hyperref[\detokenize{reference/datamodel:object.__anext__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_anext\_\_()}}}}} メソッドを使って呼び出されたときに awaitable オブジェクトを返す {\hyperref[\detokenize{glossary:term-asynchronous-iterator}]{\sphinxtermref{\DUrole{xref,std,std-term}{asynchronous iterator}}}} です。 この awaitable オブジェクトは、次の {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} 式までの非同期ジェネレータ関数の本体を実行します。 {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} にくるたびに、その位置での実行状態 (ローカル変数と保留状態の try 文) 処理は一時停止されます。 {\hyperref[\detokenize{reference/datamodel:object.__anext__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_anext\_\_()}}}}} で返された他の awaitable によって \sphinxstyleemphasis{非同期ジェネレータイテレータ} が実際に再開されたとき、中断した箇所を取得します。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 492@\spxentry{PEP 492}}\sphinxhref{https://www.python.org/dev/peps/pep-0492}{\sphinxstylestrong{PEP 492}} および \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 525@\spxentry{PEP 525}}\sphinxhref{https://www.python.org/dev/peps/pep-0525}{\sphinxstylestrong{PEP 525}} を参照してください。 \item[{asynchronous iterable\index{asynchronous iterable@\spxentry{asynchronous iterable}|spxpagem}\phantomsection\label{\detokenize{glossary:term-asynchronous-iterable}}}] \leavevmode (非同期イテラブル) {\hyperref[\detokenize{reference/compound_stmts:async-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async for}}}}} 文の中で使用できるオブジェクトです。 自身の {\hyperref[\detokenize{reference/datamodel:object.__aiter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_aiter\_\_()}}}}} メソッドから {\hyperref[\detokenize{glossary:term-asynchronous-iterator}]{\sphinxtermref{\DUrole{xref,std,std-term}{asynchronous iterator}}}} を返さなければなりません。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 492@\spxentry{PEP 492}}\sphinxhref{https://www.python.org/dev/peps/pep-0492}{\sphinxstylestrong{PEP 492}} で導入されました。 \item[{asynchronous iterator\index{asynchronous iterator@\spxentry{asynchronous iterator}|spxpagem}\phantomsection\label{\detokenize{glossary:term-asynchronous-iterator}}}] \leavevmode (非同期イテレータ) {\hyperref[\detokenize{reference/datamodel:object.__aiter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_aiter\_\_()}}}}} と {\hyperref[\detokenize{reference/datamodel:object.__anext__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_anext\_\_()}}}}} メソッドを実装したオブジェクトです。 \sphinxcode{\sphinxupquote{\_\_anext\_\_}} は {\hyperref[\detokenize{glossary:term-awaitable}]{\sphinxtermref{\DUrole{xref,std,std-term}{awaitable}}}} オブジェクトを返さなければなりません。 {\hyperref[\detokenize{reference/compound_stmts:async-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async for}}}}} は \sphinxcode{\sphinxupquote{StopAsyncIteration}} 例外を送出するまで、非同期イテレータの {\hyperref[\detokenize{reference/datamodel:object.__anext__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_anext\_\_()}}}}} メソッドが返す awaitable を解決します。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 492@\spxentry{PEP 492}}\sphinxhref{https://www.python.org/dev/peps/pep-0492}{\sphinxstylestrong{PEP 492}} で導入されました。 \item[{attribute\index{attribute@\spxentry{attribute}|spxpagem}\phantomsection\label{\detokenize{glossary:term-attribute}}}] \leavevmode (属性) オブジェクトに関連付けられ、ドット表記式によって名前で参照される値です。例えば、オブジェクト \sphinxstyleemphasis{o} が属性 \sphinxstyleemphasis{a} を持っているとき、その属性は \sphinxstyleemphasis{o.a} で参照されます。 \item[{awaitable\index{awaitable@\spxentry{awaitable}|spxpagem}\phantomsection\label{\detokenize{glossary:term-awaitable}}}] \leavevmode (待機可能) {\hyperref[\detokenize{reference/expressions:await}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{await}}}}} 式で使用することが出来るオブジェクトです。 {\hyperref[\detokenize{glossary:term-coroutine}]{\sphinxtermref{\DUrole{xref,std,std-term}{coroutine}}}} か、 {\hyperref[\detokenize{reference/datamodel:object.__await__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_await\_\_()}}}}} メソッドがあるオブジェクトです。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 492@\spxentry{PEP 492}}\sphinxhref{https://www.python.org/dev/peps/pep-0492}{\sphinxstylestrong{PEP 492}} を参照してください。 \item[{BDFL\index{BDFL@\spxentry{BDFL}|spxpagem}\phantomsection\label{\detokenize{glossary:term-bdfl}}}] \leavevmode 慈悲深き終身独裁者 (Benevolent Dictator For Life) の略です。Python の作者、\sphinxhref{https://gvanrossum.github.io/}{Guido van Rossum} のことです。 \item[{binary file\index{binary file@\spxentry{binary file}|spxpagem}\phantomsection\label{\detokenize{glossary:term-binary-file}}}] \leavevmode (バイナリファイル) {\hyperref[\detokenize{glossary:term-bytes-like-object}]{\sphinxtermref{\DUrole{xref,std,std-term}{bytes\sphinxhyphen{}like オブジェクト}}}} の読み込みおよび書き込みができる {\hyperref[\detokenize{glossary:term-file-object}]{\sphinxtermref{\DUrole{xref,std,std-term}{ファイルオブジェクト}}}} です。 バイナリファイルの例は、バイナリモード (\sphinxcode{\sphinxupquote{'rb'}}, \sphinxcode{\sphinxupquote{'wb'}} or \sphinxcode{\sphinxupquote{'rb+'}}) で開かれたファイル、 \sphinxcode{\sphinxupquote{sys.stdin.buffer}} 、 \sphinxcode{\sphinxupquote{sys.stdout.buffer}} 、 \sphinxcode{\sphinxupquote{io.BytesIO}} や \sphinxcode{\sphinxupquote{gzip.GzipFile}}. のインスタンスです。 \sphinxcode{\sphinxupquote{str}} オブジェクトの読み書きができるファイルオブジェクトについては、 {\hyperref[\detokenize{glossary:term-text-file}]{\sphinxtermref{\DUrole{xref,std,std-term}{text file}}}} も参照してください。 \item[{bytes\sphinxhyphen{}like object\index{bytes\sphinxhyphen{}like object@\spxentry{bytes\sphinxhyphen{}like object}|spxpagem}\phantomsection\label{\detokenize{glossary:term-bytes-like-object}}}] \leavevmode \DUrole{xref,std,std-ref}{bufferobjects} をサポートしていて、 C 言語の意味で \DUrole{xref,std,std-term}{連続した contiguous} バッファーを提供可能なオブジェクト。 \sphinxcode{\sphinxupquote{bytes}}, \sphinxcode{\sphinxupquote{bytearray}}, \sphinxcode{\sphinxupquote{array.array}} や、多くの一般的な \sphinxcode{\sphinxupquote{memoryview}} オブジェクトがこれに当たります。 bytes\sphinxhyphen{}like オブジェクトは、データ圧縮、バイナリファイルへの保存、ソケットを経由した送信など、バイナリデータを要求するいろいろな操作に利用することができます。 幾つかの操作ではバイナリデータを変更する必要があります。 その操作のドキュメントではよく "読み書き可能な bytes\sphinxhyphen{}like オブジェクト" に言及しています。 変更可能なバッファーオブジェクトには、 \sphinxcode{\sphinxupquote{bytearray}} と \sphinxcode{\sphinxupquote{bytearray}} の \sphinxcode{\sphinxupquote{memoryview}} などが含まれます。 また、他の幾つかの操作では不変なオブジェクト内のバイナリデータ ("読み出し専用の bytes\sphinxhyphen{}like オブジェクト") を必要します。それには \sphinxcode{\sphinxupquote{bytes}} と \sphinxcode{\sphinxupquote{bytes}} の \sphinxcode{\sphinxupquote{memoryview}} オブジェクトが含まれます。 \item[{bytecode\index{bytecode@\spxentry{bytecode}|spxpagem}\phantomsection\label{\detokenize{glossary:term-bytecode}}}] \leavevmode (バイトコード) Python のソースコードは、 Python プログラムの CPython インタプリタの内部表現であるバイトコードへとコンパイルされます。 バイトコードは \sphinxcode{\sphinxupquote{.pyc}} ファイルにキャッシュされ、同じファイルが二度目に実行されるときはより高速になります (ソースコードからバイトコードへの再度のコンパイルは回避されます)。 この "中間言語 (intermediate language)" は、各々のバイトコードに対応する機械語を実行する {\hyperref[\detokenize{glossary:term-virtual-machine}]{\sphinxtermref{\DUrole{xref,std,std-term}{仮想マシン}}}} で動作するといえます。 重要な注意として、バイトコードは異なる Python 仮想マシン間で動作することや、Python リリース間で安定であることは期待されていません。 バイトコードの命令一覧は \DUrole{xref,std,std-ref}{dis モジュール} にあります。 \item[{callback\index{callback@\spxentry{callback}|spxpagem}\phantomsection\label{\detokenize{glossary:term-callback}}}] \leavevmode (コールバック) 将来のある時点で実行されるために引数として渡される関数 \item[{class\index{class@\spxentry{class}|spxpagem}\phantomsection\label{\detokenize{glossary:term-class}}}] \leavevmode (クラス) ユーザー定義オブジェクトを作成するためのテンプレートです。クラス定義は普通、そのクラスのインスタンス上の操作をするメソッドの定義を含みます。 \item[{class variable\index{class variable@\spxentry{class variable}|spxpagem}\phantomsection\label{\detokenize{glossary:term-class-variable}}}] \leavevmode (クラス変数) クラス上に定義され、クラスレベルで (つまり、クラスのインスタンス上ではなしに) 変更されることを目的としている変数です。 \item[{coercion\index{coercion@\spxentry{coercion}|spxpagem}\phantomsection\label{\detokenize{glossary:term-coercion}}}] \leavevmode (型強制) 同じ型の 2 引数を伴う演算の最中に行われる、ある型のインスタンスの別の型への暗黙の変換です。 例えば、 \sphinxcode{\sphinxupquote{int(3.15)}} は浮動小数点数を整数 \sphinxcode{\sphinxupquote{3}} に変換します。しかし \sphinxcode{\sphinxupquote{3+4.5}} では、各引数は型が異なり(一つは整数、一つは浮動小数点数)、加算をする前に同じ型に変換できなければ \sphinxcode{\sphinxupquote{TypeError}} 例外が投げられます。 型強制がなかったら、すべての引数は、たとえ互換な型であっても、単に \sphinxcode{\sphinxupquote{3+4.5}} ではなく \sphinxcode{\sphinxupquote{float(3)+4.5}} というように、プログラマーが同じ型に正規化しなければいけません。 \item[{complex number\index{complex number@\spxentry{complex number}|spxpagem}\phantomsection\label{\detokenize{glossary:term-complex-number}}}] \leavevmode (複素数) よく知られている実数系を拡張したもので、すべての数は実部と虚部の和として表されます。虚数は虚数単位 (\sphinxcode{\sphinxupquote{\sphinxhyphen{}1}} の平方根) に実数を掛けたもので、一般に数学では \sphinxcode{\sphinxupquote{i}} と書かれ、工学では \sphinxcode{\sphinxupquote{j}} と書かれます。Python は複素数に組み込みで対応し、後者の表記を取っています。虚部は末尾に \sphinxcode{\sphinxupquote{j}} をつけて書きます。例えば \sphinxcode{\sphinxupquote{3+1j}} です。 \sphinxcode{\sphinxupquote{math}} モジュールの複素数版を利用するには、 \sphinxcode{\sphinxupquote{cmath}} を使います。複素数の使用はかなり高度な数学の機能です。必要性を感じなければ、ほぼ間違いなく無視してしまってよいでしょう。 \item[{context manager\index{context manager@\spxentry{context manager}|spxpagem}\phantomsection\label{\detokenize{glossary:term-context-manager}}}] \leavevmode (コンテキストマネージャ) {\hyperref[\detokenize{reference/datamodel:object.__enter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_enter\_\_()}}}}} と {\hyperref[\detokenize{reference/datamodel:object.__exit__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_exit\_\_()}}}}} メソッドを定義することで {\hyperref[\detokenize{reference/compound_stmts:with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{with}}}}} 文内の環境を管理するオブジェクトです。\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 343@\spxentry{PEP 343}}\sphinxhref{https://www.python.org/dev/peps/pep-0343}{\sphinxstylestrong{PEP 343}} を参照してください。 \item[{context variable\index{context variable@\spxentry{context variable}|spxpagem}\phantomsection\label{\detokenize{glossary:term-context-variable}}}] \leavevmode (コンテキスト変数) コンテキストに依存して異なる値を持つ変数。 これは、ある変数の値が各々の実行スレッドで異なり得るスレッドローカルストレージに似ています。 しかしコンテキスト変数では、 1 つの実行スレッドにいくつかのコンテキストがあり得、コンテキスト変数の主な用途は並列な非同期タスクの変数の追跡です。 \sphinxcode{\sphinxupquote{contextvars}} を参照してください。 \item[{contiguous\index{contiguous@\spxentry{contiguous}|spxpagem}\phantomsection\label{\detokenize{glossary:term-contiguous}}}] \leavevmode \index{C\sphinxhyphen{}contiguous@\spxentry{C\sphinxhyphen{}contiguous}}\index{Fortran contiguous@\spxentry{Fortran contiguous}}\ignorespaces (隣接、連続) バッファが厳密に \sphinxstyleemphasis{C\sphinxhyphen{}連続} または \sphinxstyleemphasis{Fortran 連続} である場合に、そのバッファは連続しているとみなせます。 ゼロ次元バッファは C 連続であり Fortran 連続です。 一次元の配列では、その要素は必ずメモリ上で隣接するように配置され、添字がゼロから始まり増えていく順序で並びます。 多次元の C\sphinxhyphen{}連続な配列では、メモリアドレス順に要素を巡る際には最後の添え字が最初に変わるのに対し、 Fortran 連続な配列では最初の添え字が最初に動きます。 \item[{coroutine\index{coroutine@\spxentry{coroutine}|spxpagem}\phantomsection\label{\detokenize{glossary:term-coroutine}}}] \leavevmode (コルーチン) コルーチンはサブルーチンのより一般的な形式です。 サブルーチンには決められた地点から入り、別の決められた地点から出ます。 コルーチンには多くの様々な地点から入る、出る、再開することができます。 コルーチンは {\hyperref[\detokenize{reference/compound_stmts:async-def}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async def}}}}} 文で実装できます。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 492@\spxentry{PEP 492}}\sphinxhref{https://www.python.org/dev/peps/pep-0492}{\sphinxstylestrong{PEP 492}} を参照してください。 \item[{coroutine function\index{coroutine function@\spxentry{coroutine function}|spxpagem}\phantomsection\label{\detokenize{glossary:term-coroutine-function}}}] \leavevmode (コルーチン関数) {\hyperref[\detokenize{glossary:term-coroutine}]{\sphinxtermref{\DUrole{xref,std,std-term}{coroutine}}}} オブジェクトを返す関数です。 コルーチン関数は {\hyperref[\detokenize{reference/compound_stmts:async-def}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async def}}}}} 文で実装され、{\hyperref[\detokenize{reference/expressions:await}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{await}}}}}、{\hyperref[\detokenize{reference/compound_stmts:async-for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async for}}}}}、 および {\hyperref[\detokenize{reference/compound_stmts:async-with}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{async with}}}}} キーワードを持つことが出来ます。 これらは \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 492@\spxentry{PEP 492}}\sphinxhref{https://www.python.org/dev/peps/pep-0492}{\sphinxstylestrong{PEP 492}} で導入されました。 \item[{CPython\index{CPython@\spxentry{CPython}|spxpagem}\phantomsection\label{\detokenize{glossary:term-cpython}}}] \leavevmode \sphinxhref{https://www.python.org}{python.org} で配布されている、Python プログラミング言語の標準的な実装です。"CPython" という単語は、この実装を Jython や IronPython といった他の実装と区別する必要が有る場合に利用されます。 \item[{decorator\index{decorator@\spxentry{decorator}|spxpagem}\phantomsection\label{\detokenize{glossary:term-decorator}}}] \leavevmode (デコレータ) 別の関数を返す関数で、通常、 \sphinxcode{\sphinxupquote{@wrapper}} 構文で関数変換として適用されます。デコレータの一般的な利用例は、 \sphinxcode{\sphinxupquote{classmethod()}} と \sphinxcode{\sphinxupquote{staticmethod()}} です。 デコレータの文法はシンタックスシュガーです。次の2つの関数定義は意味的に同じものです: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{def} \PYG{n+nf}{f}\PYG{p}{(}\PYG{n}{arg}\PYG{p}{)}\PYG{p}{:} \PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \PYG{n}{f} \PYG{o}{=} \PYG{n+nb}{staticmethod}\PYG{p}{(}\PYG{n}{f}\PYG{p}{)} \PYG{n+nd}{@staticmethod} \PYG{k}{def} \PYG{n+nf}{f}\PYG{p}{(}\PYG{n}{arg}\PYG{p}{)}\PYG{p}{:} \PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \end{sphinxVerbatim} 同じ概念がクラスにも存在しますが、あまり使われません。デコレータについて詳しくは、 {\hyperref[\detokenize{reference/compound_stmts:function}]{\sphinxcrossref{\DUrole{std,std-ref}{関数定義}}}} および {\hyperref[\detokenize{reference/compound_stmts:class}]{\sphinxcrossref{\DUrole{std,std-ref}{クラス定義}}}} のドキュメントを参照してください。 \item[{descriptor\index{descriptor@\spxentry{descriptor}|spxpagem}\phantomsection\label{\detokenize{glossary:term-descriptor}}}] \leavevmode (デスクリプタ) メソッド {\hyperref[\detokenize{reference/datamodel:object.__get__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_get\_\_()}}}}}, {\hyperref[\detokenize{reference/datamodel:object.__set__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_set\_\_()}}}}}, あるいは {\hyperref[\detokenize{reference/datamodel:object.__delete__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_delete\_\_()}}}}} を定義しているオブジェクトです。あるクラス属性がデスクリプタであるとき、属性探索によって、束縛されている特別な動作が呼び出されます。通常、get,set,deleteのために \sphinxstyleemphasis{a.b} と書くと、 \sphinxstyleemphasis{a} のクラス辞書内でオブジェクト \sphinxstyleemphasis{b} を検索しますが、 \sphinxstyleemphasis{b} がデスクリプタであればそれぞれのデスクリプタメソッドが呼び出されます。デスクリプタの理解は、 Python を深く理解する上で鍵となります。というのは、デスクリプタこそが、関数、メソッド、プロパティ、クラスメソッド、静的メソッド、そしてスーパクラスの参照といった多くの機能の基盤だからです。 デスクリプタのメソッドに関しての詳細は、 {\hyperref[\detokenize{reference/datamodel:descriptors}]{\sphinxcrossref{\DUrole{std,std-ref}{デスクリプタ (descriptor) の実装}}}} や \DUrole{xref,std,std-ref}{Descriptor How To Guide} を参照してください。 \item[{dictionary\index{dictionary@\spxentry{dictionary}|spxpagem}\phantomsection\label{\detokenize{glossary:term-dictionary}}}] \leavevmode (辞書) 任意のキーを値に対応付ける連想配列です。 {\hyperref[\detokenize{reference/datamodel:object.__hash__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_hash\_\_()}}}}} メソッドと {\hyperref[\detokenize{reference/datamodel:object.__eq__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_eq\_\_()}}}}} メソッドを実装した任意のオブジェクトをキーにできます。 Perl ではハッシュ (hash) と呼ばれています。 \item[{dictionary comprehension\index{dictionary comprehension@\spxentry{dictionary comprehension}|spxpagem}\phantomsection\label{\detokenize{glossary:term-dictionary-comprehension}}}] \leavevmode (辞書内包表記) iterable 内の全てあるいは一部の要素を処理して、その結果からなる辞書を返すコンパクトな書き方です。 \sphinxcode{\sphinxupquote{results = \{n: n ** 2 for n in range(10)\}}} とすると、キー \sphinxcode{\sphinxupquote{n}} を値 \sphinxcode{\sphinxupquote{n ** 2}} に対応付ける辞書を生成します。 {\hyperref[\detokenize{reference/expressions:comprehensions}]{\sphinxcrossref{\DUrole{std,std-ref}{リスト、集合、辞書の表示}}}} を参照してください。 \item[{dictionary view\index{dictionary view@\spxentry{dictionary view}|spxpagem}\phantomsection\label{\detokenize{glossary:term-dictionary-view}}}] \leavevmode (辞書ビュー) \sphinxcode{\sphinxupquote{dict.keys()}}、\sphinxcode{\sphinxupquote{dict.values()}}、\sphinxcode{\sphinxupquote{dict.items()}} が返すオブジェクトです。 辞書の項目の動的なビューを提供します。 すなわち、辞書が変更されるとビューはそれを反映します。 辞書ビューを強制的に完全なリストにするには \sphinxcode{\sphinxupquote{list(dictview)}} を使用してください。 \DUrole{xref,std,std-ref}{dict\sphinxhyphen{}views} を参照してください。 \item[{docstring\index{docstring@\spxentry{docstring}|spxpagem}\phantomsection\label{\detokenize{glossary:term-docstring}}}] \leavevmode クラス、関数、モジュールの最初の式である文字列リテラルです。そのスイートの実行時には無視されますが、コンパイラによって識別され、そのクラス、関数、モジュールの \sphinxcode{\sphinxupquote{\_\_doc\_\_}} 属性として保存されます。イントロスペクションできる(訳注: 属性として参照できる)ので、オブジェクトのドキュメントを書く標準的な場所です。 \item[{duck\sphinxhyphen{}typing\index{duck\sphinxhyphen{}typing@\spxentry{duck\sphinxhyphen{}typing}|spxpagem}\phantomsection\label{\detokenize{glossary:term-duck-typing}}}] \leavevmode あるオブジェクトが正しいインターフェースを持っているかを決定するのにオブジェクトの型を見ないプログラミングスタイルです。代わりに、単純にオブジェクトのメソッドや属性が呼ばれたり使われたりします。(「アヒルのように見えて、アヒルのように鳴けば、それはアヒルである。」)インターフェースを型より重視することで、上手くデザインされたコードは、ポリモーフィックな代替を許して柔軟性を向上させます。ダックタイピングは \sphinxcode{\sphinxupquote{type()}} や \sphinxcode{\sphinxupquote{isinstance()}} による判定を避けます。 (ただし、ダックタイピングを {\hyperref[\detokenize{glossary:term-abstract-base-class}]{\sphinxtermref{\DUrole{xref,std,std-term}{抽象基底クラス}}}} で補完することもできます。) その代わり、典型的に \sphinxcode{\sphinxupquote{hasattr()}} 判定や {\hyperref[\detokenize{glossary:term-eafp}]{\sphinxtermref{\DUrole{xref,std,std-term}{EAFP}}}} プログラミングを利用します。 \item[{EAFP\index{EAFP@\spxentry{EAFP}|spxpagem}\phantomsection\label{\detokenize{glossary:term-eafp}}}] \leavevmode 「認可をとるより許しを請う方が容易 (easier to ask for forgiveness than permission、マーフィーの法則)」の略です。この Python で広く使われているコーディングスタイルでは、通常は有効なキーや属性が存在するものと仮定し、その仮定が誤っていた場合に例外を捕捉します。この簡潔で手早く書けるコーディングスタイルには、 {\hyperref[\detokenize{reference/compound_stmts:try}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{try}}}}} 文および {\hyperref[\detokenize{reference/compound_stmts:except}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{except}}}}} 文がたくさんあるのが特徴です。このテクニックは、C のような言語でよく使われている {\hyperref[\detokenize{glossary:term-lbyl}]{\sphinxtermref{\DUrole{xref,std,std-term}{LBYL}}}} スタイルと対照的なものです。 \item[{expression\index{expression@\spxentry{expression}|spxpagem}\phantomsection\label{\detokenize{glossary:term-expression}}}] \leavevmode (式) 何かの値と評価される、一まとまりの構文 (a piece of syntax) です。言い換えると、式とはリテラル、名前、属性アクセス、演算子や関数呼び出しなど、値を返す式の要素の積み重ねです。他の多くの言語と違い、Python では言語の全ての構成要素が式というわけではありません。 {\hyperref[\detokenize{reference/compound_stmts:while}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{while}}}}} のように、式としては使えない {\hyperref[\detokenize{glossary:term-statement}]{\sphinxtermref{\DUrole{xref,std,std-term}{文}}}} もあります。代入も式ではなく文です。 \item[{extension module\index{extension module@\spxentry{extension module}|spxpagem}\phantomsection\label{\detokenize{glossary:term-extension-module}}}] \leavevmode (拡張モジュール) C や C++ で書かれたモジュールで、Python の C API を利用して Python コアやユーザーコードとやりとりします。 \item[{f\sphinxhyphen{}string\index{f\sphinxhyphen{}string@\spxentry{f\sphinxhyphen{}string}|spxpagem}\phantomsection\label{\detokenize{glossary:term-f-string}}}] \leavevmode \sphinxcode{\sphinxupquote{'f'}} や \sphinxcode{\sphinxupquote{'F'}} が先頭に付いた文字列リテラルは "f\sphinxhyphen{}string" と呼ばれ、これは {\hyperref[\detokenize{reference/lexical_analysis:f-strings}]{\sphinxcrossref{\DUrole{std,std-ref}{フォーマット済み文字列リテラル}}}} の短縮形の名称です。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 498@\spxentry{PEP 498}}\sphinxhref{https://www.python.org/dev/peps/pep-0498}{\sphinxstylestrong{PEP 498}} も参照してください。 \item[{file object\index{file object@\spxentry{file object}|spxpagem}\phantomsection\label{\detokenize{glossary:term-file-object}}}] \leavevmode (ファイルオブジェクト) 下位のリソースへのファイル指向 API (\sphinxcode{\sphinxupquote{read()}} や \sphinxcode{\sphinxupquote{write()}} メソッドを持つもの) を公開しているオブジェクトです。ファイルオブジェクトは、作成された手段によって、実際のディスク上のファイルや、その他のタイプのストレージや通信デバイス (例えば、標準入出力、インメモリバッファ、ソケット、パイプ、等) へのアクセスを媒介できます。ファイルオブジェクトは \sphinxstyleemphasis{file\sphinxhyphen{}like objects} や \sphinxstyleemphasis{streams} とも呼ばれます。 ファイルオブジェクトには実際には 3 種類あります: 生の {\hyperref[\detokenize{glossary:term-binary-file}]{\sphinxtermref{\DUrole{xref,std,std-term}{バイナリーファイル}}}}、バッファされた {\hyperref[\detokenize{glossary:term-binary-file}]{\sphinxtermref{\DUrole{xref,std,std-term}{バイナリーファイル}}}}、そして {\hyperref[\detokenize{glossary:term-text-file}]{\sphinxtermref{\DUrole{xref,std,std-term}{テキストファイル}}}} です。インターフェイスは \sphinxcode{\sphinxupquote{io}} モジュールで定義されています。ファイルオブジェクトを作る標準的な方法は \sphinxcode{\sphinxupquote{open()}} 関数を使うことです。 \item[{file\sphinxhyphen{}like object\index{file\sphinxhyphen{}like object@\spxentry{file\sphinxhyphen{}like object}|spxpagem}\phantomsection\label{\detokenize{glossary:term-file-like-object}}}] \leavevmode {\hyperref[\detokenize{glossary:term-file-object}]{\sphinxtermref{\DUrole{xref,std,std-term}{file object}}}} と同義です。 \item[{finder\index{finder@\spxentry{finder}|spxpagem}\phantomsection\label{\detokenize{glossary:term-finder}}}] \leavevmode (ファインダ) インポートされているモジュールの {\hyperref[\detokenize{glossary:term-loader}]{\sphinxtermref{\DUrole{xref,std,std-term}{loader}}}} の発見を試行するオブジェクトです。 Python 3.3 以降では 2 種類のファインダがあります。 \sphinxcode{\sphinxupquote{sys.meta\_path}} で使用される {\hyperref[\detokenize{glossary:term-meta-path-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{meta path finder}}}} と、 \sphinxcode{\sphinxupquote{sys.path\_hooks}} で使用される {\hyperref[\detokenize{glossary:term-path-entry-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{path entry finder}}}} です。 詳細については \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 302@\spxentry{PEP 302}}\sphinxhref{https://www.python.org/dev/peps/pep-0302}{\sphinxstylestrong{PEP 302}}、\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 420@\spxentry{PEP 420}}\sphinxhref{https://www.python.org/dev/peps/pep-0420}{\sphinxstylestrong{PEP 420}} および \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 451@\spxentry{PEP 451}}\sphinxhref{https://www.python.org/dev/peps/pep-0451}{\sphinxstylestrong{PEP 451}} を参照してください。 \item[{floor division\index{floor division@\spxentry{floor division}|spxpagem}\phantomsection\label{\detokenize{glossary:term-floor-division}}}] \leavevmode (切り捨て除算) 一番近い整数に切り捨てる数学的除算。 切り捨て除算演算子は \sphinxcode{\sphinxupquote{//}} です。 例えば、 \sphinxcode{\sphinxupquote{11 // 4}} は \sphinxcode{\sphinxupquote{2}} になり、それとは対称に浮動小数点数の真の除算では \sphinxcode{\sphinxupquote{2.75}} が 返ってきます。 \sphinxcode{\sphinxupquote{(\sphinxhyphen{}11) // 4}} は \sphinxcode{\sphinxupquote{\sphinxhyphen{}2.75}} を \sphinxstyleemphasis{小さい方に} 丸める (訳注: 負の無限大への丸めを行う) ので \sphinxcode{\sphinxupquote{\sphinxhyphen{}3}} になることに注意してください。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 238@\spxentry{PEP 238}}\sphinxhref{https://www.python.org/dev/peps/pep-0238}{\sphinxstylestrong{PEP 238}} を参照してください。 \item[{function\index{function@\spxentry{function}|spxpagem}\phantomsection\label{\detokenize{glossary:term-function}}}] \leavevmode (関数) 呼び出し側に値を返す一連の文のことです。関数には0以上の {\hyperref[\detokenize{glossary:term-argument}]{\sphinxtermref{\DUrole{xref,std,std-term}{実引数}}}} を渡すことが出来ます。実体の実行時に引数を使用することが出来ます。 {\hyperref[\detokenize{glossary:term-parameter}]{\sphinxtermref{\DUrole{xref,std,std-term}{仮引数}}}}、{\hyperref[\detokenize{glossary:term-method}]{\sphinxtermref{\DUrole{xref,std,std-term}{メソッド}}}}、{\hyperref[\detokenize{reference/compound_stmts:function}]{\sphinxcrossref{\DUrole{std,std-ref}{関数定義}}}} を参照してください。 \item[{function annotation\index{function annotation@\spxentry{function annotation}|spxpagem}\phantomsection\label{\detokenize{glossary:term-function-annotation}}}] \leavevmode (関数アノテーション) 関数のパラメータや返り値の {\hyperref[\detokenize{glossary:term-annotation}]{\sphinxtermref{\DUrole{xref,std,std-term}{annotation}}}} です。 関数アノテーションは、通常は {\hyperref[\detokenize{glossary:term-type-hint}]{\sphinxtermref{\DUrole{xref,std,std-term}{型ヒント}}}} のために使われます: 例えば、この関数は 2 つの \sphinxcode{\sphinxupquote{int}} 型の引数を取ると期待され、また \sphinxcode{\sphinxupquote{int}} 型の返り値を持つと期待されています。 \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{def} \PYG{n+nf}{sum\PYGZus{}two\PYGZus{}numbers}\PYG{p}{(}\PYG{n}{a}\PYG{p}{:} \PYG{n+nb}{int}\PYG{p}{,} \PYG{n}{b}\PYG{p}{:} \PYG{n+nb}{int}\PYG{p}{)} \PYG{o}{\PYGZhy{}}\PYG{o}{\PYGZgt{}} \PYG{n+nb}{int}\PYG{p}{:} \PYG{k}{return} \PYG{n}{a} \PYG{o}{+} \PYG{n}{b} \end{sphinxVerbatim} 関数アノテーションの文法は {\hyperref[\detokenize{reference/compound_stmts:function}]{\sphinxcrossref{\DUrole{std,std-ref}{関数定義}}}} の節で解説されています。 機能の説明がある {\hyperref[\detokenize{glossary:term-variable-annotation}]{\sphinxtermref{\DUrole{xref,std,std-term}{variable annotation}}}} と \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 484@\spxentry{PEP 484}}\sphinxhref{https://www.python.org/dev/peps/pep-0484}{\sphinxstylestrong{PEP 484}} を参照してください。 \item[{\_\_future\_\_\index{\_\_future\_\_@\spxentry{\_\_future\_\_}|spxpagem}\phantomsection\label{\detokenize{glossary:term-future}}}] \leavevmode A {\hyperref[\detokenize{reference/simple_stmts:future}]{\sphinxcrossref{\DUrole{std,std-ref}{future statement}}}}, \sphinxcode{\sphinxupquote{from \_\_future\_\_ import }}, directs the compiler to compile the current module using syntax or semantics that will become standard in a future release of Python. The \sphinxcode{\sphinxupquote{\_\_future\_\_}} module documents the possible values of \sphinxstyleemphasis{feature}. By importing this module and evaluating its variables, you can see when a new feature was first added to the language and when it will (or did) become the default: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k+kn}{import} \PYG{n+nn}{\PYGZus{}\PYGZus{}future\PYGZus{}\PYGZus{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{\PYGZus{}\PYGZus{}future\PYGZus{}\PYGZus{}}\PYG{o}{.}\PYG{n}{division} \PYG{g+go}{\PYGZus{}Feature((2, 2, 0, \PYGZsq{}alpha\PYGZsq{}, 2), (3, 0, 0, \PYGZsq{}alpha\PYGZsq{}, 0), 8192)} \end{sphinxVerbatim} \item[{garbage collection\index{garbage collection@\spxentry{garbage collection}|spxpagem}\phantomsection\label{\detokenize{glossary:term-garbage-collection}}}] \leavevmode (ガベージコレクション) これ以降使われることのないメモリを解放する処理です。 Pythonは、参照カウントと、循環参照を検出し破壊する循環ガベージコレクタを使ってガベージコレクションを行います。 ガベージコレクタは \sphinxcode{\sphinxupquote{gc}} モジュールを使って操作できます。 \index{generator@\spxentry{generator}}\ignorespaces \item[{generator\index{generator@\spxentry{generator}|spxpagem}\phantomsection\label{\detokenize{glossary:term-generator}}}] \leavevmode (ジェネレータ) {\hyperref[\detokenize{glossary:term-generator-iterator}]{\sphinxtermref{\DUrole{xref,std,std-term}{generator iterator}}}} を返す関数です。 通常の関数に似ていますが、 {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} 式を持つ点で異なります。 {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} 式は、 for ループで使用できたり、\sphinxcode{\sphinxupquote{next()}} 関数で値を 1 つずつ取り出したりできる、値の並びを生成するのに使用されます。 通常はジェネレータ関数を指しますが、文脈によっては \sphinxstyleemphasis{ジェネレータイテレータ} を指す場合があります。 意図された意味が明らかでない場合、 明瞭化のために完全な単語を使用します。 \item[{generator iterator\index{generator iterator@\spxentry{generator iterator}|spxpagem}\phantomsection\label{\detokenize{glossary:term-generator-iterator}}}] \leavevmode (ジェネレータイテレータ) {\hyperref[\detokenize{glossary:term-generator}]{\sphinxtermref{\DUrole{xref,std,std-term}{generator}}}} 関数で生成されるオブジェクトです。 {\hyperref[\detokenize{reference/simple_stmts:yield}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{yield}}}}} のたびに局所実行状態 (局所変数や未処理の try 文などを含む) を記憶して、処理は一時的に中断されます。 \sphinxstyleemphasis{ジェネレータイテレータ} が再開されると、中断した位置を取得します (通常の関数が実行のたびに新しい状態から開始するのと対照的です)。 \index{generator expression@\spxentry{generator expression}}\ignorespaces \item[{generator expression\index{generator expression@\spxentry{generator expression}|spxpagem}\phantomsection\label{\detokenize{glossary:term-generator-expression}}}] \leavevmode (ジェネレータ式) イテレータを返す式です。 普通の式に、ループ変数を定義する \sphinxcode{\sphinxupquote{for}} 節、範囲、そして省略可能な \sphinxcode{\sphinxupquote{if}} 節がつづいているように見えます。 こうして構成された式は、外側の関数に向けて値を生成します: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{sum}\PYG{p}{(}\PYG{n}{i}\PYG{o}{*}\PYG{n}{i} \PYG{k}{for} \PYG{n}{i} \PYG{o+ow}{in} \PYG{n+nb}{range}\PYG{p}{(}\PYG{l+m+mi}{10}\PYG{p}{)}\PYG{p}{)} \PYG{c+c1}{\PYGZsh{} sum of squares 0, 1, 4, ... 81} \PYG{g+go}{285} \end{sphinxVerbatim} \item[{generic function\index{generic function@\spxentry{generic function}|spxpagem}\phantomsection\label{\detokenize{glossary:term-generic-function}}}] \leavevmode (ジェネリック関数) 異なる型に対し同じ操作をする関数群から構成される関数です。呼び出し時にどの実装を用いるかはディスパッチアルゴリズムにより決定されます。 {\hyperref[\detokenize{glossary:term-single-dispatch}]{\sphinxtermref{\DUrole{xref,std,std-term}{single dispatch}}}}、\sphinxcode{\sphinxupquote{functools.singledispatch()}} デコレータ、\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 443@\spxentry{PEP 443}}\sphinxhref{https://www.python.org/dev/peps/pep-0443}{\sphinxstylestrong{PEP 443}} を参照してください。 \item[{generic type\index{generic type@\spxentry{generic type}|spxpagem}\phantomsection\label{\detokenize{glossary:term-generic-type}}}] \leavevmode A {\hyperref[\detokenize{glossary:term-type}]{\sphinxtermref{\DUrole{xref,std,std-term}{type}}}} that can be parameterized; typically a {\hyperref[\detokenize{reference/datamodel:sequence-types}]{\sphinxcrossref{\DUrole{std,std-ref}{container class}}}} such as \sphinxcode{\sphinxupquote{list}} or \sphinxcode{\sphinxupquote{dict}}. Used for {\hyperref[\detokenize{glossary:term-type-hint}]{\sphinxtermref{\DUrole{xref,std,std-term}{type hints}}}} and {\hyperref[\detokenize{glossary:term-annotation}]{\sphinxtermref{\DUrole{xref,std,std-term}{annotations}}}}. For more details, see \DUrole{xref,std,std-ref}{generic alias types}, \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 483@\spxentry{PEP 483}}\sphinxhref{https://www.python.org/dev/peps/pep-0483}{\sphinxstylestrong{PEP 483}}, \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 484@\spxentry{PEP 484}}\sphinxhref{https://www.python.org/dev/peps/pep-0484}{\sphinxstylestrong{PEP 484}}, \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 585@\spxentry{PEP 585}}\sphinxhref{https://www.python.org/dev/peps/pep-0585}{\sphinxstylestrong{PEP 585}}, and the \sphinxcode{\sphinxupquote{typing}} module. \item[{GIL\index{GIL@\spxentry{GIL}|spxpagem}\phantomsection\label{\detokenize{glossary:term-gil}}}] \leavevmode {\hyperref[\detokenize{glossary:term-global-interpreter-lock}]{\sphinxtermref{\DUrole{xref,std,std-term}{global interpreter lock}}}} を参照してください。 \item[{global interpreter lock\index{global interpreter lock@\spxentry{global interpreter lock}|spxpagem}\phantomsection\label{\detokenize{glossary:term-global-interpreter-lock}}}] \leavevmode (グローバルインタプリタロック) {\hyperref[\detokenize{glossary:term-cpython}]{\sphinxtermref{\DUrole{xref,std,std-term}{CPython}}}} インタプリタが利用している、一度に Python の {\hyperref[\detokenize{glossary:term-bytecode}]{\sphinxtermref{\DUrole{xref,std,std-term}{バイトコード}}}} を実行するスレッドは一つだけであることを保証する仕組みです。これにより (\sphinxcode{\sphinxupquote{dict}} などの重要な組み込み型を含む) オブジェクトモデルが同時アクセスに対して暗黙的に安全になるので、 CPython の実装がシンプルになります。インタプリタ全体をロックすることで、マルチプロセッサマシンが生じる並列化のコストと引き換えに、インタプリタを簡単にマルチスレッド化できるようになります。 ただし、標準あるいは外部のいくつかの拡張モジュールは、圧縮やハッシュ計算などの計算の重い処理をするときに GIL を解除するように設計されています。また、I/O 処理をする場合 GIL は常に解除されます。 過去に "自由なマルチスレッド化" したインタプリタ (供用されるデータを細かい粒度でロックする) が開発されましたが、一般的なシングルプロセッサの場合のパフォーマンスが悪かったので成功しませんでした。このパフォーマンスの問題を克服しようとすると、実装がより複雑になり保守コストが増加すると考えられています。 \item[{hash\sphinxhyphen{}based pyc\index{hash\sphinxhyphen{}based pyc@\spxentry{hash\sphinxhyphen{}based pyc}|spxpagem}\phantomsection\label{\detokenize{glossary:term-hash-based-pyc}}}] \leavevmode (ハッシュベース pyc ファイル) 正当性を判別するために、対応するソースファイルの最終更新時刻ではなくハッシュ値を使用するバイトコードのキャッシュファイルです。 \item[{hashable\index{hashable@\spxentry{hashable}|spxpagem}\phantomsection\label{\detokenize{glossary:term-hashable}}}] \leavevmode (ハッシュ可能) \sphinxstyleemphasis{ハッシュ可能} なオブジェクトとは、生存期間中変わらないハッシュ値を持ち ({\hyperref[\detokenize{reference/datamodel:object.__hash__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_hash\_\_()}}}}} メソッドが必要)、他のオブジェクトと比較ができる ({\hyperref[\detokenize{reference/datamodel:object.__eq__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_eq\_\_()}}}}} メソッドが必要) オブジェクトです。同値なハッシュ可能オブジェクトは必ず同じハッシュ値を持つ必要があります。 ハッシュ可能なオブジェクトは辞書のキーや集合のメンバーとして使えます。辞書や集合のデータ構造は内部でハッシュ値を使っているからです。 Python のイミュータブルな組み込みオブジェクトは、ほとんどがハッシュ可能です。(リストや辞書のような) ミュータブルなコンテナはハッシュ不可能です。(タプルや frozenset のような) イミュータブルなコンテナは、要素がハッシュ可能であるときのみハッシュ可能です。 ユーザー定義のクラスのインスタンスであるようなオブジェクトはデフォルトでハッシュ可能です。 それらは全て (自身を除いて) 比較結果は非等価であり、ハッシュ値は \sphinxcode{\sphinxupquote{id()}} より得られます。 \item[{IDLE\index{IDLE@\spxentry{IDLE}|spxpagem}\phantomsection\label{\detokenize{glossary:term-idle}}}] \leavevmode Python の統合開発環境 (Integrated DeveLopment Environment) です。IDLE は Python の標準的な配布に同梱されている基本的な機能のエディタとインタプリタ環境です。 \item[{immutable\index{immutable@\spxentry{immutable}|spxpagem}\phantomsection\label{\detokenize{glossary:term-immutable}}}] \leavevmode (イミュータブル) 固定の値を持ったオブジェクトです。イミュータブルなオブジェクトには、数値、文字列、およびタプルなどがあります。これらのオブジェクトは値を変えられません。別の値を記憶させる際には、新たなオブジェクトを作成しなければなりません。イミュータブルなオブジェクトは、固定のハッシュ値が必要となる状況で重要な役割を果たします。辞書のキーがその例です。 \item[{import path\index{import path@\spxentry{import path}|spxpagem}\phantomsection\label{\detokenize{glossary:term-import-path}}}] \leavevmode {\hyperref[\detokenize{glossary:term-path-based-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{path based finder}}}} が import するモジュールを検索する場所 (または {\hyperref[\detokenize{glossary:term-path-entry}]{\sphinxtermref{\DUrole{xref,std,std-term}{path entry}}}}) のリスト。 import 中、このリストは通常 \sphinxcode{\sphinxupquote{sys.path}} から来ますが、サブパッケージの場合は親パッケージの \sphinxcode{\sphinxupquote{\_\_path\_\_}} 属性からも来ます。 \item[{importing\index{importing@\spxentry{importing}|spxpagem}\phantomsection\label{\detokenize{glossary:term-importing}}}] \leavevmode あるモジュールの Python コードが別のモジュールの Python コードで使えるようにする処理です。 \item[{importer\index{importer@\spxentry{importer}|spxpagem}\phantomsection\label{\detokenize{glossary:term-importer}}}] \leavevmode モジュールを探してロードするオブジェクト。 {\hyperref[\detokenize{glossary:term-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{finder}}}} と {\hyperref[\detokenize{glossary:term-loader}]{\sphinxtermref{\DUrole{xref,std,std-term}{loader}}}} のどちらでもあるオブジェクト。 \item[{interactive\index{interactive@\spxentry{interactive}|spxpagem}\phantomsection\label{\detokenize{glossary:term-interactive}}}] \leavevmode (対話的) Python には対話的インタプリタがあり、文や式をインタプリタのプロンプトに入力すると即座に実行されて結果を見ることができます。 \sphinxcode{\sphinxupquote{python}} と何も引数を与えずに実行してください。(コンピュータのメインメニューから Pythonの対話的インタプリタを起動できるかもしれません。) 対話的インタプリタは、新しいアイデアを試してみたり、モジュールやパッケージの中を覗いてみる(\sphinxcode{\sphinxupquote{help(x)}} を覚えておいてください) のに非常に便利なツールです。 \item[{interpreted\index{interpreted@\spxentry{interpreted}|spxpagem}\phantomsection\label{\detokenize{glossary:term-interpreted}}}] \leavevmode Python はインタプリタ形式の言語であり、コンパイラ言語の対極に位置します。 (バイトコードコンパイラがあるために、この区別は曖昧ですが。) ここでのインタプリタ言語とは、ソースコードのファイルを、まず実行可能形式にしてから実行させるといった操作なしに、直接実行できることを意味します。インタプリタ形式の言語は通常、コンパイラ形式の言語よりも開発/デバッグのサイクルは短いものの、プログラムの実行は一般に遅いです。 {\hyperref[\detokenize{glossary:term-interactive}]{\sphinxtermref{\DUrole{xref,std,std-term}{対話的}}}} も参照してください。 \item[{interpreter shutdown\index{interpreter shutdown@\spxentry{interpreter shutdown}|spxpagem}\phantomsection\label{\detokenize{glossary:term-interpreter-shutdown}}}] \leavevmode Python インタープリターはシャットダウンを要請された時に、モジュールやすべてのクリティカルな内部構造をなどの、すべての確保したリソースを段階的に開放する、特別なフェーズに入ります。 このフェーズは {\hyperref[\detokenize{glossary:term-garbage-collection}]{\sphinxtermref{\DUrole{xref,std,std-term}{ガベージコレクタ}}}} を複数回呼び出します。 これによりユーザー定義のデストラクターや weakref コールバックが呼び出されることがあります。 シャットダウンフェーズ中に実行されるコードは、それが依存するリソースがすでに機能しない(よくある例はライブラリーモジュールや warning 機構です) ために様々な例外に直面します。 インタープリタがシャットダウンする主な理由は \sphinxcode{\sphinxupquote{\_\_main\_\_}} モジュールや実行されていたスクリプトの実行が終了したことです。 \item[{iterable\index{iterable@\spxentry{iterable}|spxpagem}\phantomsection\label{\detokenize{glossary:term-iterable}}}] \leavevmode (反復可能オブジェクト) 要素を一度に 1 つずつ返せるオブジェクトです。 反復可能オブジェクトの例には、(\sphinxcode{\sphinxupquote{list}}, \sphinxcode{\sphinxupquote{str}}, \sphinxcode{\sphinxupquote{tuple}} といった) 全てのシーケンス型や、 \sphinxcode{\sphinxupquote{dict}} や {\hyperref[\detokenize{glossary:term-file-object}]{\sphinxtermref{\DUrole{xref,std,std-term}{ファイルオブジェクト}}}} といった幾つかの非シーケンス型、 あるいは {\hyperref[\detokenize{glossary:term-sequence}]{\sphinxtermref{\DUrole{xref,std,std-term}{Sequence}}}} 意味論を実装した {\hyperref[\detokenize{reference/datamodel:object.__iter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_iter\_\_()}}}}} メソッドか {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} メソッドを持つ任意のクラスのインスタンスが含まれます。 反復可能オブジェクトは {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} ループ内やその他多くのシーケンス (訳注: ここでのシーケンスとは、シーケンス型ではなくただの列という意味)が必要となる状況 (\sphinxcode{\sphinxupquote{zip()}}, \sphinxcode{\sphinxupquote{map()}}, ...) で利用できます。 反復可能オブジェクトを組み込み関数 \sphinxcode{\sphinxupquote{iter()}} の引数として渡すと、 オブジェクトに対するイテレータを返します。 このイテレータは一連の値を引き渡す際に便利です。 通常は反復可能オブジェクトを使う際には、 \sphinxcode{\sphinxupquote{iter()}} を呼んだりイテレータオブジェクトを自分で操作する必要はありません。 \sphinxcode{\sphinxupquote{for}} 文ではこの操作を自動的に行い、一時的な無名の変数を作成してループを回している間イテレータを保持します。 {\hyperref[\detokenize{glossary:term-iterator}]{\sphinxtermref{\DUrole{xref,std,std-term}{イテレータ}}}} 、 {\hyperref[\detokenize{glossary:term-sequence}]{\sphinxtermref{\DUrole{xref,std,std-term}{シーケンス}}}} 、 {\hyperref[\detokenize{glossary:term-generator}]{\sphinxtermref{\DUrole{xref,std,std-term}{ジェネレータ}}}} も参照してください。 \item[{iterator\index{iterator@\spxentry{iterator}|spxpagem}\phantomsection\label{\detokenize{glossary:term-iterator}}}] \leavevmode (イテレータ) データの流れを表現するオブジェクトです。イテレータの \sphinxcode{\sphinxupquote{\_\_next\_\_()}} メソッドを繰り返し呼び出す (または組み込み関数 \sphinxcode{\sphinxupquote{next()}} に渡す) と、流れの中の要素を一つずつ返します。データがなくなると、代わりに \sphinxcode{\sphinxupquote{StopIteration}} 例外を送出します。その時点で、イテレータオブジェクトは尽きており、それ以降は \sphinxcode{\sphinxupquote{\_\_next\_\_()}} を何度呼んでも \sphinxcode{\sphinxupquote{StopIteration}} を送出します。イテレータは、そのイテレータオブジェクト自体を返す {\hyperref[\detokenize{reference/datamodel:object.__iter__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_iter\_\_()}}}}} メソッドを実装しなければならないので、イテレータは他の iterable を受理するほとんどの場所で利用できます。はっきりとした例外は複数の反復を行うようなコードです。 (\sphinxcode{\sphinxupquote{list}} のような) コンテナオブジェクトは、自身を \sphinxcode{\sphinxupquote{iter()}} 関数にオブジェクトに渡したり {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} ループ内で使うたびに、新たな未使用のイテレータを生成します。これをイテレータで行おうとすると、前回のイテレーションで使用済みの同じイテレータオブジェクトを単純に返すため、空のコンテナのようになってしまします。 詳細な情報は \DUrole{xref,std,std-ref}{typeiter} にあります。 \item[{key function\index{key function@\spxentry{key function}|spxpagem}\phantomsection\label{\detokenize{glossary:term-key-function}}}] \leavevmode (キー関数) キー関数、あるいは照合関数とは、ソートや順序比較のための値を返す呼び出し可能オブジェクト(callable)です。例えば、 \sphinxcode{\sphinxupquote{locale.strxfrm()}} をキー関数に使えば、ロケール依存のソートの慣習にのっとったソートキーを返します。 Python の多くのツールはキー関数を受け取り要素の並び順やグループ化を管理します。 \sphinxcode{\sphinxupquote{min()}}, \sphinxcode{\sphinxupquote{max()}}, \sphinxcode{\sphinxupquote{sorted()}}, \sphinxcode{\sphinxupquote{list.sort()}}, \sphinxcode{\sphinxupquote{heapq.merge()}}, \sphinxcode{\sphinxupquote{heapq.nsmallest()}}, \sphinxcode{\sphinxupquote{heapq.nlargest()}}, \sphinxcode{\sphinxupquote{itertools.groupby()}} 等があります。 キー関数を作る方法はいくつかあります。 例えば \sphinxcode{\sphinxupquote{str.lower()}} メソッドを大文字小文字を区別しないソートを行うキー関数として使うことが出来ます。 あるいは、\sphinxcode{\sphinxupquote{lambda r: (r{[}0{]}, r{[}2{]})}} のような {\hyperref[\detokenize{reference/expressions:lambda}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{lambda}}}}} 式からキー関数を作ることができます。 また、 \sphinxcode{\sphinxupquote{operator}} モジュールは \sphinxcode{\sphinxupquote{attrgetter()}}, \sphinxcode{\sphinxupquote{itemgetter()}}, \sphinxcode{\sphinxupquote{methodcaller()}} という 3 つのキー関数コンストラクタを提供しています。 キー関数の作り方と使い方の例は \DUrole{xref,std,std-ref}{Sorting HOW TO} を参照してください。 \item[{keyword argument\index{keyword argument@\spxentry{keyword argument}|spxpagem}\phantomsection\label{\detokenize{glossary:term-keyword-argument}}}] \leavevmode {\hyperref[\detokenize{glossary:term-argument}]{\sphinxtermref{\DUrole{xref,std,std-term}{実引数}}}} を参照してください。 \item[{lambda\index{lambda@\spxentry{lambda}|spxpagem}\phantomsection\label{\detokenize{glossary:term-lambda}}}] \leavevmode (ラムダ) 無名のインライン関数で、関数が呼び出されたときに評価される 1 つの {\hyperref[\detokenize{glossary:term-expression}]{\sphinxtermref{\DUrole{xref,std,std-term}{式}}}} を含みます。ラムダ関数を作る構文は \sphinxcode{\sphinxupquote{lambda {[}parameters{]}: expression}} です。 \item[{LBYL\index{LBYL@\spxentry{LBYL}|spxpagem}\phantomsection\label{\detokenize{glossary:term-lbyl}}}] \leavevmode 「ころばぬ先の杖 (look before you leap)」 の略です。このコーディングスタイルでは、呼び出しや検索を行う前に、明示的に前提条件 (pre\sphinxhyphen{}condition) 判定を行います。 {\hyperref[\detokenize{glossary:term-eafp}]{\sphinxtermref{\DUrole{xref,std,std-term}{EAFP}}}} アプローチと対照的で、 {\hyperref[\detokenize{reference/compound_stmts:if}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{if}}}}} 文がたくさん使われるのが特徴的です。 マルチスレッド化された環境では、LBYL アプローチは "見る" 過程と "飛ぶ" 過程の競合状態を引き起こすリスクがあります。例えば、\sphinxcode{\sphinxupquote{if key in mapping: return mapping{[}key{]}}} というコードは、判定の後、別のスレッドが探索の前に \sphinxstyleemphasis{mapping} から \sphinxstyleemphasis{key} を取り除くと失敗します。この問題は、ロックするか EAFP アプローチを使うことで解決できます。 \item[{list\index{list@\spxentry{list}|spxpagem}\phantomsection\label{\detokenize{glossary:term-list}}}] \leavevmode (リスト) Python の組み込みの {\hyperref[\detokenize{glossary:term-sequence}]{\sphinxtermref{\DUrole{xref,std,std-term}{シーケンス}}}} です。リストという名前ですが、リンクリストではなく、他の言語で言う配列 (array) と同種のもので、要素へのアクセスは O(1) です。 \item[{list comprehension\index{list comprehension@\spxentry{list comprehension}|spxpagem}\phantomsection\label{\detokenize{glossary:term-list-comprehension}}}] \leavevmode (リスト内包表記) シーケンス中の全てあるいは一部の要素を処理して、その結果からなるリストを返す、コンパクトな方法です。 \sphinxcode{\sphinxupquote{result = {[}'\{:\#04x\}'.format(x) for x in range(256) if x \% 2 == 0{]}}} とすると、 0 から 255 までの偶数を 16進数表記 (0x..) した文字列からなるリストを生成します。 {\hyperref[\detokenize{reference/compound_stmts:if}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{if}}}}} 節はオプションです。 {\hyperref[\detokenize{reference/compound_stmts:if}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{if}}}}} 節がない場合、 \sphinxcode{\sphinxupquote{range(256)}} の全ての要素が処理されます。 \item[{loader\index{loader@\spxentry{loader}|spxpagem}\phantomsection\label{\detokenize{glossary:term-loader}}}] \leavevmode モジュールをロードするオブジェクト。 \sphinxcode{\sphinxupquote{load\_module()}} という名前のメソッドを定義していなければなりません。ローダーは一般的に {\hyperref[\detokenize{glossary:term-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{finder}}}} から返されます。詳細は \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 302@\spxentry{PEP 302}}\sphinxhref{https://www.python.org/dev/peps/pep-0302}{\sphinxstylestrong{PEP 302}} を、 {\hyperref[\detokenize{glossary:term-abstract-base-class}]{\sphinxtermref{\DUrole{xref,std,std-term}{abstract base class}}}} については \sphinxcode{\sphinxupquote{importlib.abc.Loader}} を参照してください。 \item[{magic method\index{magic method@\spxentry{magic method}|spxpagem}\phantomsection\label{\detokenize{glossary:term-magic-method}}}] \leavevmode \index{magic@\spxentry{magic}!method@\spxentry{method}}\index{method@\spxentry{method}!magic@\spxentry{magic}}\ignorespaces {\hyperref[\detokenize{glossary:term-special-method}]{\sphinxtermref{\DUrole{xref,std,std-term}{special method}}}} のくだけた同義語です。 \item[{mapping\index{mapping@\spxentry{mapping}|spxpagem}\phantomsection\label{\detokenize{glossary:term-mapping}}}] \leavevmode (マッピング) 任意のキー探索をサポートしていて、 \sphinxcode{\sphinxupquote{Mapping}} か \sphinxcode{\sphinxupquote{MutableMapping}} の \DUrole{xref,std,std-ref}{抽象基底クラス} で指定されたメソッドを実装しているコンテナオブジェクトです。例えば、 \sphinxcode{\sphinxupquote{dict}}, \sphinxcode{\sphinxupquote{collections.defaultdict}}, \sphinxcode{\sphinxupquote{collections.OrderedDict}}, \sphinxcode{\sphinxupquote{collections.Counter}} などです。 \item[{meta path finder\index{meta path finder@\spxentry{meta path finder}|spxpagem}\phantomsection\label{\detokenize{glossary:term-meta-path-finder}}}] \leavevmode \sphinxcode{\sphinxupquote{sys.meta\_path}} を検索して得られた {\hyperref[\detokenize{glossary:term-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{finder}}}}. meta path finder は {\hyperref[\detokenize{glossary:term-path-entry-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{path entry finder}}}} と関係はありますが、別物です。 meta path finder が実装するメソッドについては \sphinxcode{\sphinxupquote{importlib.abc.MetaPathFinder}} を参照してください。 \item[{metaclass\index{metaclass@\spxentry{metaclass}|spxpagem}\phantomsection\label{\detokenize{glossary:term-metaclass}}}] \leavevmode (メタクラス) クラスのクラスです。クラス定義は、クラス名、クラスの辞書と、基底クラスのリストを作ります。メタクラスは、それら 3 つを引数として受け取り、クラスを作る責任を負います。ほとんどのオブジェクト指向言語は(訳注:メタクラスの)デフォルトの実装を提供しています。Python が特別なのはカスタムのメタクラスを作成できる点です。ほとんどのユーザーに取って、メタクラスは全く必要のないものです。しかし、一部の場面では、メタクラスは強力でエレガントな方法を提供します。たとえば属性アクセスのログを取ったり、スレッドセーフ性を追加したり、オブジェクトの生成を追跡したり、シングルトンを実装するなど、多くの場面で利用されます。 詳細は {\hyperref[\detokenize{reference/datamodel:metaclasses}]{\sphinxcrossref{\DUrole{std,std-ref}{メタクラス}}}} を参照してください。 \item[{method\index{method@\spxentry{method}|spxpagem}\phantomsection\label{\detokenize{glossary:term-method}}}] \leavevmode (メソッド) クラス本体の中で定義された関数。そのクラスのインスタンスの属性として呼び出された場合、メソッドはインスタンスオブジェクトを第一 {\hyperref[\detokenize{glossary:term-argument}]{\sphinxtermref{\DUrole{xref,std,std-term}{引数}}}} として受け取ります (この第一引数は通常 \sphinxcode{\sphinxupquote{self}} と呼ばれます)。 {\hyperref[\detokenize{glossary:term-function}]{\sphinxtermref{\DUrole{xref,std,std-term}{関数}}}} と {\hyperref[\detokenize{glossary:term-nested-scope}]{\sphinxtermref{\DUrole{xref,std,std-term}{ネストされたスコープ}}}} も参照してください。 \item[{method resolution order\index{method resolution order@\spxentry{method resolution order}|spxpagem}\phantomsection\label{\detokenize{glossary:term-method-resolution-order}}}] \leavevmode (メソッド解決順序) 探索中に基底クラスが構成要素を検索される順番です。 2.3 以降の Python インタープリタが使用するアルゴリズムの詳細については \sphinxhref{https://www.python.org/download/releases/2.3/mro/}{The Python 2.3 Method Resolution Order} を参照してください。 \item[{module\index{module@\spxentry{module}|spxpagem}\phantomsection\label{\detokenize{glossary:term-module}}}] \leavevmode (モジュール) Python コードの組織単位としてはたらくオブジェクトです。モジュールは任意の Python オブジェクトを含む名前空間を持ちます。モジュールは {\hyperref[\detokenize{glossary:term-importing}]{\sphinxtermref{\DUrole{xref,std,std-term}{importing}}}} の処理によって Python に読み込まれます。 {\hyperref[\detokenize{glossary:term-package}]{\sphinxtermref{\DUrole{xref,std,std-term}{パッケージ}}}} を参照してください。 \item[{module spec\index{module spec@\spxentry{module spec}|spxpagem}\phantomsection\label{\detokenize{glossary:term-module-spec}}}] \leavevmode モジュールをロードするのに使われるインポート関連の情報を含む名前空間です。 \sphinxcode{\sphinxupquote{importlib.machinery.ModuleSpec}} のインスタンスです。 \item[{MRO\index{MRO@\spxentry{MRO}|spxpagem}\phantomsection\label{\detokenize{glossary:term-mro}}}] \leavevmode {\hyperref[\detokenize{glossary:term-method-resolution-order}]{\sphinxtermref{\DUrole{xref,std,std-term}{method resolution order}}}} を参照してください。 \item[{mutable\index{mutable@\spxentry{mutable}|spxpagem}\phantomsection\label{\detokenize{glossary:term-mutable}}}] \leavevmode (ミュータブル) ミュータブルなオブジェクトは、 \sphinxcode{\sphinxupquote{id()}} を変えることなく値を変更できます。 {\hyperref[\detokenize{glossary:term-immutable}]{\sphinxtermref{\DUrole{xref,std,std-term}{イミュータブル}}}}) も参照してください。 \item[{named tuple\index{named tuple@\spxentry{named tuple}|spxpagem}\phantomsection\label{\detokenize{glossary:term-named-tuple}}}] \leavevmode "名前付きタプル" という用語は、タプルを継承していて、インデックスが付く要素に対し属性を使ってのアクセスもできる任意の型やクラスに応用されています。 その型やクラスは他の機能も持っていることもあります。 \sphinxcode{\sphinxupquote{time.localtime()}} や \sphinxcode{\sphinxupquote{os.stat()}} の返り値を含むいくつかの組み込み型は名前付きタプルです。 他の例は \sphinxcode{\sphinxupquote{sys.float\_info}} です: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{sys}\PYG{o}{.}\PYG{n}{float\PYGZus{}info}\PYG{p}{[}\PYG{l+m+mi}{1}\PYG{p}{]} \PYG{c+c1}{\PYGZsh{} indexed access} \PYG{g+go}{1024} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{sys}\PYG{o}{.}\PYG{n}{float\PYGZus{}info}\PYG{o}{.}\PYG{n}{max\PYGZus{}exp} \PYG{c+c1}{\PYGZsh{} named field access} \PYG{g+go}{1024} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n+nb}{isinstance}\PYG{p}{(}\PYG{n}{sys}\PYG{o}{.}\PYG{n}{float\PYGZus{}info}\PYG{p}{,} \PYG{n+nb}{tuple}\PYG{p}{)} \PYG{c+c1}{\PYGZsh{} kind of tuple} \PYG{g+go}{True} \end{sphinxVerbatim} (上の例のように) いくつかの名前付きタプルは組み込み型になっています。 その他にも名前付きタプルは、通常のクラス定義で \sphinxcode{\sphinxupquote{tuple}} を継承し、名前のフィールドを定義して作成できます。 そのようなクラスは手動で書いたり、 \sphinxcode{\sphinxupquote{collections.namedtuple()}} ファクトリ関数で作成したりできます。 後者の方法は、手動で書いた名前付きタプルや組み込みの名前付きタプルには無い付加的なメソッドを追加できます。 \item[{namespace\index{namespace@\spxentry{namespace}|spxpagem}\phantomsection\label{\detokenize{glossary:term-namespace}}}] \leavevmode (名前空間) 変数が格納される場所です。名前空間は辞書として実装されます。名前空間にはオブジェクトの (メソッドの) 入れ子になったものだけでなく、局所的なもの、大域的なもの、そして組み込みのものがあります。名前空間は名前の衝突を防ぐことによってモジュール性をサポートする。例えば関数 \sphinxcode{\sphinxupquote{builtins.open}} と \sphinxcode{\sphinxupquote{os.open()}} は名前空間で区別されています。また、どのモジュールが関数を実装しているか明示することによって名前空間は可読性と保守性を支援します。例えば、\sphinxcode{\sphinxupquote{random.seed()}} や \sphinxcode{\sphinxupquote{itertools.islice()}} と書くと、それぞれモジュール \sphinxcode{\sphinxupquote{random}} や \sphinxcode{\sphinxupquote{itertools}} で実装されていることが明らかです。 \item[{namespace package\index{namespace package@\spxentry{namespace package}|spxpagem}\phantomsection\label{\detokenize{glossary:term-namespace-package}}}] \leavevmode (名前空間パッケージ) サブパッケージのコンテナとしてのみ提供される \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 420@\spxentry{PEP 420}}\sphinxhref{https://www.python.org/dev/peps/pep-0420}{\sphinxstylestrong{PEP 420}} で定義された {\hyperref[\detokenize{glossary:term-package}]{\sphinxtermref{\DUrole{xref,std,std-term}{package}}}} です。名前空間パッケージは物理的な表現を持たないことができ、 \sphinxcode{\sphinxupquote{\_\_init\_\_.py}} ファイルを持たないため、 {\hyperref[\detokenize{glossary:term-regular-package}]{\sphinxtermref{\DUrole{xref,std,std-term}{regular package}}}} とは異なります。 {\hyperref[\detokenize{glossary:term-module}]{\sphinxtermref{\DUrole{xref,std,std-term}{module}}}} を参照してください。 \item[{nested scope\index{nested scope@\spxentry{nested scope}|spxpagem}\phantomsection\label{\detokenize{glossary:term-nested-scope}}}] \leavevmode (ネストされたスコープ) 外側で定義されている変数を参照する機能です。例えば、ある関数が別の関数の中で定義されている場合、内側の関数は外側の関数中の変数を参照できます。ネストされたスコープはデフォルトでは変数の参照だけができ、変数の代入はできないので注意してください。ローカル変数は、最も内側のスコープで変数を読み書きします。同様に、グローバル変数を使うとグローバル名前空間の値を読み書きします。 {\hyperref[\detokenize{reference/simple_stmts:nonlocal}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{nonlocal}}}}} で外側の変数に書き込めます。 \item[{new\sphinxhyphen{}style class\index{new\sphinxhyphen{}style class@\spxentry{new\sphinxhyphen{}style class}|spxpagem}\phantomsection\label{\detokenize{glossary:term-new-style-class}}}] \leavevmode (新スタイルクラス) 今では全てのクラスオブジェクトに使われている味付けの古い名前です。以前の Python のバージョンでは、新スタイルクラスのみが {\hyperref[\detokenize{reference/datamodel:object.__slots__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_slots\_\_}}}}} 、デスクリプタ、 {\hyperref[\detokenize{reference/datamodel:object.__getattribute__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getattribute\_\_()}}}}} 、クラスメソッド、そして静的メソッド等の Python の新しい、多様な機能を利用できました。 \item[{object\index{object@\spxentry{object}|spxpagem}\phantomsection\label{\detokenize{glossary:term-object}}}] \leavevmode (オブジェクト) 状態 (属性や値) と定義された振る舞い (メソッド) をもつ全てのデータ。もしくは、全ての {\hyperref[\detokenize{glossary:term-new-style-class}]{\sphinxtermref{\DUrole{xref,std,std-term}{新スタイルクラス}}}} の究極の基底クラスのこと。 \item[{package\index{package@\spxentry{package}|spxpagem}\phantomsection\label{\detokenize{glossary:term-package}}}] \leavevmode (パッケージ) サブモジュールや再帰的にサブパッケージを含むことの出来る {\hyperref[\detokenize{glossary:term-module}]{\sphinxtermref{\DUrole{xref,std,std-term}{module}}}} のことです。専門的には、パッケージは \sphinxcode{\sphinxupquote{\_\_path\_\_}} 属性を持つ Python オブジェクトです。 {\hyperref[\detokenize{glossary:term-regular-package}]{\sphinxtermref{\DUrole{xref,std,std-term}{regular package}}}} と {\hyperref[\detokenize{glossary:term-namespace-package}]{\sphinxtermref{\DUrole{xref,std,std-term}{namespace package}}}} を参照してください。 \item[{parameter\index{parameter@\spxentry{parameter}|spxpagem}\phantomsection\label{\detokenize{glossary:term-parameter}}}] \leavevmode (仮引数) 名前付の実体で {\hyperref[\detokenize{glossary:term-function}]{\sphinxtermref{\DUrole{xref,std,std-term}{関数}}}} (や {\hyperref[\detokenize{glossary:term-method}]{\sphinxtermref{\DUrole{xref,std,std-term}{メソッド}}}} ) の定義において関数が受ける {\hyperref[\detokenize{glossary:term-argument}]{\sphinxtermref{\DUrole{xref,std,std-term}{実引数}}}} を指定します。仮引数には5種類あります: \begin{itemize} \item {} \sphinxstyleemphasis{位置またはキーワード}: {\hyperref[\detokenize{glossary:term-argument}]{\sphinxtermref{\DUrole{xref,std,std-term}{位置}}}} であるいは {\hyperref[\detokenize{glossary:term-argument}]{\sphinxtermref{\DUrole{xref,std,std-term}{キーワード引数}}}} として渡すことができる引数を指定します。 これはたとえば以下の \sphinxstyleemphasis{foo} や \sphinxstyleemphasis{bar} のように、デフォルトの仮引数の種類です: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{def} \PYG{n+nf}{func}\PYG{p}{(}\PYG{n}{foo}\PYG{p}{,} \PYG{n}{bar}\PYG{o}{=}\PYG{k+kc}{None}\PYG{p}{)}\PYG{p}{:} \PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \end{sphinxVerbatim} \end{itemize} \phantomsection\label{\detokenize{glossary:positional-only-parameter}}\begin{itemize} \item {} 位置専用: 位置によってのみ与えられる引数を指定します。位置専用の引数は 関数定義の引数のリストの中でそれらの後ろに \sphinxcode{\sphinxupquote{/}} を含めることで定義できます。例えば下記の \sphinxstyleemphasis{posonly1} と \sphinxstyleemphasis{posonly2} は位置専用引数になります: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{def} \PYG{n+nf}{func}\PYG{p}{(}\PYG{n}{posonly1}\PYG{p}{,} \PYG{n}{posonly2}\PYG{p}{,} \PYG{o}{/}\PYG{p}{,} \PYG{n}{positional\PYGZus{}or\PYGZus{}keyword}\PYG{p}{)}\PYG{p}{:} \PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \end{sphinxVerbatim} \end{itemize} \phantomsection\label{\detokenize{glossary:keyword-only-parameter}}\begin{itemize} \item {} \sphinxstyleemphasis{キーワード専用}: キーワードによってのみ与えられる引数を指定します。キーワード専用の引数を定義できる場所は、例えば以下の \sphinxstyleemphasis{kw\_only1} や \sphinxstyleemphasis{kw\_only2} のように、関数定義の仮引数リストに含めた可変長位置引数または裸の \sphinxcode{\sphinxupquote{*}} の後です: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{def} \PYG{n+nf}{func}\PYG{p}{(}\PYG{n}{arg}\PYG{p}{,} \PYG{o}{*}\PYG{p}{,} \PYG{n}{kw\PYGZus{}only1}\PYG{p}{,} \PYG{n}{kw\PYGZus{}only2}\PYG{p}{)}\PYG{p}{:} \PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \end{sphinxVerbatim} \item {} \sphinxstyleemphasis{可変長位置}: (他の仮引数で既に受けられた任意の位置引数に加えて) 任意の個数の位置引数が与えられることを指定します。このような仮引数は、以下の \sphinxstyleemphasis{args} のように仮引数名の前に \sphinxcode{\sphinxupquote{*}} をつけることで定義できます: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{def} \PYG{n+nf}{func}\PYG{p}{(}\PYG{o}{*}\PYG{n}{args}\PYG{p}{,} \PYG{o}{*}\PYG{o}{*}\PYG{n}{kwargs}\PYG{p}{)}\PYG{p}{:} \PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \end{sphinxVerbatim} \item {} \sphinxstyleemphasis{可変長キーワード}: (他の仮引数で既に受けられた任意のキーワード引数に加えて) 任意の個数のキーワード引数が与えられることを指定します。このような仮引数は、上の例の \sphinxstyleemphasis{kwargs} のように仮引数名の前に \sphinxcode{\sphinxupquote{**}} をつけることで定義できます。 \end{itemize} 仮引数はオプションと必須の引数のどちらも指定でき、オプションの引数にはデフォルト値も指定できます。 {\hyperref[\detokenize{glossary:term-parameter}]{\sphinxtermref{\DUrole{xref,std,std-term}{仮引数}}}} 、FAQ の \DUrole{xref,std,std-ref}{実引数と仮引数の違いは何ですか?} 、\sphinxcode{\sphinxupquote{inspect.Parameter}} クラス、 {\hyperref[\detokenize{reference/compound_stmts:function}]{\sphinxcrossref{\DUrole{std,std-ref}{関数定義}}}} セクション、\index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 362@\spxentry{PEP 362}}\sphinxhref{https://www.python.org/dev/peps/pep-0362}{\sphinxstylestrong{PEP 362}} を参照してください。 \item[{path entry\index{path entry@\spxentry{path entry}|spxpagem}\phantomsection\label{\detokenize{glossary:term-path-entry}}}] \leavevmode {\hyperref[\detokenize{glossary:term-path-based-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{path based finder}}}} が import するモジュールを探す {\hyperref[\detokenize{glossary:term-import-path}]{\sphinxtermref{\DUrole{xref,std,std-term}{import path}}}} 上の1つの場所です。 \item[{path entry finder\index{path entry finder@\spxentry{path entry finder}|spxpagem}\phantomsection\label{\detokenize{glossary:term-path-entry-finder}}}] \leavevmode \sphinxcode{\sphinxupquote{sys.path\_hooks}} にある callable (つまり {\hyperref[\detokenize{glossary:term-path-entry-hook}]{\sphinxtermref{\DUrole{xref,std,std-term}{path entry hook}}}}) が返した {\hyperref[\detokenize{glossary:term-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{finder}}}} です。与えられた {\hyperref[\detokenize{glossary:term-path-entry}]{\sphinxtermref{\DUrole{xref,std,std-term}{path entry}}}} にあるモジュールを見つける方法を知っています。 パスエントリーファインダが実装するメソッドについては \sphinxcode{\sphinxupquote{importlib.abc.PathEntryFinder}} を参照してください。 \item[{path entry hook\index{path entry hook@\spxentry{path entry hook}|spxpagem}\phantomsection\label{\detokenize{glossary:term-path-entry-hook}}}] \leavevmode \sphinxcode{\sphinxupquote{sys.path\_hook}} リストにある callable で、指定された {\hyperref[\detokenize{glossary:term-path-entry}]{\sphinxtermref{\DUrole{xref,std,std-term}{path entry}}}} にあるモジュールを見つける方法を知っている場合に {\hyperref[\detokenize{glossary:term-path-entry-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{path entry finder}}}} を返します。 \item[{path based finder\index{path based finder@\spxentry{path based finder}|spxpagem}\phantomsection\label{\detokenize{glossary:term-path-based-finder}}}] \leavevmode デフォルトの {\hyperref[\detokenize{glossary:term-meta-path-finder}]{\sphinxtermref{\DUrole{xref,std,std-term}{meta path finder}}}} の1つは、モジュールの {\hyperref[\detokenize{glossary:term-import-path}]{\sphinxtermref{\DUrole{xref,std,std-term}{import path}}}} を検索します。 \item[{path\sphinxhyphen{}like object\index{path\sphinxhyphen{}like object@\spxentry{path\sphinxhyphen{}like object}|spxpagem}\phantomsection\label{\detokenize{glossary:term-path-like-object}}}] \leavevmode (path\sphinxhyphen{}like オブジェクト) ファイルシステムパスを表します。 path\sphinxhyphen{}like オブジェクトは、パスを表す \sphinxcode{\sphinxupquote{str}} オブジェクトや \sphinxcode{\sphinxupquote{bytes}} オブジェクト、または \sphinxcode{\sphinxupquote{os.PathLike}} プロトコルを実装したオブジェクトのどれかです。 \sphinxcode{\sphinxupquote{os.PathLike}} プロトコルをサポートしているオブジェクトは \sphinxcode{\sphinxupquote{os.fspath()}} を呼び出すことで \sphinxcode{\sphinxupquote{str}} または \sphinxcode{\sphinxupquote{bytes}} のファイルシステムパスに変換できます。 \sphinxcode{\sphinxupquote{os.fsdecode()}} と \sphinxcode{\sphinxupquote{os.fsencode()}} はそれぞれ \sphinxcode{\sphinxupquote{str}} あるいは \sphinxcode{\sphinxupquote{bytes}} になるのを保証するのに使えます。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 519@\spxentry{PEP 519}}\sphinxhref{https://www.python.org/dev/peps/pep-0519}{\sphinxstylestrong{PEP 519}} で導入されました。 \item[{PEP\index{PEP@\spxentry{PEP}|spxpagem}\phantomsection\label{\detokenize{glossary:term-pep}}}] \leavevmode Python Enhancement Proposal。PEP は、Python コミュニティに対して情報を提供する、あるいは Python の新機能やその過程や環境について記述する設計文書です。 PEP は、機能についての簡潔な技術的仕様と提案する機能の論拠 (理論) を伝えるべきです。 PEP は、新機能の提案にかかる、コミュニティによる問題提起の集積と Python になされる設計決断の文書化のための最上位の機構となることを意図しています。PEP の著者にはコミュニティ内の合意形成を行うこと、反対意見を文書化することの責務があります。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 1@\spxentry{PEP 1}}\sphinxhref{https://www.python.org/dev/peps/pep-0001}{\sphinxstylestrong{PEP 1}} を参照してください。 \item[{portion\index{portion@\spxentry{portion}|spxpagem}\phantomsection\label{\detokenize{glossary:term-portion}}}] \leavevmode \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 420@\spxentry{PEP 420}}\sphinxhref{https://www.python.org/dev/peps/pep-0420}{\sphinxstylestrong{PEP 420}} で定義されている、namespace package に属する、複数のファイルが (zipファイルに格納されている場合もある) 1つのディレクトリに格納されたもの。 \item[{positional argument (位置引数)\index{positional argument (位置引数)@\spxentry{positional argument}\spxextra{位置引数}|spxpagem}\phantomsection\label{\detokenize{glossary:term-positional-argument}}}] \leavevmode {\hyperref[\detokenize{glossary:term-argument}]{\sphinxtermref{\DUrole{xref,std,std-term}{実引数}}}} を参照してください。 \item[{provisional API\index{provisional API@\spxentry{provisional API}|spxpagem}\phantomsection\label{\detokenize{glossary:term-provisional-api}}}] \leavevmode (暫定 API) 標準ライブラリの後方互換性保証から計画的に除外されたものです。そのようなインターフェースへの大きな変更は、暫定であるとされている間は期待されていませんが、コア開発者によって必要とみなされれば、後方非互換な変更 (インターフェースの削除まで含まれる) が行われえます。このような変更はむやみに行われるものではありません \sphinxhyphen{}\sphinxhyphen{} これは API を組み込む前には見落とされていた重大な欠陥が露呈したときにのみ行われます。 暫定 API についても、後方互換性のない変更は「最終手段」とみなされています。問題点が判明した場合でも後方互換な解決策を探すべきです。 このプロセスにより、標準ライブラリは問題となるデザインエラーに長い間閉じ込められることなく、時代を超えて進化を続けられます。詳細は \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 411@\spxentry{PEP 411}}\sphinxhref{https://www.python.org/dev/peps/pep-0411}{\sphinxstylestrong{PEP 411}} を参照してください。 \item[{provisional package\index{provisional package@\spxentry{provisional package}|spxpagem}\phantomsection\label{\detokenize{glossary:term-provisional-package}}}] \leavevmode {\hyperref[\detokenize{glossary:term-provisional-api}]{\sphinxtermref{\DUrole{xref,std,std-term}{provisional API}}}} を参照してください。 \item[{Python 3000\index{Python 3000@\spxentry{Python 3000}|spxpagem}\phantomsection\label{\detokenize{glossary:term-python-3000}}}] \leavevmode Python 3.x リリースラインのニックネームです。(Python 3 が遠い将来の話だった頃に作られた言葉です。) "Py3k" と略されることもあります。 \item[{Pythonic\index{Pythonic@\spxentry{Pythonic}|spxpagem}\phantomsection\label{\detokenize{glossary:term-pythonic}}}] \leavevmode 他の言語で一般的な考え方で書かれたコードではなく、Python の特に一般的なイディオムに従った考え方やコード片。例えば、Python の一般的なイディオムでは {\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} 文を使ってイテラブルのすべての要素に渡ってループします。他の多くの言語にはこの仕組みはないので、Python に慣れていない人は代わりに数値のカウンターを使うかもしれません: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{for} \PYG{n}{i} \PYG{o+ow}{in} \PYG{n+nb}{range}\PYG{p}{(}\PYG{n+nb}{len}\PYG{p}{(}\PYG{n}{food}\PYG{p}{)}\PYG{p}{)}\PYG{p}{:} \PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{food}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)} \end{sphinxVerbatim} これに対し、きれいな Pythonic な方法は: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{for} \PYG{n}{piece} \PYG{o+ow}{in} \PYG{n}{food}\PYG{p}{:} \PYG{n+nb}{print}\PYG{p}{(}\PYG{n}{piece}\PYG{p}{)} \end{sphinxVerbatim} \item[{qualified name\index{qualified name@\spxentry{qualified name}|spxpagem}\phantomsection\label{\detokenize{glossary:term-qualified-name}}}] \leavevmode (修飾名) モジュールのグローバルスコープから、そのモジュールで定義されたクラス、関数、メソッドへの、 "パス" を表すドット名表記です。 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 3155@\spxentry{PEP 3155}}\sphinxhref{https://www.python.org/dev/peps/pep-3155}{\sphinxstylestrong{PEP 3155}} で定義されています。トップレベルの関数やクラスでは、修飾名はオブジェクトの名前と同じです: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k}{class} \PYG{n+nc}{C}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{class} \PYG{n+nc}{D}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{def} \PYG{n+nf}{meth}\PYG{p}{(}\PYG{n+nb+bp}{self}\PYG{p}{)}\PYG{p}{:} \PYG{g+gp}{... } \PYG{k}{pass} \PYG{g+gp}{...} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{C}\PYG{o}{.}\PYG{n+nv+vm}{\PYGZus{}\PYGZus{}qualname\PYGZus{}\PYGZus{}} \PYG{g+go}{\PYGZsq{}C\PYGZsq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{C}\PYG{o}{.}\PYG{n}{D}\PYG{o}{.}\PYG{n+nv+vm}{\PYGZus{}\PYGZus{}qualname\PYGZus{}\PYGZus{}} \PYG{g+go}{\PYGZsq{}C.D\PYGZsq{}} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{C}\PYG{o}{.}\PYG{n}{D}\PYG{o}{.}\PYG{n}{meth}\PYG{o}{.}\PYG{n+nv+vm}{\PYGZus{}\PYGZus{}qualname\PYGZus{}\PYGZus{}} \PYG{g+go}{\PYGZsq{}C.D.meth\PYGZsq{}} \end{sphinxVerbatim} モジュールへの参照で使われると、\sphinxstyleemphasis{完全修飾名 (fully qualified name)} はすべての親パッケージを含む全体のドット名表記、例えば \sphinxcode{\sphinxupquote{email.mime.text}} を意味します: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{k+kn}{import} \PYG{n+nn}{email}\PYG{n+nn}{.}\PYG{n+nn}{mime}\PYG{n+nn}{.}\PYG{n+nn}{text} \PYG{g+gp}{\PYGZgt{}\PYGZgt{}\PYGZgt{} }\PYG{n}{email}\PYG{o}{.}\PYG{n}{mime}\PYG{o}{.}\PYG{n}{text}\PYG{o}{.}\PYG{n+nv+vm}{\PYGZus{}\PYGZus{}name\PYGZus{}\PYGZus{}} \PYG{g+go}{\PYGZsq{}email.mime.text\PYGZsq{}} \end{sphinxVerbatim} \item[{reference count\index{reference count@\spxentry{reference count}|spxpagem}\phantomsection\label{\detokenize{glossary:term-reference-count}}}] \leavevmode (参照カウント) あるオブジェクトに対する参照の数。参照カウントが0になったとき、そのオブジェクトは破棄されます。参照カウントは通常は Python のコード上には現れませんが、 {\hyperref[\detokenize{glossary:term-cpython}]{\sphinxtermref{\DUrole{xref,std,std-term}{CPython}}}} 実装の重要な要素です。 \sphinxcode{\sphinxupquote{sys}} モジュールは、プログラマーが任意のオブジェクトの参照カウントを知るための \sphinxcode{\sphinxupquote{getrefcount()}} 関数を提供しています。 \item[{regular package\index{regular package@\spxentry{regular package}|spxpagem}\phantomsection\label{\detokenize{glossary:term-regular-package}}}] \leavevmode 伝統的な、 \sphinxcode{\sphinxupquote{\_\_init\_\_.py}} ファイルを含むディレクトリとしての {\hyperref[\detokenize{glossary:term-package}]{\sphinxtermref{\DUrole{xref,std,std-term}{package}}}}。 {\hyperref[\detokenize{glossary:term-namespace-package}]{\sphinxtermref{\DUrole{xref,std,std-term}{namespace package}}}} を参照してください。 \item[{\_\_slots\_\_\index{\_\_slots\_\_@\spxentry{\_\_slots\_\_}|spxpagem}\phantomsection\label{\detokenize{glossary:term-slots}}}] \leavevmode クラス内での宣言で、インスタンス属性の領域をあらかじめ定義しておき、インスタンス辞書を排除することで、メモリを節約します。これはよく使われるテクニックですが、正しく扱うには少しトリッキーなので、稀なケース、例えばメモリが死活問題となるアプリケーションでインスタンスが大量に存在する、といったときを除き、使わないのがベストです。 \item[{sequence\index{sequence@\spxentry{sequence}|spxpagem}\phantomsection\label{\detokenize{glossary:term-sequence}}}] \leavevmode (シーケンス) 整数インデクスによる効率的な要素アクセスを {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} 特殊メソッドを通じてサポートし、長さを返す {\hyperref[\detokenize{reference/datamodel:object.__len__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_len\_\_()}}}}} メソッドを定義した {\hyperref[\detokenize{glossary:term-iterable}]{\sphinxtermref{\DUrole{xref,std,std-term}{iterable}}}} です。組み込みシーケンス型には、 \sphinxcode{\sphinxupquote{list}}, \sphinxcode{\sphinxupquote{str}}, \sphinxcode{\sphinxupquote{tuple}}, \sphinxcode{\sphinxupquote{bytes}} などがあります。 \sphinxcode{\sphinxupquote{dict}} は {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} と {\hyperref[\detokenize{reference/datamodel:object.__len__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_len\_\_()}}}}} もサポートしますが、検索の際に整数ではなく任意の {\hyperref[\detokenize{glossary:term-immutable}]{\sphinxtermref{\DUrole{xref,std,std-term}{immutable}}}} なキーを使うため、シーケンスではなくマッピング (mapping) とみなされているので注意してください。 The \sphinxcode{\sphinxupquote{collections.abc.Sequence}} abstract base class defines a much richer interface that goes beyond just {\hyperref[\detokenize{reference/datamodel:object.__getitem__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_getitem\_\_()}}}}} and {\hyperref[\detokenize{reference/datamodel:object.__len__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_len\_\_()}}}}}, adding \sphinxcode{\sphinxupquote{count()}}, \sphinxcode{\sphinxupquote{index()}}, {\hyperref[\detokenize{reference/datamodel:object.__contains__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_contains\_\_()}}}}}, and {\hyperref[\detokenize{reference/datamodel:object.__reversed__}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{\_\_reversed\_\_()}}}}}. Types that implement this expanded interface can be registered explicitly using \sphinxcode{\sphinxupquote{register()}}. \item[{set comprehension\index{set comprehension@\spxentry{set comprehension}|spxpagem}\phantomsection\label{\detokenize{glossary:term-set-comprehension}}}] \leavevmode A compact way to process all or part of the elements in an iterable and return a set with the results. \sphinxcode{\sphinxupquote{results = \{c for c in 'abracadabra' if c not in 'abc'\}}} generates the set of strings \sphinxcode{\sphinxupquote{\{'r', 'd'\}}}. See {\hyperref[\detokenize{reference/expressions:comprehensions}]{\sphinxcrossref{\DUrole{std,std-ref}{リスト、集合、辞書の表示}}}}. \item[{single dispatch\index{single dispatch@\spxentry{single dispatch}|spxpagem}\phantomsection\label{\detokenize{glossary:term-single-dispatch}}}] \leavevmode {\hyperref[\detokenize{glossary:term-generic-function}]{\sphinxtermref{\DUrole{xref,std,std-term}{generic function}}}} の一種で実装は一つの引数の型により選択されます。 \item[{slice\index{slice@\spxentry{slice}|spxpagem}\phantomsection\label{\detokenize{glossary:term-slice}}}] \leavevmode (スライス) 一般に {\hyperref[\detokenize{glossary:term-sequence}]{\sphinxtermref{\DUrole{xref,std,std-term}{シーケンス}}}} の一部を含むオブジェクト。スライスは、添字表記 \sphinxcode{\sphinxupquote{{[}{]}}} で与えられた複数の数の間にコロンを書くことで作られます。例えば、 \sphinxcode{\sphinxupquote{variable\_name{[}1:3:5{]}}} です。角括弧 (添字) 記号は \sphinxcode{\sphinxupquote{slice}} オブジェクトを内部で利用しています。 \item[{special method\index{special method@\spxentry{special method}|spxpagem}\phantomsection\label{\detokenize{glossary:term-special-method}}}] \leavevmode \index{special@\spxentry{special}!method@\spxentry{method}}\index{method@\spxentry{method}!special@\spxentry{special}}\ignorespaces (特殊メソッド) ある型に特定の操作、例えば加算をするために Python から暗黙に呼び出されるメソッド。この種類のメソッドは、メソッド名の最初と最後にアンダースコア 2 つがついています。特殊メソッドについては {\hyperref[\detokenize{reference/datamodel:specialnames}]{\sphinxcrossref{\DUrole{std,std-ref}{特殊メソッド名}}}} で解説されています。 \item[{statement\index{statement@\spxentry{statement}|spxpagem}\phantomsection\label{\detokenize{glossary:term-statement}}}] \leavevmode (文) 文はスイート (コードの"ブロック") に不可欠な要素です。文は {\hyperref[\detokenize{glossary:term-expression}]{\sphinxtermref{\DUrole{xref,std,std-term}{式}}}} かキーワードから構成されるもののどちらかです。後者には {\hyperref[\detokenize{reference/compound_stmts:if}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{if}}}}}、{\hyperref[\detokenize{reference/compound_stmts:while}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{while}}}}}、{\hyperref[\detokenize{reference/compound_stmts:for}]{\sphinxcrossref{\sphinxcode{\sphinxupquote{for}}}}} があります。 \item[{text encoding\index{text encoding@\spxentry{text encoding}|spxpagem}\phantomsection\label{\detokenize{glossary:term-text-encoding}}}] \leavevmode A string in Python is a sequence of Unicode code points (in range \sphinxcode{\sphinxupquote{U+0000}}\sphinxhyphen{}\sphinxhyphen{}\sphinxcode{\sphinxupquote{U+10FFFF}}). To store or transfer a string, it needs to be serialized as a sequence of bytes. Serializing a string into a sequence of bytes is known as "encoding", and recreating the string from the sequence of bytes is known as "decoding". There are a variety of different text serialization \DUrole{xref,std,std-ref}{codecs}, which are collectively referred to as "text encodings". \item[{text file\index{text file@\spxentry{text file}|spxpagem}\phantomsection\label{\detokenize{glossary:term-text-file}}}] \leavevmode (テキストファイル) \sphinxcode{\sphinxupquote{str}} オブジェクトを読み書きできる {\hyperref[\detokenize{glossary:term-file-object}]{\sphinxtermref{\DUrole{xref,std,std-term}{file object}}}} です。 しばしば、テキストファイルは実際にバイト指向のデータストリームにアクセスし、 {\hyperref[\detokenize{glossary:term-text-encoding}]{\sphinxtermref{\DUrole{xref,std,std-term}{テキストエンコーディング}}}} を自動的に行います。 テキストファイルの例は、 \sphinxcode{\sphinxupquote{sys.stdin}}, \sphinxcode{\sphinxupquote{sys.stdout}}, \sphinxcode{\sphinxupquote{io.StringIO}} インスタンスなどをテキストモード (\sphinxcode{\sphinxupquote{'r'}} or \sphinxcode{\sphinxupquote{'w'}}) で開いたファイルです。 {\hyperref[\detokenize{glossary:term-bytes-like-object}]{\sphinxtermref{\DUrole{xref,std,std-term}{bytes\sphinxhyphen{}like オブジェクト}}}} を読み書きできるファイルオブジェクトについては、 {\hyperref[\detokenize{glossary:term-binary-file}]{\sphinxtermref{\DUrole{xref,std,std-term}{バイナリファイル}}}} も参照してください。 \item[{triple\sphinxhyphen{}quoted string\index{triple\sphinxhyphen{}quoted string@\spxentry{triple\sphinxhyphen{}quoted string}|spxpagem}\phantomsection\label{\detokenize{glossary:term-triple-quoted-string}}}] \leavevmode (三重クォート文字列) 3つの連続したクォート記号(")かアポストロフィー(')で囲まれた文字列。通常の(一重)クォート文字列に比べて表現できる文字列に違いはありませんが、幾つかの理由で有用です。1つか2つの連続したクォート記号をエスケープ無しに書くことができますし、行継続文字(\textbackslash{})を使わなくても複数行にまたがることができるので、ドキュメンテーション文字列を書く時に特に便利です。 \item[{type\index{type@\spxentry{type}|spxpagem}\phantomsection\label{\detokenize{glossary:term-type}}}] \leavevmode (型) Python オブジェクトの型はオブジェクトがどのようなものかを決めます。あらゆるオブジェクトは型を持っています。オブジェクトの型は \sphinxcode{\sphinxupquote{\_\_class\_\_}} 属性でアクセスしたり、\sphinxcode{\sphinxupquote{type(obj)}} で取得したり出来ます。 \item[{type alias\index{type alias@\spxentry{type alias}|spxpagem}\phantomsection\label{\detokenize{glossary:term-type-alias}}}] \leavevmode (型エイリアス) 型の別名で、型を識別子に代入して作成します。 型エイリアスは {\hyperref[\detokenize{glossary:term-type-hint}]{\sphinxtermref{\DUrole{xref,std,std-term}{型ヒント}}}} を単純化するのに有用です。例えば: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{def} \PYG{n+nf}{remove\PYGZus{}gray\PYGZus{}shades}\PYG{p}{(} \PYG{n}{colors}\PYG{p}{:} \PYG{n+nb}{list}\PYG{p}{[}\PYG{n+nb}{tuple}\PYG{p}{[}\PYG{n+nb}{int}\PYG{p}{,} \PYG{n+nb}{int}\PYG{p}{,} \PYG{n+nb}{int}\PYG{p}{]}\PYG{p}{]}\PYG{p}{)} \PYG{o}{\PYGZhy{}}\PYG{o}{\PYGZgt{}} \PYG{n+nb}{list}\PYG{p}{[}\PYG{n+nb}{tuple}\PYG{p}{[}\PYG{n+nb}{int}\PYG{p}{,} \PYG{n+nb}{int}\PYG{p}{,} \PYG{n+nb}{int}\PYG{p}{]}\PYG{p}{]}\PYG{p}{:} \PYG{k}{pass} \end{sphinxVerbatim} これは次のようにより読みやすくできます: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{Color} \PYG{o}{=} \PYG{n+nb}{tuple}\PYG{p}{[}\PYG{n+nb}{int}\PYG{p}{,} \PYG{n+nb}{int}\PYG{p}{,} \PYG{n+nb}{int}\PYG{p}{]} \PYG{k}{def} \PYG{n+nf}{remove\PYGZus{}gray\PYGZus{}shades}\PYG{p}{(}\PYG{n}{colors}\PYG{p}{:} \PYG{n+nb}{list}\PYG{p}{[}\PYG{n}{Color}\PYG{p}{]}\PYG{p}{)} \PYG{o}{\PYGZhy{}}\PYG{o}{\PYGZgt{}} \PYG{n+nb}{list}\PYG{p}{[}\PYG{n}{Color}\PYG{p}{]}\PYG{p}{:} \PYG{k}{pass} \end{sphinxVerbatim} 機能の説明がある \sphinxcode{\sphinxupquote{typing}} と \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 484@\spxentry{PEP 484}}\sphinxhref{https://www.python.org/dev/peps/pep-0484}{\sphinxstylestrong{PEP 484}} を参照してください。 \item[{type hint\index{type hint@\spxentry{type hint}|spxpagem}\phantomsection\label{\detokenize{glossary:term-type-hint}}}] \leavevmode (型ヒント) 変数、クラス属性、関数のパラメータや返り値の期待される型を指定する {\hyperref[\detokenize{glossary:term-annotation}]{\sphinxtermref{\DUrole{xref,std,std-term}{annotation}}}} です。 型ヒントは必須ではなく Python では強制ではありませんが、静的型解析ツールにとって有用であり、IDE のコード補完とリファクタリングの手助けになります。 グローバル変数、クラス属性、関数で、ローカル変数でないものの型ヒントは \sphinxcode{\sphinxupquote{typing.get\_type\_hints()}} で取得できます。 機能の説明がある \sphinxcode{\sphinxupquote{typing}} と \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 484@\spxentry{PEP 484}}\sphinxhref{https://www.python.org/dev/peps/pep-0484}{\sphinxstylestrong{PEP 484}} を参照してください。 \item[{universal newlines\index{universal newlines@\spxentry{universal newlines}|spxpagem}\phantomsection\label{\detokenize{glossary:term-universal-newlines}}}] \leavevmode テキストストリームの解釈法の一つで、以下のすべてを行末と認識します: Unix の行末規定 \sphinxcode{\sphinxupquote{'\textbackslash{}n'}}、Windows の規定 \sphinxcode{\sphinxupquote{'\textbackslash{}r\textbackslash{}n'}}、古い Macintosh の規定 \sphinxcode{\sphinxupquote{'\textbackslash{}r'}}。利用法について詳しくは、 \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 278@\spxentry{PEP 278}}\sphinxhref{https://www.python.org/dev/peps/pep-0278}{\sphinxstylestrong{PEP 278}} と \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 3116@\spxentry{PEP 3116}}\sphinxhref{https://www.python.org/dev/peps/pep-3116}{\sphinxstylestrong{PEP 3116}} 、さらに \sphinxcode{\sphinxupquote{bytes.splitlines()}} も参照してください。 \item[{variable annotation\index{variable annotation@\spxentry{variable annotation}|spxpagem}\phantomsection\label{\detokenize{glossary:term-variable-annotation}}}] \leavevmode (変数アノテーション) 変数あるいはクラス属性の {\hyperref[\detokenize{glossary:term-annotation}]{\sphinxtermref{\DUrole{xref,std,std-term}{annotation}}}} 。 変数あるいはクラス属性に注釈を付けたときは、代入部分は任意です: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{k}{class} \PYG{n+nc}{C}\PYG{p}{:} \PYG{n}{field}\PYG{p}{:} \PYG{l+s+s1}{\PYGZsq{}}\PYG{l+s+s1}{annotation}\PYG{l+s+s1}{\PYGZsq{}} \end{sphinxVerbatim} 変数アノテーションは通常は {\hyperref[\detokenize{glossary:term-type-hint}]{\sphinxtermref{\DUrole{xref,std,std-term}{型ヒント}}}} のために使われます: 例えば、この変数は \sphinxcode{\sphinxupquote{int}} の値を取ることを期待されています: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYG{n}{count}\PYG{p}{:} \PYG{n+nb}{int} \PYG{o}{=} \PYG{l+m+mi}{0} \end{sphinxVerbatim} 変数アノテーションの構文については {\hyperref[\detokenize{reference/simple_stmts:annassign}]{\sphinxcrossref{\DUrole{std,std-ref}{注釈付き代入文 (annotated assignment statements)}}}} 節で解説しています。 この機能について解説している {\hyperref[\detokenize{glossary:term-function-annotation}]{\sphinxtermref{\DUrole{xref,std,std-term}{function annotation}}}}, \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 484@\spxentry{PEP 484}}\sphinxhref{https://www.python.org/dev/peps/pep-0484}{\sphinxstylestrong{PEP 484}}, \index{Python Enhancement Proposals@\spxentry{Python Enhancement Proposals}!PEP 526@\spxentry{PEP 526}}\sphinxhref{https://www.python.org/dev/peps/pep-0526}{\sphinxstylestrong{PEP 526}} を参照してください。 \item[{virtual environment\index{virtual environment@\spxentry{virtual environment}|spxpagem}\phantomsection\label{\detokenize{glossary:term-virtual-environment}}}] \leavevmode (仮想環境) 協調的に切り離された実行環境です。これにより Python ユーザとアプリケーションは同じシステム上で動いている他の Python アプリケーションの挙動に干渉することなく Python パッケージのインストールと更新を行うことができます。 \sphinxcode{\sphinxupquote{venv}} を参照してください。 \item[{virtual machine\index{virtual machine@\spxentry{virtual machine}|spxpagem}\phantomsection\label{\detokenize{glossary:term-virtual-machine}}}] \leavevmode (仮想マシン) 完全にソフトウェアにより定義されたコンピュータ。 Python の仮想マシンは、バイトコードコンパイラが出力した {\hyperref[\detokenize{glossary:term-bytecode}]{\sphinxtermref{\DUrole{xref,std,std-term}{バイトコード}}}} を実行します。 \item[{Zen of Python\index{Zen of Python@\spxentry{Zen of Python}|spxpagem}\phantomsection\label{\detokenize{glossary:term-zen-of-python}}}] \leavevmode (Pythonの悟り) Python を理解し利用する上での導きとなる、Python の設計原則と哲学をリストにしたものです。対話プロンプトで "\sphinxcode{\sphinxupquote{import this}}" とするとこのリストを読めます。 \end{description} \phantomsection\label{\detokenize{about::doc}} \chapter{このドキュメントについて} \label{\detokenize{about:about-these-documents}} このドキュメントは、 Python のドキュメントを主要な目的として作られた ドキュメントプロセッサの \sphinxhref{http://sphinx-doc.org/}{Sphinx} を利用して、 \sphinxhref{http://docutils.sourceforge.net/rst.html}{reStructuredText} 形式のソースから生成されました。 ドキュメントとそのツール群の開発は、Python 自身と同様に完全にボランティアの努力です。 もしあなたが貢献したいなら、どのようにすればよいかについて \DUrole{xref,std,std-ref}{reporting\sphinxhyphen{}bugs} ページをご覧下さい。 新しいボランティアはいつでも歓迎です! (訳注: 日本語訳の問題については、 GitHub 上の \sphinxhref{https://github.com/python-doc-ja/python-doc-ja/issues}{Issue Tracker} で報告をお願いします。) 多大な感謝を: \begin{itemize} \item {} Fred L. Drake, Jr., オリジナルの Python ドキュメントツールセットの作成者で、ドキュメントの多くを書きました。 \item {} \sphinxhref{http://docutils.sourceforge.net/}{Docutils} プロジェクト. reStructuredText と docutils ツールセットを作成しました。 \item {} Fredrik Lundh for his Alternative Python Reference project from which Sphinx got many good ideas. \end{itemize} \section{Pythonドキュメント 貢献者} \label{\detokenize{about:contributors-to-the-python-documentation}} 多くの方々が Python 言語、Python 標準ライブラリ、そして Python ドキュメンテーションに貢献してくれています。ソース配布物の \sphinxhref{https://github.com/python/cpython/tree/3.9/Misc/ACKS}{Misc/ACKS} に、それら貢献してくれた人々を部分的にではありますがリストアップしてあります。 Python コミュニティからの情報提供と貢献がなければこの素晴らしいドキュメンテーションは生まれませんでした \sphinxhyphen{}\sphinxhyphen{} ありがとう! \phantomsection\label{\detokenize{license::doc}} \chapter{歴史とライセンス} \label{\detokenize{license:history-and-license}}\label{\detokenize{license:id1}} \section{Python の歴史} \label{\detokenize{license:history-of-the-software}} Python は 1990 年代の始め、オランダにある Stichting Mathematisch Centrum (CWI, \sphinxurl{https://www.cwi.nl/} 参照) で Guido van Rossum によって ABC と呼ばれる言語の後継言語として生み出されました。その後多くの人々が Python に貢献していますが、 Guido は今日でも Python 製作者の先頭に立っています。 1995 年、 Guido は米国ヴァージニア州レストンにある Corporation for National Reserch Initiatives (CNRI, \sphinxurl{https://www.cnri.reston.va.us/} 参照) で Python の開発に携わり、いくつかのバージョンをリリースしました。 2000 年 3 月、 Guido と Python のコア開発チームは BeOpen.com に移り、 BeOpen PythonLabs チームを結成しました。同年 10 月、 PythonLabs チームは Digital Creations (現在の Zope Corporation, \sphinxurl{https://www.zope.org/} 参照) に移りました。そして 2001 年、 Python に関する知的財産を保有するための非営利組織 Python Software Foundation (PSF、 \sphinxurl{https://www.python.org/psf/} 参照) を立ち上げました。このとき Zope Corporation は PSF の賛助会員になりました。 Python のリリースは全てオープンソース (オープンソースの定義は \sphinxurl{https://opensource.org/} を参照してください) です。歴史的にみて、ごく一部を除くほとんどの Python リリースは GPL 互換になっています; 各リリースについては下表にまとめてあります。 \begin{savenotes}\sphinxattablestart \centering \begin{tabulary}{\linewidth}[t]{|T|T|T|T|T|} \hline \sphinxstyletheadfamily リリース &\sphinxstyletheadfamily ベース &\sphinxstyletheadfamily 西暦年 &\sphinxstyletheadfamily 権利 &\sphinxstyletheadfamily GPL 互換 \\ \hline 0.9.0 \sphinxhyphen{} 1.2 & n/a & 1991\sphinxhyphen{}1995 & CWI & yes \\ \hline 1.3 \sphinxhyphen{} 1.5.2 & 1.2 & 1995\sphinxhyphen{}1999 & CNRI & yes \\ \hline 1.6 & 1.5.2 & 2000 & CNRI & no \\ \hline 2.0 & 1.6 & 2000 & BeOpen.com & no \\ \hline 1.6.1 & 1.6 & 2001 & CNRI & no \\ \hline 2.1 & 2.0+1.6.1 & 2001 & PSF & no \\ \hline 2.0.1 & 2.0+1.6.1 & 2001 & PSF & yes \\ \hline 2.1.1 & 2.1+2.0.1 & 2001 & PSF & yes \\ \hline 2.1.2 & 2.1.1 & 2002 & PSF & yes \\ \hline 2.1.3 & 2.1.2 & 2002 & PSF & yes \\ \hline 2.2 以降 & 2.1.1 & 2001\sphinxhyphen{}現在 & PSF & yes \\ \hline \end{tabulary} \par \sphinxattableend\end{savenotes} \begin{sphinxadmonition}{note}{注釈:} 「GPL 互換」という表現は、Python が GPL で配布されているという意味ではありません。Python のライセンスは全て、GPL と違い、変更したバージョンを配布する際に変更をオープンソースにしなくてもかまいません。GPL 互換のライセンスの下では、GPL でリリースされている他のソフトウェアと Python を組み合わせられますが、それ以外のライセンスではそうではありません。 \end{sphinxadmonition} Guido の指示の下、これらのリリースを可能にしてくださった多くのボランティアのみなさんに感謝します。 \section{Terms and conditions for accessing or otherwise using Python} \label{\detokenize{license:terms-and-conditions-for-accessing-or-otherwise-using-python}} Python software and documentation are licensed under the {\hyperref[\detokenize{license:psf-license}]{\sphinxcrossref{\DUrole{std,std-ref}{PSF License Agreement}}}}. Starting with Python 3.8.6, examples, recipes, and other code in the documentation are dual licensed under the PSF License Agreement and the {\hyperref[\detokenize{license:bsd0}]{\sphinxcrossref{\DUrole{std,std-ref}{Zero\sphinxhyphen{}Clause BSD license}}}}. Some software incorporated into Python is under different licenses. The licenses are listed with code falling under that license. See {\hyperref[\detokenize{license:otherlicenses}]{\sphinxcrossref{\DUrole{std,std-ref}{Licenses and Acknowledgements for Incorporated Software}}}} for an incomplete list of these licenses. \subsection{PSF LICENSE AGREEMENT FOR PYTHON 3.9.16} \label{\detokenize{license:psf-license-agreement-for-python-release}}\label{\detokenize{license:psf-license}}\begin{sphinxalltt} 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using Python 3.9.16 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty\sphinxhyphen{}free, world\sphinxhyphen{}wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 3.9.16 alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright © 2001\sphinxhyphen{}2023 Python Software Foundation; All Rights Reserved" are retained in Python 3.9.16 alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 3.9.16 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 3.9.16. 4. PSF is making Python 3.9.16 available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 3.9.16 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.9.16 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.9.16, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using Python 3.9.16, Licensee agrees to be bound by the terms and conditions of this License Agreement. \end{sphinxalltt} \subsection{BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0} \label{\detokenize{license:beopen-com-license-agreement-for-python-2-0}} BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 \begin{sphinxVerbatim}[commandchars=\\\{\}] 1. This LICENSE AGREEMENT is between BeOpen.com (\PYGZdq{}BeOpen\PYGZdq{}), having an office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization (\PYGZdq{}Licensee\PYGZdq{}) accessing and otherwise using this software in source or binary form and its associated documentation (\PYGZdq{}the Software\PYGZdq{}). 2. Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby grants Licensee a non\PYGZhy{}exclusive, royalty\PYGZhy{}free, world\PYGZhy{}wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use the Software alone or in any derivative version, provided, however, that the BeOpen Python License is retained in the Software, alone or in any derivative version prepared by Licensee. 3. BeOpen is making the Software available to Licensee on an \PYGZdq{}AS IS\PYGZdq{} basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 5. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 6. This License Agreement shall be governed by and interpreted in all respects by the law of the State of California, excluding conflict of law provisions. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between BeOpen and Licensee. This License Agreement does not grant permission to use BeOpen trademarks or trade names in a trademark sense to endorse or promote products or services of Licensee, or any third party. As an exception, the \PYGZdq{}BeOpen Python\PYGZdq{} logos available at http://www.pythonlabs.com/logos.html may be used according to the permissions granted on that web page. 7. By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms and conditions of this License Agreement. \end{sphinxVerbatim} \subsection{CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1} \label{\detokenize{license:cnri-license-agreement-for-python-1-6-1}} \begin{sphinxVerbatim}[commandchars=\\\{\}] 1. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191 (\PYGZdq{}CNRI\PYGZdq{}), and the Individual or Organization (\PYGZdq{}Licensee\PYGZdq{}) accessing and otherwise using Python 1.6.1 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee a nonexclusive, royalty\PYGZhy{}free, world\PYGZhy{}wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 1.6.1 alone or in any derivative version, provided, however, that CNRI\PYGZsq{}s License Agreement and CNRI\PYGZsq{}s notice of copyright, i.e., \PYGZdq{}Copyright © 1995\PYGZhy{}2001 Corporation for National Research Initiatives; All Rights Reserved\PYGZdq{} are retained in Python 1.6.1 alone or in any derivative version prepared by Licensee. Alternately, in lieu of CNRI\PYGZsq{}s License Agreement, Licensee may substitute the following text (omitting the quotes): \PYGZdq{}Python 1.6.1 is made available subject to the terms and conditions in CNRI\PYGZsq{}s License Agreement. This Agreement together with Python 1.6.1 may be located on the Internet using the following unique, persistent identifier (known as a handle): 1895.22/1013. This Agreement may also be obtained from a proxy server on the Internet using the following URL: http://hdl.handle.net/1895.22/1013.\PYGZdq{} 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 1.6.1. 4. CNRI is making Python 1.6.1 available to Licensee on an \PYGZdq{}AS IS\PYGZdq{} basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. This License Agreement shall be governed by the federal intellectual property law of the United States, including without limitation the federal copyright law, and, to the extent such U.S. federal law does not apply, by the law of the Commonwealth of Virginia, excluding Virginia\PYGZsq{}s conflict of law provisions. Notwithstanding the foregoing, with regard to derivative works based on Python 1.6.1 that incorporate non\PYGZhy{}separable material that was previously distributed under the GNU General Public License (GPL), the law of the Commonwealth of Virginia shall govern this License Agreement only as to issues arising under or with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between CNRI and Licensee. This License Agreement does not grant permission to use CNRI trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By clicking on the \PYGZdq{}ACCEPT\PYGZdq{} button where indicated, or by copying, installing or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and conditions of this License Agreement. \end{sphinxVerbatim} \subsection{CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2} \label{\detokenize{license:cwi-license-agreement-for-python-0-9-0-through-1-2}} \begin{sphinxVerbatim}[commandchars=\\\{\}] Copyright © 1991 \PYGZhy{} 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All rights reserved. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. \end{sphinxVerbatim} \subsection{ZERO\sphinxhyphen{}CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3.9.16 DOCUMENTATION} \label{\detokenize{license:zero-clause-bsd-license-for-code-in-the-python-release-documentation}}\label{\detokenize{license:bsd0}} \begin{sphinxVerbatim}[commandchars=\\\{\}] Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED \PYGZdq{}AS IS\PYGZdq{} AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. \end{sphinxVerbatim} \section{Licenses and Acknowledgements for Incorporated Software} \label{\detokenize{license:licenses-and-acknowledgements-for-incorporated-software}}\label{\detokenize{license:otherlicenses}} This section is an incomplete, but growing list of licenses and acknowledgements for third\sphinxhyphen{}party software incorporated in the Python distribution. \subsection{Mersenne Twister} \label{\detokenize{license:mersenne-twister}} The \sphinxcode{\sphinxupquote{\_random}} module includes code based on a download from \sphinxurl{http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html}. The following are the verbatim comments from the original code: \begin{sphinxVerbatim}[commandchars=\\\{\}] A C\PYGZhy{}program for MT19937, with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto. Before using, initialize the state by using init\PYGZus{}genrand(seed) or init\PYGZus{}by\PYGZus{}array(init\PYGZus{}key, key\PYGZus{}length). Copyright (C) 1997 \PYGZhy{} 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \PYGZdq{}AS IS\PYGZdq{} AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Any feedback is very welcome. http://www.math.sci.hiroshima\PYGZhy{}u.ac.jp/\PYGZti{}m\PYGZhy{}mat/MT/emt.html email: m\PYGZhy{}mat @ math.sci.hiroshima\PYGZhy{}u.ac.jp (remove space) \end{sphinxVerbatim} \subsection{ソケット} \label{\detokenize{license:sockets}} The \sphinxcode{\sphinxupquote{socket}} module uses the functions, \sphinxcode{\sphinxupquote{getaddrinfo()}}, and \sphinxcode{\sphinxupquote{getnameinfo()}}, which are coded in separate source files from the WIDE Project, \sphinxurl{http://www.wide.ad.jp/}. \begin{sphinxVerbatim}[commandchars=\\\{\}] Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS\PYGZsq{}\PYGZsq{} AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \end{sphinxVerbatim} \subsection{Asynchronous socket services} \label{\detokenize{license:asynchronous-socket-services}} The \sphinxcode{\sphinxupquote{asynchat}} and \sphinxcode{\sphinxupquote{asyncore}} modules contain the following notice: \begin{sphinxVerbatim}[commandchars=\\\{\}] Copyright 1996 by Sam Rushing All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Sam Rushing not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. \end{sphinxVerbatim} \subsection{Cookie management} \label{\detokenize{license:cookie-management}} The \sphinxcode{\sphinxupquote{http.cookies}} module contains the following notice: \begin{sphinxVerbatim}[commandchars=\\\{\}] Copyright 2000 by Timothy O\PYGZsq{}Malley \PYGZlt{}timo@alum.mit.edu\PYGZgt{} All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Timothy O\PYGZsq{}Malley not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. Timothy O\PYGZsq{}Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL Timothy O\PYGZsq{}Malley BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. \end{sphinxVerbatim} \subsection{Execution tracing} \label{\detokenize{license:execution-tracing}} The \sphinxcode{\sphinxupquote{trace}} module contains the following notice: \begin{sphinxVerbatim}[commandchars=\\\{\}] portions copyright 2001, Autonomous Zones Industries, Inc., all rights... err... reserved and offered to the public under the terms of the Python 2.2 license. Author: Zooko O\PYGZsq{}Whielacronx http://zooko.com/ mailto:zooko@zooko.com Copyright 2000, Mojam Media, Inc., all rights reserved. Author: Skip Montanaro Copyright 1999, Bioreason, Inc., all rights reserved. Author: Andrew Dalke Copyright 1995\PYGZhy{}1997, Automatrix, Inc., all rights reserved. Author: Skip Montanaro Copyright 1991\PYGZhy{}1995, Stichting Mathematisch Centrum, all rights reserved. Permission to use, copy, modify, and distribute this Python software and its associated documentation for any purpose without fee is hereby granted, provided that the above copyright notice appears in all copies, and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of neither Automatrix, Bioreason or Mojam Media be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. \end{sphinxVerbatim} \subsection{UUencode and UUdecode functions} \label{\detokenize{license:uuencode-and-uudecode-functions}} The \sphinxcode{\sphinxupquote{uu}} module contains the following notice: \begin{sphinxVerbatim}[commandchars=\\\{\}] Copyright 1994 by Lance Ellinghouse Cathedral City, California Republic, United States of America. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Lance Ellinghouse not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Modified by Jack Jansen, CWI, July 1995: \PYGZhy{} Use binascii module to do the actual line\PYGZhy{}by\PYGZhy{}line conversion between ascii and binary. This results in a 1000\PYGZhy{}fold speedup. The C version is still 5 times faster, though. \PYGZhy{} Arguments more compliant with Python standard \end{sphinxVerbatim} \subsection{XML Remote Procedure Calls} \label{\detokenize{license:xml-remote-procedure-calls}} The \sphinxcode{\sphinxupquote{xmlrpc.client}} module contains the following notice: \begin{sphinxVerbatim}[commandchars=\\\{\}] The XML\PYGZhy{}RPC client interface is Copyright (c) 1999\PYGZhy{}2002 by Secret Labs AB Copyright (c) 1999\PYGZhy{}2002 by Fredrik Lundh By obtaining, using, and/or copying this software and/or its associated documentation, you agree that you have read, understood, and will comply with the following terms and conditions: Permission to use, copy, modify, and distribute this software and its associated documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appears in all copies, and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Secret Labs AB or the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT\PYGZhy{} ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. \end{sphinxVerbatim} \subsection{test\_epoll} \label{\detokenize{license:test-epoll}} \sphinxcode{\sphinxupquote{test\_epoll}} モジュールは次の告知を含んでいます: \begin{sphinxVerbatim}[commandchars=\\\{\}] Copyright (c) 2001\PYGZhy{}2006 Twisted Matrix Laboratories. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \PYGZdq{}Software\PYGZdq{}), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \PYGZdq{}AS IS\PYGZdq{}, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \end{sphinxVerbatim} \subsection{Select kqueue} \label{\detokenize{license:select-kqueue}} \sphinxcode{\sphinxupquote{select}} モジュールは kqueue インターフェースについての次の告知を含んでいます: \begin{sphinxVerbatim}[commandchars=\\\{\}] Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS\PYGZsq{}\PYGZsq{} AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \end{sphinxVerbatim} \subsection{SipHash24} \label{\detokenize{license:siphash24}} The file \sphinxcode{\sphinxupquote{Python/pyhash.c}} contains Marek Majkowski' implementation of Dan Bernstein's SipHash24 algorithm. It contains the following note: \begin{sphinxVerbatim}[commandchars=\\\{\}] \PYGZlt{}MIT License\PYGZgt{} Copyright (c) 2013 Marek Majkowski \PYGZlt{}marek@popcount.org\PYGZgt{} Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \PYGZdq{}Software\PYGZdq{}), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. \PYGZlt{}/MIT License\PYGZgt{} Original location: https://github.com/majek/csiphash/ Solution inspired by code from: Samuel Neves (supercop/crypto\PYGZus{}auth/siphash24/little) djb (supercop/crypto\PYGZus{}auth/siphash24/little2) Jean\PYGZhy{}Philippe Aumasson (https://131002.net/siphash/siphash24.c) \end{sphinxVerbatim} \subsection{strtod と dtoa} \label{\detokenize{license:strtod-and-dtoa}} The file \sphinxcode{\sphinxupquote{Python/dtoa.c}}, which supplies C functions dtoa and strtod for conversion of C doubles to and from strings, is derived from the file of the same name by David M. Gay, currently available from \sphinxurl{http://www.netlib.org/fp/}. The original file, as retrieved on March 16, 2009, contains the following copyright and licensing notice: \begin{sphinxVerbatim}[commandchars=\\\{\}] /**************************************************************** * * The author of this software is David M. Gay. * * Copyright (c) 1991, 2000, 2001 by Lucent Technologies. * * Permission to use, copy, modify, and distribute this software for any * purpose without fee is hereby granted, provided that this entire notice * is included in all copies of any software which is or includes a copy * or modification of this software and in all copies of the supporting * documentation for such software. * * THIS SOFTWARE IS BEING PROVIDED \PYGZdq{}AS IS\PYGZdq{}, WITHOUT ANY EXPRESS OR IMPLIED * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. * ***************************************************************/ \end{sphinxVerbatim} \subsection{OpenSSL} \label{\detokenize{license:openssl}} The modules \sphinxcode{\sphinxupquote{hashlib}}, \sphinxcode{\sphinxupquote{posix}}, \sphinxcode{\sphinxupquote{ssl}}, \sphinxcode{\sphinxupquote{crypt}} use the OpenSSL library for added performance if made available by the operating system. Additionally, the Windows and macOS installers for Python may include a copy of the OpenSSL libraries, so we include a copy of the OpenSSL license here: \begin{sphinxVerbatim}[commandchars=\\\{\}] LICENSE ISSUES ============== The OpenSSL toolkit stays under a dual license, i.e. both the conditions of the OpenSSL License and the original SSLeay license apply to the toolkit. See below for the actual license texts. Actually both licenses are BSD\PYGZhy{}style Open Source licenses. In case of any license issues related to OpenSSL please contact openssl\PYGZhy{}core@openssl.org. OpenSSL License \PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{} /* ==================================================================== * Copyright (c) 1998\PYGZhy{}2008 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * \PYGZdq{}This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)\PYGZdq{} * * 4. The names \PYGZdq{}OpenSSL Toolkit\PYGZdq{} and \PYGZdq{}OpenSSL Project\PYGZdq{} must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl\PYGZhy{}core@openssl.org. * * 5. Products derived from this software may not be called \PYGZdq{}OpenSSL\PYGZdq{} * nor may \PYGZdq{}OpenSSL\PYGZdq{} appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * \PYGZdq{}This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)\PYGZdq{} * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS\PYGZsq{}\PYGZsq{} AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ Original SSLeay License \PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{} /* Copyright (C) 1995\PYGZhy{}1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non\PYGZhy{}commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young\PYGZsq{}s, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * \PYGZdq{}This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)\PYGZdq{} * The word \PYGZsq{}cryptographic\PYGZsq{} can be left out if the rouines from the library * being used are not cryptographic related :\PYGZhy{}). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * \PYGZdq{}This product includes software written by Tim Hudson (tjh@cryptsoft.com)\PYGZdq{} * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS\PYGZsq{}\PYGZsq{} AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ \end{sphinxVerbatim} \subsection{expat} \label{\detokenize{license:expat}} The \sphinxcode{\sphinxupquote{pyexpat}} extension is built using an included copy of the expat sources unless the build is configured \sphinxcode{\sphinxupquote{\sphinxhyphen{}\sphinxhyphen{}with\sphinxhyphen{}system\sphinxhyphen{}expat}}: \begin{sphinxVerbatim}[commandchars=\\\{\}] Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd and Clark Cooper Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \PYGZdq{}Software\PYGZdq{}), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \PYGZdq{}AS IS\PYGZdq{}, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \end{sphinxVerbatim} \subsection{libffi} \label{\detokenize{license:libffi}} The \sphinxcode{\sphinxupquote{\_ctypes}} extension is built using an included copy of the libffi sources unless the build is configured \sphinxcode{\sphinxupquote{\sphinxhyphen{}\sphinxhyphen{}with\sphinxhyphen{}system\sphinxhyphen{}libffi}}: \begin{sphinxVerbatim}[commandchars=\\\{\}] Copyright (c) 1996\PYGZhy{}2008 Red Hat, Inc and others. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ``Software\PYGZsq{}\PYGZsq{}), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ``AS IS\PYGZsq{}\PYGZsq{}, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \end{sphinxVerbatim} \subsection{zlib} \label{\detokenize{license:zlib}} The \sphinxcode{\sphinxupquote{zlib}} extension is built using an included copy of the zlib sources if the zlib version found on the system is too old to be used for the build: \begin{sphinxVerbatim}[commandchars=\\\{\}] Copyright (C) 1995\PYGZhy{}2011 Jean\PYGZhy{}loup Gailly and Mark Adler This software is provided \PYGZsq{}as\PYGZhy{}is\PYGZsq{}, without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean\PYGZhy{}loup Gailly Mark Adler jloup@gzip.org madler@alumni.caltech.edu \end{sphinxVerbatim} \subsection{cfuhash} \label{\detokenize{license:cfuhash}} The implementation of the hash table used by the \sphinxcode{\sphinxupquote{tracemalloc}} で使用しているハッシュテーブルの実装は、cfuhashプロジェクトのものに基づきます: \begin{sphinxVerbatim}[commandchars=\\\{\}] Copyright (c) 2005 Don Owens All rights reserved. This code is released under the BSD license: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \PYGZdq{}AS IS\PYGZdq{} AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \end{sphinxVerbatim} \subsection{libmpdec} \label{\detokenize{license:libmpdec}} The \sphinxcode{\sphinxupquote{\_decimal}} module is built using an included copy of the libmpdec library unless the build is configured \sphinxcode{\sphinxupquote{\sphinxhyphen{}\sphinxhyphen{}with\sphinxhyphen{}system\sphinxhyphen{}libmpdec}}: \begin{sphinxVerbatim}[commandchars=\\\{\}] Copyright (c) 2008\PYGZhy{}2020 Stefan Krah. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \PYGZdq{}AS IS\PYGZdq{} AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \end{sphinxVerbatim} \subsection{W3C C14N test suite} \label{\detokenize{license:w3c-c14n-test-suite}} The C14N 2.0 test suite in the \sphinxcode{\sphinxupquote{test}} package (\sphinxcode{\sphinxupquote{Lib/test/xmltestdata/c14n\sphinxhyphen{}20/}}) was retrieved from the W3C website at \sphinxurl{https://www.w3.org/TR/xml-c14n2-testcases/} and is distributed under the 3\sphinxhyphen{}clause BSD license: \begin{sphinxVerbatim}[commandchars=\\\{\}] Copyright (c) 2013 W3C(R) (MIT, ERCIM, Keio, Beihang), All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the original copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the W3C nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \PYGZdq{}AS IS\PYGZdq{} AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \end{sphinxVerbatim} \phantomsection\label{\detokenize{copyright::doc}} \chapter{Copyright} \label{\detokenize{copyright:copyright}} Python and this documentation is: Copyright © 2001\sphinxhyphen{}2023 Python Software Foundation. All rights reserved. Copyright © 2000 BeOpen.com. All rights reserved. Copyright © 1995\sphinxhyphen{}2000 Corporation for National Research Initiatives. All rights reserved. Copyright © 1991\sphinxhyphen{}1995 Stichting Mathematisch Centrum. All rights reserved. \bigskip\hrule\bigskip ライセンスおよび許諾に関する完全な情報は、 {\hyperref[\detokenize{license:history-and-license}]{\sphinxcrossref{\DUrole{std,std-ref}{歴史とライセンス}}}} を参照してください。 \renewcommand{\indexname}{索引} \printindex \end{document}