"inspect" — 活動中のオブジェクトの情報を取得する
************************************************

バージョン 2.1 で追加.

**ソースコード:** Lib/inspect.py

======================================================================

"inspect" は、活動中のオブジェクト (モジュール、クラス、メソッド、関数
、トレースバック、フレームオブジェクト、コードオブジェクトなど) から情
報を取得する関数を定義しており、クラスの内容を調べたり、メソッドのソー
スコードを取得したり、関数の引数リストを取り出して整形したり、詳細なト
レースバックを表示するのに必要な情報を取得したりするために利用できます
。

このモジュールの機能は4種類に分類することができます。型チェック、ソー
スコードの情報取得、クラスや関数からの情報取得、インタープリタのスタッ
ク情報の調査です。


型とメンバー
============

The "getmembers()" function retrieves the members of an object such as
a class or module. The sixteen functions whose names begin with 「is」
are mainly provided as convenient choices for the second argument to
"getmembers()". They also help you determine when you can expect to
find the following special attributes:

+-------------+-------------------+-----------------------------+---------+
| 型          | 属性              | 説明                        | Notes   |
+=============+===================+=============================+=========+
| module      | __doc__           | ドキュメント文字列          |         |
+-------------+-------------------+-----------------------------+---------+
|             | __file__          | ファイル名 (組み込みモジュ  |         |
|             |                   | ールには存在しません)       |         |
+-------------+-------------------+-----------------------------+---------+
| クラス      | __doc__           | ドキュメント文字列          |         |
+-------------+-------------------+-----------------------------+---------+
|             | __module__        | クラスを定義しているモジュ  |         |
|             |                   | ールの名前                  |         |
+-------------+-------------------+-----------------------------+---------+
| メソッド    | __doc__           | ドキュメント文字列          |         |
+-------------+-------------------+-----------------------------+---------+
|             | __name__          | メソッドの定義名            |         |
+-------------+-------------------+-----------------------------+---------+
|             | im_class          | class object that asked for | (1)     |
|             |                   | this method                 |         |
+-------------+-------------------+-----------------------------+---------+
|             | im_func or        | メソッドを実装している関数  |         |
|             | __func__          | オブジェクト                |         |
+-------------+-------------------+-----------------------------+---------+
|             | im_self or        | メソッドに結合しているイン  |         |
|             | __self__          | スタンス、または "None"     |         |
+-------------+-------------------+-----------------------------+---------+
| function    | __doc__           | ドキュメント文字列          |         |
+-------------+-------------------+-----------------------------+---------+
|             | __name__          | 関数の定義名                |         |
+-------------+-------------------+-----------------------------+---------+
|             | func_code         | 関数をコンパイルしたバイト  |         |
|             |                   | コード (*bytecode*) を格納  |         |
|             |                   | するコードオブジェ クト     |         |
+-------------+-------------------+-----------------------------+---------+
|             | func_defaults     | tuple of any default values |         |
|             |                   | for arguments               |         |
+-------------+-------------------+-----------------------------+---------+
|             | func_doc          | (same as __doc__)           |         |
+-------------+-------------------+-----------------------------+---------+
|             | func_globals      | 関数が定義されたグローバル  |         |
|             |                   | 名前空間                    |         |
+-------------+-------------------+-----------------------------+---------+
|             | func_name         | (same as __name__)          |         |
+-------------+-------------------+-----------------------------+---------+
| ジェネレー  | __iter__          | defined to support          |         |
| タ          |                   | iteration over container    |         |
+-------------+-------------------+-----------------------------+---------+
|             | close             | raises new GeneratorExit    |         |
|             |                   | exception inside the        |         |
|             |                   | generator to terminate the  |         |
|             |                   | iteration                   |         |
+-------------+-------------------+-----------------------------+---------+
|             | gi_code           | code object                 |         |
+-------------+-------------------+-----------------------------+---------+
|             | gi_frame          | frame object or possibly    |         |
|             |                   | "None" once the generator   |         |
|             |                   | has been exhausted          |         |
+-------------+-------------------+-----------------------------+---------+
|             | gi_running        | set to 1 when generator is  |         |
|             |                   | executing, 0 otherwise      |         |
+-------------+-------------------+-----------------------------+---------+
|             | next              | return the next item from   |         |
|             |                   | the container               |         |
+-------------+-------------------+-----------------------------+---------+
|             | send              | resumes the generator and   |         |
|             |                   | 「sends」 a value that      |         |
|             |                   | becomes the result of the   |         |
|             |                   | current yield-expression    |         |
+-------------+-------------------+-----------------------------+---------+
|             | throw             | used to raise an exception  |         |
|             |                   | inside the generator        |         |
+-------------+-------------------+-----------------------------+---------+
| traceback   | tb_frame          | このレベルのフレームオブジ  |         |
|             |                   | ェクト                      |         |
+-------------+-------------------+-----------------------------+---------+
|             | tb_lasti          | 最後に実行しようとしたバイ  |         |
|             |                   | トコード中のインストラクシ  |         |
|             |                   | ョンを示すインデッ クス     |         |
+-------------+-------------------+-----------------------------+---------+
|             | tb_lineno         | 現在の Python ソースコード  |         |
|             |                   | の行番号                    |         |
+-------------+-------------------+-----------------------------+---------+
|             | tb_next           | このオブジェクトの内側 (こ  |         |
|             |                   | のレベルから呼び出された)   |         |
|             |                   | のトレースバックオ ブジェク |         |
|             |                   | ト                          |         |
+-------------+-------------------+-----------------------------+---------+
| フレーム    | f_back            | 外側 (このフレームを呼び出  |         |
|             |                   | した) のフレームオブジェク  |         |
|             |                   | ト                          |         |
+-------------+-------------------+-----------------------------+---------+
|             | f_builtins        | このフレームで参照している  |         |
|             |                   | 組み込み名前空間            |         |
+-------------+-------------------+-----------------------------+---------+
|             | f_code            | このフレームで実行している  |         |
|             |                   | コードオブジェクト          |         |
+-------------+-------------------+-----------------------------+---------+
|             | f_exc_traceback   | traceback if raised in this |         |
|             |                   | frame, or "None"            |         |
+-------------+-------------------+-----------------------------+---------+
|             | f_exc_type        | exception type if raised in |         |
|             |                   | this frame, or "None"       |         |
+-------------+-------------------+-----------------------------+---------+
|             | f_exc_value       | exception value if raised   |         |
|             |                   | in this frame, or "None"    |         |
+-------------+-------------------+-----------------------------+---------+
|             | f_globals         | このフレームで参照している  |         |
|             |                   | グローバル名前空間          |         |
+-------------+-------------------+-----------------------------+---------+
|             | f_lasti           | 最後に実行しようとしたバイ  |         |
|             |                   | トコード中のインストラクシ  |         |
|             |                   | ョンを示すインデッ クス     |         |
+-------------+-------------------+-----------------------------+---------+
|             | f_lineno          | 現在の Python ソースコード  |         |
|             |                   | の行番号                    |         |
+-------------+-------------------+-----------------------------+---------+
|             | f_locals          | このフレームで参照している  |         |
|             |                   | ローカル名前空間            |         |
+-------------+-------------------+-----------------------------+---------+
|             | f_restricted      | 制限実行モードなら1、それ以 |         |
|             |                   | 外なら0                     |         |
+-------------+-------------------+-----------------------------+---------+
|             | f_trace           | このフレームのトレース関数  |         |
|             |                   | 、または "None"             |         |
+-------------+-------------------+-----------------------------+---------+
| コード      | co_argcount       | number of arguments (not    |         |
|             |                   | including * or ** args)     |         |
+-------------+-------------------+-----------------------------+---------+
|             | co_code           | コンパイルされたバイトコー  |         |
|             |                   | ドそのままの文字列          |         |
+-------------+-------------------+-----------------------------+---------+
|             | co_consts         | バイトコード中で使用してい  |         |
|             |                   | る定数のタプル              |         |
+-------------+-------------------+-----------------------------+---------+
|             | co_filename       | コードオブジェクトを生成し  |         |
|             |                   | たファイルのファイル名      |         |
+-------------+-------------------+-----------------------------+---------+
|             | co_firstlineno    | Python ソースコードの先頭行 |         |
+-------------+-------------------+-----------------------------+---------+
|             | co_flags          | bitmap: 1=optimized "|"     |         |
|             |                   | 2=newlocals "|" 4=*arg "|"  |         |
|             |                   | 8=**arg                     |         |
+-------------+-------------------+-----------------------------+---------+
|             | co_lnotab         | 行番号からバイトコードイン  |         |
|             |                   | デックスへの変換表を文字列  |         |
|             |                   | にエンコードしたも の       |         |
+-------------+-------------------+-----------------------------+---------+
|             | co_name           | コードオブジェクトが定義さ  |         |
|             |                   | れたときの名前              |         |
+-------------+-------------------+-----------------------------+---------+
|             | co_names          | ローカル変数名のタプル      |         |
+-------------+-------------------+-----------------------------+---------+
|             | co_nlocals        | ローカル変数の数            |         |
+-------------+-------------------+-----------------------------+---------+
|             | co_stacksize      | 必要とされる仮想マシンのス  |         |
|             |                   | タックスペース              |         |
+-------------+-------------------+-----------------------------+---------+
|             | co_varnames       | 引数名とローカル変数名のタ  |         |
|             |                   | プル                        |         |
+-------------+-------------------+-----------------------------+---------+
| 組み込み    | __doc__           | ドキュメント文字列          |         |
+-------------+-------------------+-----------------------------+---------+
|             | __name__          | 関数、メソッドの元々の名前  |         |
+-------------+-------------------+-----------------------------+---------+
|             | __self__          | メソッドが結合しているイン  |         |
|             |                   | スタンス、または "None"     |         |
+-------------+-------------------+-----------------------------+---------+

Note:

1. バージョン 2.2 で変更: "im_class" used to refer to the class
   that defined the method.

inspect.getmembers(object[, predicate])

   オブジェクトの全メンバーを、(名前, 値) の組み合わせのリストで返しま
   す。リストはメンバー名でソートされています。*predicate* が指定され
   ている場合、predicate の戻り値が真となる値のみを返します。

   注釈: "getmembers()" does not return metaclass attributes when
     the argument is a class (this behavior is inherited from the
     "dir()" function).

inspect.getmoduleinfo(path)

   Return a tuple of values that describe how Python will interpret
   the file identified by *path* if it is a module, or "None" if it
   would not be identified as a module.  The return tuple is "(name,
   suffix, mode, module_type)", where *name* is the name of the module
   without the name of any enclosing package, *suffix* is the trailing
   part of the file name (which may not be a dot-delimited extension),
   *mode* is the "open()" mode that would be used ("'r'" or "'rb'"),
   and *module_type* is an integer giving the type of the module.
   *module_type* will have a value which can be compared to the
   constants defined in the "imp" module; see the documentation for
   that module for more information on module types.

   バージョン 2.6 で変更: Returns a *named tuple* "ModuleInfo(name,
   suffix, mode, module_type)".

inspect.getmodulename(path)

   Return the name of the module named by the file *path*, without
   including the names of enclosing packages.  This uses the same
   algorithm as the interpreter uses when searching for modules.  If
   the name cannot be matched according to the interpreter’s rules,
   "None" is returned.

inspect.ismodule(object)

   オブジェクトがモジュールの場合真を返します。

inspect.isclass(object)

   オブジェクトが組み込みか Python が生成したクラスの場合に真を返しま
   す。

inspect.ismethod(object)

   Return true if the object is a bound or unbound method written in
   Python.

inspect.isfunction(object)

   オブジェクトが Python 関数(*lambda* 式で生成されたものを含む) の場
   合に真を返します。

inspect.isgeneratorfunction(object)

   *object* が Python のジェネレータ関数の場合真を返します。

   バージョン 2.6 で追加.

inspect.isgenerator(object)

   *object* がジェネレータの場合真を返します。

   バージョン 2.6 で追加.

inspect.istraceback(object)

   オブジェクトがトレースバックの場合は真を返します。

inspect.isframe(object)

   オブジェクトがフレームの場合は真を返します。

inspect.iscode(object)

   オブジェクトがコードの場合は真を返します。

inspect.isbuiltin(object)

   オブジェクトが組み込み関数か束縛済みの組み込みメソッドの場合に真を
   返します。

inspect.isroutine(object)

   オブジェクトがユーザ定義か組み込みの関数またはメソッドの場合は真を
   返します。

inspect.isabstract(object)

   *object* が抽象規定型 (ABC) であるときに真を返します。

   バージョン 2.6 で追加.

inspect.ismethoddescriptor(object)

   オブジェクトがメソッドデスクリプタであり、 "ismethod()",
   "isclass()", "isfunction()", "isbuiltin()" でない場合に真を返します
   。

   This is new as of Python 2.2, and, for example, is true of
   "int.__add__". An object passing this test has a "__get__()" method
   but not a "__set__()" method, but beyond that the set of attributes
   varies.  A "__name__" attribute is usually sensible, and "__doc__"
   often is.

   Methods implemented via descriptors that also pass one of the other
   tests return false from the "ismethoddescriptor()" test, simply
   because the other tests promise more – you can, e.g., count on
   having the "im_func" attribute (etc) when an object passes
   "ismethod()".

inspect.isdatadescriptor(object)

   オブジェクトがデータデスクリプタの場合に真を返します。

   データデスクリプタは "__get__" および "__set__" 属性の両方を持ちま
   す。データデスクリプタの例は (Python 上で定義された) プロパティや
   getset やメンバーです。後者のふたつは C で定義されており、個々の型
   に特有のテストも行います。そのため、Python の実装よりもより確実です
   。通常、データデスクリプタは "__name__" や "__doc__"  属性を持ちま
   す (プロパティ、 getset 、メンバーは両方の属性を持っています) が、
   保証されているわけではありません。

   バージョン 2.3 で追加.

inspect.isgetsetdescriptor(object)

   オブジェクトが getset デスクリプタの場合に真を返します。

   getset とは、拡張モジュールで "PyGetSetDef" 構造体を用いて定義され
   た属性のことです。そのような型を持たない Python 実装の場合は、この
   メソッドは常に "False" を返します。

   バージョン 2.5 で追加.

inspect.ismemberdescriptor(object)

   オブジェクトがメンバーデスクリプタの場合に真を返します。

   メンバーデスクリプタとは、拡張モジュールで "PyMemberDef" 構造体を用
   いて定義された属性のことです。そのような型を持たない Python 実装の
   場合は、このメソッドは常に "False" を返します。

   バージョン 2.5 で追加.


ソースコードの情報取得
======================

inspect.getdoc(object)

   Get the documentation string for an object, cleaned up with
   "cleandoc()".

inspect.getcomments(object)

   Return in a single string any lines of comments immediately
   preceding the object’s source code (for a class, function, or
   method), or at the top of the Python source file (if the object is
   a module).

inspect.getfile(object)

   オブジェクトを定義している (テキストまたはバイナリの) ファイルの名
   前を返します。オブジェクトが組み込みモジュール、クラス、関数の場合
   は "TypeError" 例外が発生します。

inspect.getmodule(object)

   オブジェクトを定義しているモジュールを推測します。

inspect.getsourcefile(object)

   オブジェクトを定義している Python ソースファイルの名前を返します。
   オブジェクトが組み込みのモジュール、クラス、関数の場合には、
   "TypeError" 例外が発生します。

inspect.getsourcelines(object)

   Return a list of source lines and starting line number for an
   object. The argument may be a module, class, method, function,
   traceback, frame, or code object.  The source code is returned as a
   list of the lines corresponding to the object and the line number
   indicates where in the original source file the first line of code
   was found.  An "IOError" is raised if the source code cannot be
   retrieved.

inspect.getsource(object)

   Return the text of the source code for an object. The argument may
   be a module, class, method, function, traceback, frame, or code
   object.  The source code is returned as a single string.  An
   "IOError" is raised if the source code cannot be retrieved.

inspect.cleandoc(doc)

   コードブロックと位置を合わせるためのインデントを docstring から削除
   します。

   先頭行の行頭の空白文字は全て削除されます。 2行目以降では全行で同じ
   数の行頭の空白文字が、削除できるだけ削除されます。 その後、先頭と末
   尾の空白行が削除され、全てのタブが空白に展開されます。

   バージョン 2.6 で追加.


クラスと関数
============

inspect.getclasstree(classes[, unique])

   リストで指定したクラスの継承関係から、ネストしたリストを作成します
   。ネストしたリストには、直前の要素から派生したクラスが格納されます
   。各要素は長さ2のタプルで、クラスと基底クラスのタプルを格納していま
   す。*unique* が真の場合、各クラスは戻り値のリスト内に一つだけしか格
   納されません。真でなければ、多重継承を利用したクラスとその派生クラ
   スは複数回格納される場合があります。

inspect.getargspec(func)

   Get the names and default values of a Python function’s arguments.
   A tuple of four things is returned: "(args, varargs, keywords,
   defaults)". *args* is a list of the argument names (it may contain
   nested lists). *varargs* and *keywords* are the names of the "*"
   and "**" arguments or "None". *defaults* is a tuple of default
   argument values or "None" if there are no default arguments; if
   this tuple has *n* elements, they correspond to the last *n*
   elements listed in *args*.

   バージョン 2.6 で変更: Returns a *named tuple* "ArgSpec(args,
   varargs, keywords, defaults)".

inspect.getargvalues(frame)

   Get information about arguments passed into a particular frame. A
   tuple of four things is returned: "(args, varargs, keywords,
   locals)". *args* is a list of the argument names (it may contain
   nested lists). *varargs* and *keywords* are the names of the "*"
   and "**" arguments or "None". *locals* is the locals dictionary of
   the given frame.

   バージョン 2.6 で変更: Returns a *named tuple* "ArgInfo(args,
   varargs, keywords, locals)".

inspect.formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue, join])

   Format a pretty argument spec from the four values returned by
   "getargspec()".  The format* arguments are the corresponding
   optional formatting functions that are called to turn names and
   values into strings.

inspect.formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue, join])

   "getargvalues()" で取得した4つの値を読みやすく整形します。 format*
   引数はオプションで、名前と値を文字列に変換する整形関数を指定するこ
   とができます。

inspect.getmro(cls)

   *cls* クラスの基底クラス (*cls* 自身も含む) を、メソッドの優先順位
   順に並べたタプルを返します。結果のリスト内で各クラスは一度だけ格納
   されます。メソッドの優先順位はクラスの型によって異なります。非常に
   特殊なユーザ定義のメタクラスを使用していない限り、*cls* が戻り値の
   先頭要素となります。

inspect.getcallargs(func[, *args][, **kwds])

   *args* と *kwds* を、Python の関数もしくはメソッド *func* を呼び出
   した場合と同じように引数名に束縛します。束縛済みメソッド(bound
   method)の場合、最初の引数(慣習的に "self" という名前が付けられます)
   にも、関連づけられたインスタンスを束縛します。引数名 ("*" や "**"
   引数が存在すればその名前も) に *args* と *kwds* からの値をマップし
   た辞書を返します。*func* を正しく呼び出せない場合、つまり
   "func(*args, **kwds)" がシグネチャの不一致のために例外を投げるよう
   な場合には、それと同じ型で同じか似ているメッセージの例外を発生させ
   ます。例:

      >>> from inspect import getcallargs
      >>> def f(a, b=1, *pos, **named):
      ...     pass
      >>> getcallargs(f, 1, 2, 3)
      {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
      >>> getcallargs(f, a=2, x=4)
      {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
      >>> getcallargs(f)
      Traceback (most recent call last):
      ...
      TypeError: f() takes at least 1 argument (0 given)

   バージョン 2.7 で追加.


インタープリタスタック
======================

When the following functions return 「frame records,」 each record is
a tuple of six items: the frame object, the filename, the line number
of the current line, the function name, a list of lines of context
from the source code, and the index of the current line within that
list.

注釈: フレームレコードの最初の要素などのフレームオブジェクトへの参照
  を保存 すると、循環参照になってしまう場合があります。循環参照ができ
  ると、 Python の循環参照検出機能を有効にしていたとしても関連するオブ
  ジェク トが参照しているすべてのオブジェクトが解放されにくくなり、明
  示的に参 照を削除しないとメモリ消費量が増大する恐れがあります。参照
  の削除を Python の循環参照検出機能にまかせることもできますが、
  "finally" 節で 循環参照を解除すれば確実にフレーム (とそのローカル変
  数) は削除されま す。また、循環参照検出機能は Python のコンパイルオ
  プションや "gc.disable()" で無効とされている場合がありますので注意が
  必要です。 例:

     def handle_stackframe_without_leak():
         frame = inspect.currentframe()
         try:
             # do something with the frame
         finally:
             del frame

以下の関数でオプション引数 *context* には、戻り値のソース行リストに何
行分のソースを含めるかを指定します。ソース行リストには、実行中の行を中
心として指定された行数分のリストを返します。

inspect.getframeinfo(frame[, context])

   Get information about a frame or traceback object.  A 5-tuple is
   returned, the last five elements of the frame’s frame record.

   バージョン 2.6 で変更: Returns a *named tuple* "Traceback(filename,
   lineno, function, code_context, index)".

inspect.getouterframes(frame[, context])

   指定したフレームと、その外側の全フレームのフレームレコードを返しま
   す。外側のフレームとは *frame* が生成されるまでのすべての関数呼び出
   しを示します。戻り値のリストの先頭は *frame* のフレームレコードで、
   末尾の要素は *frame* のスタックにある最も外側のフレームのフレームレ
   コードとなります。

inspect.getinnerframes(traceback[, context])

   指定したフレームと、その内側の全フレームのフレームレコードを返しま
   す。内のフレームとは *frame* から続く一連の関数呼び出しを示します。
   戻り値のリストの先頭は *traceback* のフレームレコードで、末尾の要素
   は例外が発生した位置を示します。

inspect.currentframe()

   呼び出し元のフレームオブジェクトを返します。

   この関数はインタプリタの Python スタックフレームサポートに依存しま
   す。これは Python のすべての実装に存在している保証はありません。
   Python スタックフレームサポートのない環境では、この関数は "None" を
   返します。

inspect.stack([context])

   呼び出し元スタックのフレームレコードのリストを返します。最初の要素
   は呼び出し元のフレームレコードで、末尾の要素はスタックにある最も外
   側のフレームのフレームレコードとなります。

inspect.trace([context])

   実行中のフレームと処理中の例外が発生したフレームの間のフレームレコ
   ードのリストを返します。最初の要素は呼び出し元のフレームレコードで
   、末尾の要素は例外が発生した位置を示します。
