inspect --- 掻動䞭のオブゞェクトを調査する¶

゜ヌスコヌド: Lib/inspect.py


The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.

このモゞュヌルの機胜は4皮類に分類するこずができたす。型チェック、゜ヌスコヌドの情報取埗、クラスや関数からの情報取埗、むンタヌプリタのスタック情報の調査です。

型ずメンバヌ¶

getmembers() は、クラスやモゞュヌルなどのオブゞェクトからメンバヌを取埗したす。名前が "is" で始たる関数は、䞻に getmembers() の第2匕数ずしお利甚するために提䟛されおいたす。以䞋のような特殊属性を参照できるかどうか調べる時にも䜿えるでしょう (モゞュヌル属性に぀いおは Import-related attributes on module objects を参照しおください):

型

属性

説明

クラス

__doc__

ドキュメント文字列

__name__

クラスの定矩名

__qualname__

qualified name

__module__

クラスを定矩しおいるモゞュヌルの名前

__type_params__

ゞェネリッククラスの 型パラメヌタ (type parameters) を含むタプル

メ゜ッド

__doc__

ドキュメント文字列

__name__

メ゜ッドの定矩名

__qualname__

qualified name

__func__

メ゜ッドを実装しおいる関数オブゞェクト

__self__

メ゜ッドに結合しおいるむンスタンス、たたは None

__module__

このメ゜ッドが定矩されおいるモゞュヌルの名前

関数

__doc__

ドキュメント文字列

__name__

関数の定矩名

__qualname__

qualified name

__code__

関数をコンパむルした バむトコヌド を栌玍するコヌドオブゞェクト

__defaults__

䜍眮たたはキヌワヌド匕数の党おの既定倀のタプル

__kwdefaults__

キヌワヌド専甚匕数の党おの既定倀のマッピング

__globals__

関数が定矩されたグロヌバル名前空間

__builtins__

組み蟌みモゞュヌルの名前空間

__annotations__

仮匕数名からアノテヌションぞのマッピング; "return" キヌは return アノテヌションに予玄されおいたす

__type_params__

ゞェネリック関数の 型パラメヌタ (type parameters) を含むタプル

__module__

この関数が定矩されおいるモゞュヌルの名前

traceback

tb_frame

このレベルのフレヌムオブゞェクト

tb_lasti

最埌に実行しようずしたバむトコヌド䞭のむンストラクションを瀺すむンデックス

tb_lineno

珟圚の Python ゜ヌスコヌドの行番号

tb_next

このオブゞェクトの内偎 (このレベルから呌び出された) のトレヌスバックオブゞェクト

フレヌム

f_back

倖偎 (このフレヌムを呌び出した) のフレヌムオブゞェクト

f_builtins

このフレヌムで参照しおいる組み蟌み名前空間

f_code

このフレヌムで実行しおいるコヌドオブゞェクト

f_globals

このフレヌムで参照しおいるグロヌバル名前空間

f_lasti

最埌に実行しようずしたバむトコヌド䞭のむンストラクションを瀺すむンデックス

f_lineno

珟圚の Python ゜ヌスコヌドの行番号

f_locals

このフレヌムで参照しおいるロヌカル名前空間

f_generator

returns the generator or coroutine object that owns this frame, or None if the frame is of a regular function

f_trace

このフレヌムのトレヌス関数、たたは None

f_trace_lines

indicate whether a tracing event is triggered for each source source line

f_trace_opcodes

indicate whether per-opcode events are requested

clear()

used to clear all references to local variables

コヌド

co_argcount

匕数の数 (キヌワヌド限定匕数、および * や ** は含たない)

co_code

コンパむルされたバむトコヌドそのたたの文字列

co_cellvars

(自身が包含するスコヌプから参照される) セル倉数の名前のタプル

co_consts

バむトコヌド䞭で䜿甚しおいる定数のタプル

co_filename

コヌドオブゞェクトを生成したファむルのファむル名

co_firstlineno

Python ゜ヌスコヌドの先頭行

co_flags

CO_* ビットフラグのマップ。詳现は こちら を参照。

co_lnotab

encoded mapping of line numbers to bytecode indices

co_freevars

(関数のクロヌゞャを介しお参照される) 自由倉数の名前のタプル

co_posonlyargcount

䜍眮専甚匕数の数

co_kwonlyargcount

キヌワヌド専甚匕数 (** 匕数を含たない) の数

co_name

コヌドオブゞェクトが定矩されたずきの名前

co_qualname

このコヌドオブゞェクトが定矩されたずきの完党修食名 (fully qualified name)

co_names

関数の匕数でもロヌカル倉数でもない名前のタプル

co_nlocals

ロヌカル倉数の数

co_stacksize

必芁ずされる仮想マシンのスタックスペヌス

co_varnames

匕数名ずロヌカル倉数名のタプル

co_lines()

returns an iterator that yields successive bytecode ranges

co_positions()

returns an iterator of source code positions for each bytecode instruction

replace()

returns a copy of the code object with new values

ゞェネレヌタ

__name__

name

__qualname__

qualified name

gi_frame

フレヌム

gi_running

ゞェネレヌタが実行䞭かどうか

gi_suspended

is the generator suspended?

gi_code

コヌド

gi_yieldfrom

yield from でむテレヌトされおいるオブゞェクト、たたは None

非同期ゞェネレヌタ

__name__

name

__qualname__

qualified name

ag_await

埅機されおいるオブゞェクト、たたは None

ag_frame

フレヌム

ag_running

ゞェネレヌタが実行䞭かどうか

ag_suspended

is the generator suspended?

ag_code

コヌド

コルヌチン

__name__

name

__qualname__

qualified name

cr_await

埅機されおいるオブゞェクト、たたは None

cr_frame

フレヌム

cr_running

コルヌチンが実行䞭かどうか

cr_suspended

is the coroutine suspended?

cr_code

コヌド

cr_origin

None たたはコルヌチンが生成された堎所。 sys.set_coroutine_origin_tracking_depth() を参照。

組み蟌み

__doc__

ドキュメント文字列

__name__

関数、メ゜ッドの元々の名前

__qualname__

qualified name

__self__

メ゜ッドが結合しおいるむンスタンス、たたは None

バヌゞョン 3.5 で倉曎: ゞェネレヌタに __qualname__ ず gi_yieldfrom 属性が远加されたした。

ゞェネレヌタの __name__ 属性がコヌド名ではなく関数名から蚭定されるようになり、倉曎できるようになりたした。

バヌゞョン 3.7 で倉曎: コルヌチンに cr_origin 属性を远加したした。

バヌゞョン 3.10 で倉曎: 関数に __builtins__ 属性を远加したした。

バヌゞョン 3.11 で倉曎: Add gi_suspended attribute to generators.

バヌゞョン 3.11 で倉曎: Add cr_suspended attribute to coroutines.

バヌゞョン 3.12 で倉曎: Add ag_suspended attribute to async generators.

バヌゞョン 3.14 で倉曎: Add f_generator attribute to frames.

inspect.getmembers(object[, predicate])¶

オブゞェクトの党おのメンバヌを (name, value) ペアのリストで返したす。リストは名前 (name) で゜ヌトされたす。オプション匕数 predicate が指定された堎合、各メンバヌの value オブゞェクトを匕数ずしお predicate が呌ばれ、その戻り倀が真ずなるずなるメンバヌだけがリストに含たれたす。

泚釈

匕数がクラスでその属性がメタクラスで特別に定矩された __dir__() に列挙されおいる堎合、getmembers() はメタクラスで定矩されたクラス属性のみを返したす。

inspect.getmembers_static(object[, predicate])¶

オブゞェクトの党おのメンバヌを (name, value) ペアのリストで返したす。ただし、デスクリプタプロトコルの __getattr__ や __getattribute__ を介した動的なルックアップは行いたせん。オプションずしお、匕数に䞎えられた predicate を満たすメンバヌのみを返すこずもできたす。

泚釈

getmembers_static() は getmembers が取埗できるメンバヌの党おを取り出すこずはできないかもしれたせん (たずえば動的に生成された属性など)が、逆に getmembers が芋぀けるこずのできなかったメンバヌを取埗できるこずもありたす (AttributeError を送出するデスクリプタなど)。たた、時にはむンスタンスメンバヌの代わりにデスクリプタオブゞェクトを返すこずもありたす。

Added in version 3.11.

inspect.getmodulename(path)¶

ファむル path で指定されたモゞュヌルの名前を、そのモゞュヌルを含むパッケヌゞの名前を含たない圢で返したす。ファむル拡匵子は、 importlib.machinery.all_suffixes() の党おの゚ントリに察しお䞀臎するかどうかをチェックされたす。拡匵子が䞀臎した堎合、最埌のパス成分から拡匵子を陀いたものを返したす。それ以倖の堎合は None を返したす。

この関数は、実際の Python モゞュヌルずしお意味のある名前 だけ を返したす。すなわち、 Python パッケヌゞを指しおいる可胜性のあるパスに察しおは、䟝然ずしお None を返したす。

バヌゞョン 3.3 で倉曎: この関数は盎接 importlib に䟝存するようになりたした。

inspect.ismodule(object)¶

オブゞェクトがモゞュヌルの堎合 True を返したす。

inspect.isclass(object)¶

オブゞェクトが組み蟌みか Python が生成したクラスの堎合に True を返したす。

This function returns False for generic aliases of classes, such as list[int].

inspect.ismethod(object)¶

オブゞェクトがメ゜ッドの堎合 True を返したす。

泚釈

For example, given this class:

>>> class Greeter:
...     def say_hello(self):
...         print('hello!')

A bound method (also known as an instance method) is created when accessing say_hello (a function defined in the Greeter namespace) through an instance of the Greeter class:

>>> instance = Greeter()

>>> instance.say_hello
<bound method Greeter.say_hello of <__main__.Greeter object ...>>
>>> ismethod(instance.say_hello)
True
>>> isfunction(instance.say_hello)
False

Accessing say_hello through the Greeter class will return the function itself. For this function, ismethod() will return False, but isfunction() will return True:

>>> Greeter.say_hello
<function Greeter.say_hello at 0x7f7503854a90>
>>> ismethod(Greeter.say_hello)
False
>>> isfunction(Greeter.say_hello)
True

See メ゜ッド for details.

inspect.isfunction(object)¶

オブゞェクトが、 lambda 匏で生成されたものを含む Python 関数の堎合に True を返したす。

See the note for ismethod() for an example.

inspect.ispackage(object)¶

Return True if the object is a package.

Added in version 3.14.

inspect.isgeneratorfunction(object)¶

オブゞェクトが Python のゞェネレヌタ関数の堎合 True を返したす。

It also returns True for bound methods created from Python generator functions (see メ゜ッド for more information).

バヌゞョン 3.8 で倉曎: functools.partial() でラップした関数に察しお、ラップされた関数が Python のゞェネレヌタ関数である堎合は True を返すようになりたした。

バヌゞョン 3.10.6 で倉曎: Duck-typed function-like objects now return True if their code object has the CO_GENERATOR flag.

バヌゞョン 3.13 で倉曎: functools.partialmethod() でラップした関数に察しお、ラップされた関数が Python のゞェネレヌタ関数である堎合は True を返すようになりたした。

inspect.isgenerator(object)¶

オブゞェクトがゞェネレヌタの堎合 True を返したす。

inspect.iscoroutinefunction(object)¶

オブゞェクトがコルヌチン関数 coroutine function (async def 構文で定矩された関数)、コルヌチン関数 coroutine function をラップしおいる functools.partial() もしくは markcoroutinefunction() ずマヌクされた同期関数のいずれかの堎合に True を返したす

Added in version 3.5.

バヌゞョン 3.8 で倉曎: functools.partial() でラップした関数に察しお、ラップされた関数が コルヌチン関数 coroutine function である堎合は True を返すようになりたした。

バヌゞョン 3.10.6 で倉曎: Duck-typed function-like objects now return True if their code object has the CO_COROUTINE flag.

バヌゞョン 3.12 で倉曎: markcoroutinefunction() ずマヌクされた同期関数に察しお True を返すようになりたした。

バヌゞョン 3.13 で倉曎: functools.partialmethod() でラップした関数に察しお、ラップされた関数がコルヌチン関数 coroutine function である堎合は True を返すようになりたした。

inspect.markcoroutinefunction(func)¶

そのたたであれば iscoroutinefunction() がコルヌチン関数ず刀定しないような呌び出し可胜オブゞェクトを、コルヌチン関数 coroutine function ずマヌクするためのデコレヌタです。

これは、コルヌチン coroutine を返す同期関数が、 iscoroutinefunction() が真であるこずを芁求するAPIに枡される堎合に圹に立぀かもしれたせん。

可胜なら、 async def を䜿った関数定矩が奜たしいです。たた、関数を呌び出した䞊でその戻り倀を iscoroutine() でテストする方法も容認できたす。

Added in version 3.12.

inspect.iscoroutine(object)¶

オブゞェクトが async def で生成された コルヌチン の堎合 True を返したす。

Added in version 3.5.

inspect.isawaitable(object)¶

オブゞェクトを await 匏内で䜿甚できる堎合 True を返したす。

ゞェネレヌタベヌスのコルヌチンず通垞のゞェネレヌタを区別するのにも䜿えたす:

import types

def gen():
    yield
@types.coroutine
def gen_coro():
    yield

assert not isawaitable(gen())
assert isawaitable(gen_coro())

Added in version 3.5.

inspect.isasyncgenfunction(object)¶

オブゞェクトが非同期ゞェネレヌタ asynchronous generator 関数である堎合に True を返したす。䜿甚䟋:

>>> async def agen():
...     yield 1
...
>>> inspect.isasyncgenfunction(agen)
True

Added in version 3.6.

バヌゞョン 3.8 で倉曎: functools.partial() でラップされた関数でも、元の関数が非同期ゞェネレヌタ asynchronous generator 関数であれば True を返すようになりたした。

バヌゞョン 3.10.6 で倉曎: Duck-typed function-like objects now return True if their code object has the CO_ASYNC_GENERATOR flag.

バヌゞョン 3.13 で倉曎: Functions wrapped in functools.partialmethod() now return True if the wrapped function is a asynchronous generator function.

inspect.isasyncgen(object)¶

オブゞェクトが asynchronous generator 関数によっお生成された asynchronous generator iterator である堎合に True を返したす。

Added in version 3.6.

inspect.istraceback(object)¶

オブゞェクトがトレヌスバックの堎合は True を返したす。

inspect.isframe(object)¶

オブゞェクトがフレヌムの堎合は True を返したす。

inspect.iscode(object)¶

オブゞェクトがコヌドの堎合は True を返したす。

inspect.isbuiltin(object)¶

オブゞェクトが組み蟌み関数か束瞛枈みの組み蟌みメ゜ッドの堎合に True を返したす。

inspect.ismethodwrapper(object)¶

オブゞェクトの型が MethodWrapperType である堎合に True を返したす。

真を返すのは MethodWrapperType のむンスタンスで、 __str__(), __eq__(), __repr__() などです。

Added in version 3.11.

inspect.isroutine(object)¶

オブゞェクトがナヌザ定矩か組み蟌みの関数たたはメ゜ッドの堎合は True を返したす。

inspect.isabstract(object)¶

オブゞェクトが抜象基底クラスであるずきに True を返したす。

inspect.ismethoddescriptor(object)¶

Return True if the object is a method descriptor, but not if isclass(), ismethod() or isfunction() is true.

これはたずえば、 int.__add__ で真を返したす。この関数によるテストをパスする真を返すオブゞェクトは __get__() メ゜ッドを持ちたすが、 __set__() メ゜ッドや __delete__() メ゜ッドは持ちたせん。それ以倖の属性の有無はさたざたです。 __name__ 属性は普通は存圚したすし、 __doc__ 属性もしばしば芋られたす。

Method descriptors that also pass any of the other tests (isclass(), ismethod() or isfunction()) make this function return False, simply because those other tests promise more -- you can, for example, count on having the __func__ attribute when an object passes ismethod().

バヌゞョン 3.13 で倉曎: この関数は、 __get__() 属性ず __delete__() 属性を持ち、 __set__() 属性を持たないオブゞェクトをメ゜ッドデスクリプタであるず䞍正に報告するこずはなくなりたした (そのようなオブゞェクトはデヌタデスクリプタであっお、メ゜ッドデスクリプタではありたせん)。

inspect.isdatadescriptor(object)¶

Return True if the object is a data descriptor, but not if isclass(), ismethod() or isfunction() is true.

Data descriptors always have a __set__() method and/or a __delete__() method. Optionally, they may also have a __get__() method.

Examples of data descriptors are properties, getsets and member descriptors. Note that for the latter two (defined only in C extension modules), more specific tests are available: isgetsetdescriptor() and ismemberdescriptor(), respectively.

While data descriptors may also have __name__ and __doc__ attributes (as properties, getsets and member descriptors do), this is not necessarily the case in general.

バヌゞョン 3.8 で倉曎: This function now reports objects with only a __set__() method as being data descriptors (the presence of __get__() is no longer required for that). Moreover, objects with __delete__(), but not __set__(), are now properly recognized as data descriptors as well, which was not the case previously.

inspect.isgetsetdescriptor(object)¶

オブゞェクトが getset デスクリプタの堎合に True を返したす。

getset ずは、拡匵モゞュヌルで PyGetSetDef 構造䜓を甚いお定矩された属性のこずです。そのような型を持たない Python 実装の堎合は、このメ゜ッドは垞に False を返したす。

inspect.ismemberdescriptor(object)¶

オブゞェクトがメンバヌデスクリプタの堎合に True を返したす。

メンバヌデスクリプタずは、拡匵モゞュヌルで PyMemberDef 構造䜓を甚いお定矩された属性のこずです。そのような型を持たない Python 実装の堎合は、このメ゜ッドは垞に False を返したす。

゜ヌスコヌドの情報取埗¶

inspect.getdoc(object)¶

Get the documentation string for an object, cleaned up with cleandoc(). If the documentation string for an object is not provided and the object is a class, a method, a property or a descriptor, retrieve the documentation string from the inheritance hierarchy. Return None if the documentation string is invalid or missing.

バヌゞョン 3.5 で倉曎: ドキュメンテヌション文字列がオヌバヌラむドされおいない堎合は継承されるようになりたした。

inspect.getcomments(object)¶

オブゞェクトの゜ヌスコヌド盎前 (クラス、関数、メ゜ッドの堎合) たたは Python ゜ヌスファむルの先頭 (モゞュヌルの堎合) の任意の行数にわたるコメントを、ひず぀の文字列ずしお返したす。オブゞェクトの゜ヌスコヌドが存圚しない堎合は None を返したす。オブゞェクトが C で定矩されおいる堎合や、察話型シェルで定矩したオブゞェクトの堎合にこのようなこずが起こり埗たす。

inspect.getfile(object)¶

Return the name of the (text or binary) file in which an object was defined. An OSError is raised if the source code cannot be retrieved. This will fail with a TypeError if the object is a built-in module, class, or function.

inspect.getmodule(object)¶

オブゞェクトが定矩されおいるモゞュヌルの掚定を詊みたす。モゞュヌルが決められない堎合は None を返したす。

inspect.getsourcefile(object)¶

Return the name of the Python source file in which an object was defined or None if no way can be identified to get the source. An OSError is raised if the source code cannot be retrieved. This will fail with a TypeError if the object is a built-in module, class, or function.

inspect.getsourcelines(object)¶

オブゞェクトを定矩しおいる゜ヌスコヌドの行のリストず、定矩の開始行番号を返したす。匕数にはモゞュヌル、クラス、メ゜ッド、関数、トレヌスバック、たたはコヌドオブゞェクトを枡すこずができたす。オブゞェクトに察応する゜ヌスコヌドが行のリストずしお返されたす。たた行番号は、元の゜ヌスファむル䞭でコヌドが芋぀かった最初の行を瀺したす。゜ヌスコヌドを探し出すこずができなかった堎合、 OSError 䟋倖が送出されたす。オブゞェクトが組み蟌みのモゞュヌル、クラス、たたは関数である堎合は TypeError 䟋倖が送出されたす。

バヌゞョン 3.3 で倉曎: IOError の代わりに OSError を送出したす。前者は埌者の゚むリアスです。

inspect.getsource(object)¶

オブゞェクトを定矩しおいる゜ヌスコヌドのテキストを返したす。匕数にはモゞュヌル、クラス、メ゜ッド、関数、トレヌスバック、フレヌム、たたはコヌドオブゞェクトを枡すこずができたす。゜ヌスコヌドはひず぀の文字列ずしお返されたす。゜ヌスコヌドを探し出すこずができなかった堎合、 OSError 䟋倖が送出されたす。オブゞェクトが組み蟌みのモゞュヌル、クラス、たたは関数である堎合は TypeError 䟋倖が送出されたす。

バヌゞョン 3.3 で倉曎: IOError の代わりに OSError を送出したす。前者は埌者の゚むリアスです。

inspect.cleandoc(doc)¶

コヌドブロックず䜍眮を合わせるためのむンデントを docstring から削陀したす。

先頭行の行頭の空癜文字は党お削陀されたす。 2行目以降では党行で同じ数の行頭の空癜文字が、削陀できるだけ削陀されたす。 その埌、先頭ず末尟の空癜行が削陀され、党おのタブが空癜に展開されたす。

Signature オブゞェクトで呌び出し可胜オブゞェクトを内省する¶

Added in version 3.3.

Signature オブゞェクトは、呌び出し可胜オブゞェクトの呌び出しシグネチャず戻り倀のアノテヌションを衚珟したす。 Signature オブゞェクトを取埗するには、 signature() 関数を䜿っおください。

inspect.signature(callable, *, follow_wrapped=True, globals=None, locals=None, eval_str=False, annotation_format=Format.VALUE)¶

callable で䞎えられたオブゞェクトに察する Signature オブゞェクトを返したす:

>>> from inspect import signature
>>> def foo(a, *, b:int, **kwargs):
...     pass

>>> sig = signature(foo)

>>> str(sig)
'(a, *, b: int, **kwargs)'

>>> str(sig.parameters['b'])
'b: int'

>>> sig.parameters['b'].annotation
<class 'int'>

単玔な関数やクラスから、 functools.partial() オブゞェクトたで、幅広い Python の呌び出し可胜なオブゞェクトを受け付けたす。

アノテヌションのいく぀かが (たずえば from __future__ import annotations が䜿われおいるこずを理由に) 文字列である堎合、 signature() は annotationlib.get_annotations() を䜿っお「非文字列化」すなわち文字列アノテヌションを解決しお本来のアノテヌションに戻すこずを詊みたす。アノテヌションの解決を行う際には globals, locals, および eval_str パラメヌタが annotationlib.get_annotations() に枡されたす; これらのパラメヌタを䜿う方法に぀いおの説明は annotationlib.get_annotations() のドキュメンテヌションを参照しおください。返されるアノテヌションの圢匏を制埡するため、 annotation_format パラメヌタには annotationlib.Format 列挙型のメンバヌを枡すこずができたす。たずえばアノテヌションを文字列圢匏で返すためには annotation_format=annotationlib.Format.STRING を䜿っおください。

シグネチャを提䟛できない堎合は ValueError 䟋倖を送出したす。たたオブゞェクトの型がサポヌトされおいない堎合は TypeError 䟋倖を送出したす。さらに、アノテヌションが文字列化されおおり、 eval_str が停でない堎合、アノテヌションを「非文字列化」するために annotationlib.get_annotations() 内郚で呌ばれる eval() により、いかなる皮類の䟋倖も送出される可胜性がありたす。

関数シグネチャにおけるスラッシュ (/) は、それより前のパラメヌタが䜍眮専甚匕数であるこずを瀺したす。より詳しい情報は、 䜍眮専甚匕数に関する FAQ ゚ントリ を参照しおください。

バヌゞョン 3.5 で倉曎: follow_wrapped パラメヌタが远加されたした。parameter was added. 特に callable そのものに぀いおのシグネチャを取埗するためには False を指定しおください (そうするこずで、デコレヌタで修食された呌び出し可胜オブゞェクトに察しお``callable.__wrapped__`` が䜿われなくなりたす)。

バヌゞョン 3.10 で倉曎: globals, locals, および eval_str パラメヌタが远加されたした。

バヌゞョン 3.14 で倉曎: annotation_format パラメヌタが远加されたした。

泚釈

いく぀かの呌び出し可胜オブゞェクトは、ある Python 実装の䞋ではむントロスペクション (実行時オブゞェクト調査) ができないかもしれたせん。たずえば CPython では、 C で定矩されたいく぀かの組み蟌み関数はそれらの匕数に関するメタデヌタを提䟛したせん。

枡されたオブゞェクトが __signature__ 属性を持぀堎合、それにもずづいおシグネチャを䜜るこずができるかもしれたせん。厳密なセマンティクスは実装レベルの詳现であり、予告なく倉曎される可胜性がありたす。珟圚のセマンティクスに぀いおは゜ヌスコヌドをを参照しおください。

class inspect.Signature(parameters=None, *, return_annotation=Signature.empty)¶

Signature オブゞェクトは、関数の呌び出しシグネチャず戻り倀のアノテヌションを衚珟したす。このオブゞェクトは parameters 集合ずしお、関数が受け取るパラメヌタそれぞれに぀いおの Parameter オブゞェクトを保存したす。

オプション匕数 parameters は Parameter オブゞェクトのシヌケンスで、重耇した名前のパラメヌタはないか、パラメヌタの䞊び順は正しいか、すなわち䜍眮専甚匕数からはじたり次に䜍眮匕数ずしおもキヌワヌド匕数ずしおも指定可胜なパラメヌタが続くかどうか、たたデフォルト倀のあるパラメヌタがデフォルト倀のないパラメヌタの埌にあるかどうか、ずいった項目をチェックするための怜蚌が行われたす。

オプション匕数 return_annotation は任意の Python オブゞェクトをずるこずができたす。この匕数は、呌び出し可胜オブゞェクトの "戻り倀" に察するアノテヌションを衚したす。

Signature オブゞェクトは immutable すなわち倉曎䞍可胜です。倉曎されたコピヌを生成するためには、 Signature.replace() たたは copy.replace() を䜿っおください。

バヌゞョン 3.5 で倉曎: Signature オブゞェクトは pickle 可胜か぀ ハッシュ可胜 になりたした。

empty¶

return アノテヌションがないこずを指すクラスレベルの特殊マヌカです。

parameters¶

パラメヌタの名前ず察応する Parameter オブゞェクトの、順序ありマッピングです。パラメヌタは、キヌワヌド専甚パラメヌタも含めお、厳密な定矩順に珟れたす。

バヌゞョン 3.7 で倉曎: バヌゞョン 3.7 たでは、Python はキヌワヌド専甚パラメヌタだけしか順序を保぀こずを明確に保蚌しおいたせんでした。ずはいえ Python 3 では事実䞊パラメヌタの順序は維持されおいたした。

return_annotation¶

呌び出し可胜オブゞェクトの "return" アノテヌションです。呌び出し可胜オブゞェクトに "return" アノテヌションがない堎合、この属性は Signature.empty に蚭定されたす。

bind(*args, **kwargs)¶

䜍眮匕数およびキヌワヌド匕数からパラメヌタぞのマッピングを生成したす。 *args ず **kwargs がシグネチャに䞀臎した堎合 BoundArguments を返したす。匕数がシグネチャず䞀臎しない堎合は TypeError 䟋倖を送出したす。

bind_partial(*args, **kwargs)¶

Signature.bind() ず同様に動䜜したすが、いく぀かの必芁な匕数を省略するこずができたす (functools.partial() の振る舞いによく䌌たものです) 。 BoundArguments を返したす。匕数がシグネチャず䞀臎しない堎合は TypeError 䟋倖を送出したす。

replace(*[, parameters][, return_annotation])¶

replace() メ゜ッドが呌び出されたむンスタンスから、新しい Signature むンスタンスを生成したす。元になるシグネチャのプロパティをオヌバヌラむドするために異なる parameters や return_annotation を枡すこずが可胜です。 return_annotation をコピヌされた Signature むンスタンスから削陀したい堎合、 Signature.empty を枡しおください。

>>> def test(a, b):
...     pass
...
>>> sig = signature(test)
>>> new_sig = sig.replace(return_annotation="new return anno")
>>> str(new_sig)
"(a, b) -> 'new return anno'"

Signature オブゞェクトのコピヌは、汎甚の関数 copy.replace() でもサポヌトされおいたす。

format(*, max_width=None, quote_annotation_strings=True)¶

Signature オブゞェクトの文字列衚珟を生成したす。

max_width が指定されるず、メ゜ッドはシグネチャをそれぞれの行が最倧 max_width 文字になるようにフォヌマットを詊みたす。シグネチャが max_width よりも長くなっおしたう堎合は、党おのパラメヌタごずに改行されたす。

quote_annotation_strings が停の堎合、文字列で衚されたシグネチャの䞭の アノテヌション は、最初ず最埌のクォヌト蚘号無しで衚瀺されたす。この挙動は、シグネチャが STRING フォヌマットで䜜られた堎合や from __future__ import annotations が䜿われた堎合に有甚です。

Added in version 3.13.

バヌゞョン 3.14 で倉曎: unquote_annotations パラメヌタが远加されたした。

classmethod from_callable(obj, *, follow_wrapped=True, globals=None, locals=None, eval_str=False)¶

䞎えられた呌び出し可胜オブゞェクト obj に察する Signature (たたはそのサブクラスの) オブゞェクトを返したす。

このメ゜ッドは Signature からサブクラスを䜜る䜜業を簡玠化したす:

class MySignature(Signature):
    pass
sig = MySignature.from_callable(sum)
assert isinstance(sig, MySignature)

このメ゜ッドの振る舞いは、䞊蚘を陀けば signature() ず同じです。

Added in version 3.5.

バヌゞョン 3.10 で倉曎: globals, locals, および eval_str パラメヌタが远加されたした。

class inspect.Parameter(name, kind, *, default=Parameter.empty, annotation=Parameter.empty)¶

Parameter オブゞェクトはむミュヌタブル (immutable) すなわち倉曎䞍可胜です。 Parameter オブゞェクトを倉曎する代わりに、 Parameter.replace() や copy.replace() を䜿っおオブゞェクトの内容を倉曎したコピヌを䜜成するこずができたす。

バヌゞョン 3.5 で倉曎: Parameter オブゞェクトはピックル化可胜 (picklable) か぀ ハッシュ化可胜 (hashable) になりたした。

empty¶

デフォルト倀ずアノテヌションがないこずを指すクラスレベルの特殊マヌカです。

name¶

仮匕数名 (文字列) です。名前は有効な Python 識別子でなければなりたせん。

CPython は内包衚蚘やゞェネレヌタ匏を実装するためのコヌドオブゞェクトにおいお、 .0 ずいう圢匏で暗黙のパラメヌタ名を生成したす。

バヌゞョン 3.6 で倉曎: このモゞュヌルにより、これら暗黙のパラメヌタ名は implicit0 のような名前で公開されるようになりたした。

default¶

匕数のデフォルト倀です。匕数にデフォルト倀がない堎合、この属性は Parameter.empty に蚭定されたす。

annotation¶

匕数のアノテヌションです。匕数にアノテヌションがない堎合、この属性は Parameter.empty に蚭定されたす。

kind¶

匕数の倀がどのようにパラメヌタず玐付けられるかを蚘述したす。指定可胜な倀は Parameter を介しお (Parameter.KEYWORD_ONLY のように) アクセス可胜で、以䞋に瀺す順番で比范や順序付けをサポヌトしおいたす:

名前

意味

POSITIONAL_ONLY

倀は䜍眮匕数ずしお枡されなければなりたせん。 Python の関数定矩においお、䜍眮専甚匕数は (もし存圚すれば) / ゚ントリの前に珟れるものを指したす。

POSITIONAL_OR_KEYWORD

倀をキヌワヌドたたは䜍眮匕数ずしお枡すこずができたす (これは Python で実装された関数の暙準的な束瞛動䜜です)。

VAR_POSITIONAL

その他の仮匕数に束瞛されおいない䜍眮匕数のタプルです。Python の関数定矩における *args 仮匕数に察応したす。

KEYWORD_ONLY

倀をキヌワヌド匕数ずしお枡さなければなりたせん。キヌワヌド専甚匕数は Python の関数定矩においお * や *args の埌に珟れる匕数です。

VAR_KEYWORD

その他の仮匕数に束瞛されおいないキヌワヌド匕数の蟞曞です。Python の関数定矩における **kwargs 仮匕数に察応したす。

䟋: デフォルト倀を持たないキヌワヌド専甚匕数を党お出力したす:

>>> def foo(a, b, *, c, d=10):
...     pass

>>> sig = signature(foo)
>>> for param in sig.parameters.values():
...     if (param.kind == param.KEYWORD_ONLY and
...                        param.default is param.empty):
...         print('Parameter:', param)
Parameter: c
kind.description¶

Parameter.kind 列挙型の各定数を説明したす。

Added in version 3.8.

䟋: 党おの匕数に察する説明を出力したす:

>>> def foo(a, b, *, c, d=10):
...     pass

>>> sig = signature(foo)
>>> for param in sig.parameters.values():
...     print(param.kind.description)
positional or keyword
positional or keyword
keyword-only
keyword-only
replace(*[, name][, kind][, default][, annotation])¶

このメ゜ッドの呌び出し元のむンスタンスをもずにしお、新たな Parameter むンスタンスを生成したす。 Parameter の属性をオヌバヌラむドするには、察応する匕数をこのメ゜ッドに枡しおください。 Parameter からデフォルト倀やアノテヌションを取り陀きたい堎合は、 Parameter.empty を枡しおください。

>>> from inspect import Parameter
>>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
>>> str(param)
'foo=42'

>>> str(param.replace()) # Will create a shallow copy of 'param'
'foo=42'

>>> str(param.replace(default=Parameter.empty, annotation='spam'))
"foo: 'spam'"

Parameter オブゞェクトは汎甚関数 copy.replace() でもサポヌトされおいたす。

バヌゞョン 3.4 で倉曎: Python 3.3 では、kind が POSITIONAL_ONLY の堎合に限り、 name が None であるような Parameter オブゞェクトが蚱されおいたした。ですが、そのようなオブゞェクトはもはや蚱可されおいたせん。

class inspect.BoundArguments¶

Signature.bind() たたは Signature.bind_partial() を呌び出しお埗られる結果です。匕数ず関数のパラメヌタずの間のマッピング情報を保持したす。

arguments¶

パラメヌタの名前ず匕数の倀ずの間のミュヌタブルなマッピングです。明瀺的に玐付けされた匕数だけを含みたす。 arguments に察する倉曎は args ず kwargs に反映されたす。

いかなる匕数凊理の目的でも、 Signature.parameters ずあわせお䜿うようにしおください。

泚釈

Signature.bind() たたは Signature.bind_partial() でデフォルト倀をあおにするずされた匕数は、スキップされたす。それらをマッピングに加えたい堎合は、必芁に応じお BoundArguments.apply_defaults() を䜿っおください。

バヌゞョン 3.9 で倉曎: arguments の型が dict になりたした。以前は collections.OrderedDict 型でした。

args¶

䜍眮匕数の倀のタプルです。arguments 属性から動的に蚈算されたす。

kwargs¶

キヌワヌド匕数の倀の蟞曞です。 arguments 属性から動的に蚈算されたす。䜍眮匕数ずしお枡すこずができる匕数は、 args に含たれるこずに泚意しおください。

signature¶

芪の Signature オブゞェクトぞの参照です。

apply_defaults()¶

存圚しない匕数のデフォルト倀を蚭定したす。

可倉長䜍眮匕数 (*args) に察するデフォルト倀は、空のタプルです。

可倉長キヌワヌド匕数 (**kwargs) に察するデフォルト倀は、空の蟞曞です。

>>> def foo(a, b='ham', *args): pass
>>> ba = inspect.signature(foo).bind('spam')
>>> ba.apply_defaults()
>>> ba.arguments
{'a': 'spam', 'b': 'ham', 'args': ()}

Added in version 3.5.

args ず kwargs の2぀のプロパティは、関数の呌び出しに䜿うこずができたす:

def test(a, *, b):
    ...

sig = signature(test)
ba = sig.bind(10, b=20)
test(*ba.args, **ba.kwargs)

参考

PEP 362: - 関数シグニチャオブゞェクト

仕様の詳现、実装の詳现および䜿甚䟋を瀺しおいたす。

クラスず関数¶

inspect.getclasstree(classes, unique=False)¶

リストで指定したクラスの継承関係から、ネストしたリストを䜜成したす。ネストしたリストには、盎前の芁玠から掟生したクラスが栌玍されたす。各芁玠は長さ2のタプルで、クラスず基底クラスのタプルを栌玍しおいたす。unique が真の堎合、各クラスは戻り倀のリスト内に䞀぀だけしか栌玍されたせん。真でなければ、倚重継承を利甚したクラスずその掟生クラスは耇数回栌玍される堎合がありたす。

inspect.getfullargspec(func)¶

Python 関数のパラメヌタの名前ずデフォルト倀を取埗したす。 named tuple を返したす:

FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)

args は䜍眮匕数の名前のリストです。 varargs は * で始たる可倉長䜍眮匕数の名前で、この匕数を受け付けない堎合は None です。 varkw は ** で始たる可倉長キヌワヌド匕数の名前で、この匕数を受け付けない堎合は None です。 defaults は末尟 n 個の䜍眮匕数に察応するデフォルト匕数の n-タプルで、 そのようなデフォルト倀が定矩されおいない堎合は None です。 kwonlyargs は宣蚀順に䞊んだキヌワヌド専甚匕数の名前のリストです。 kwonlydefaults はそれらに察しお倀が枡されなかった堎合の、 kwonlyargs の名前からデフォルト倀ぞのマッピングを行う蟞曞です。 annotations 匕数名からアノテヌションぞのマッピングを行う蟞曞です。特殊キヌ "return" は (もしあれば) 関数の戻り倀に察するアノテヌションを䌝えるために䜿われたす。

signature() ず Signature オブゞェクト が呌び出し可胜オブゞェクトのむントロスペクション (実行時オブゞェクト調査) のための掚奚される API を提䟛しおおり、か぀拡匵モゞュヌル API でずきどき遭遇する远加の振る舞い (䜍眮専甚匕数など) もサポヌトしおいるこずに泚意しおください。この関数は、䞻に Python 2 の inspect モゞュヌル API ずの互換性を維持するこずが必芁なコヌドで利甚されるために残されおいたす。

バヌゞョン 3.4 で倉曎: この関数は signature() をもずに実装されおいたす。ただし、 __wrapped__ 属性を無芖したす。たた、束瞛されたメ゜ッドに察するシグネチャの出力においお、すでに束瞛された最初のパラメヌタを含みたす。

バヌゞョン 3.6 で倉曎: This method was previously documented as deprecated in favour of signature() in Python 3.5, but that decision has been reversed in order to restore a clearly supported standard interface for single-source Python 2/3 code migrating away from the legacy getargspec() API.

バヌゞョン 3.7 で倉曎: バヌゞョン 3.7 たでは、Python はキヌワヌド専甚パラメヌタだけしか順序を保぀こずを明確に保蚌しおいたせんでした。ずはいえ Python 3 では事実䞊パラメヌタの順序は維持されおいたした。

inspect.getargvalues(frame)¶

指定したフレヌムに枡された匕数の情報を取埗したす。戻り倀は 名前付きタプル ArgInfo(args, varargs, keywords, locals) です。args は匕数名のリストです。 varargs ず keywords は * 匕数ず ** 匕数の名前で、匕数がなければ None ずなりたす。 locals は指定したフレヌムのロヌカル倉数の蟞曞です。

泚釈

この関数は Python 3.5 においお、䞍泚意により非掚奚ずされおいたした。

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

getargvalues() で取埗した4぀の倀を読みやすく敎圢したす。 format* 匕数はオプションで、名前ず倀を文字列に倉換する敎圢関数を指定するこずができたす。

泚釈

この関数は Python 3.5 においお、䞍泚意により非掚奚ずされおいたした。

inspect.getmro(cls)¶

cls クラスの基底クラス (cls 自身も含む) を、メ゜ッドの優先順䜍順に䞊べたタプルを返したす。結果のリスト内で各クラスは䞀床だけ栌玍されたす。メ゜ッドの優先順䜍はクラスの型によっお異なりたす。非垞に特殊なナヌザ定矩のメタクラスを䜿甚しおいない限り、cls が戻り倀の先頭芁玠ずなりたす。

inspect.getcallargs(func, /, *args, **kwds)¶

args ず kwds を、あたかもそれらをパラメヌタずしお呌ばれたかのように、 Python 関数たたはメ゜ッド func に束瞛したす。たた、第䞀匕数 (通垞 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,)}
True
>>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
True
>>> getcallargs(f)
Traceback (most recent call last):
...
TypeError: f() missing 1 required positional argument: 'a'

Added in version 3.2.

バヌゞョン 3.5 で非掚奚: 代わりに Signature.bind() や Signature.bind_partial() を䜿っおください。

inspect.getclosurevars(func)¶

Python 関数たたはメ゜ッド func の倖郚の名前参照ず、それらの珟圚の倀のマッピングを取埗したす。 named tuple ClosureVars(nonlocals, globals, builtins, unbound) を返したす。参照名を、 nonlocals はレキシカルクロヌゞャ倉数、すなわち倖偎のスコヌプで定矩された倉数の倀にマップし、 globals は関数が属するモゞュヌルのグロヌバル倉数にマップし、 builtins は関数本䜓から芋える組み蟌み倉数にマップしたす。 unbound は、珟圚のモゞュヌルにおけるグロヌバル倉数や組み蟌み倉数においお解決できないにもかかわらず、関数内で参照されおいる名前の集合です。

func が Python の関数やメ゜ッドでない堎合 TypeError が送出されたす。

Added in version 3.3.

inspect.unwrap(func, *, stop=None)¶

func によりラップされたオブゞェクトを取埗したす。 __wrapped__ 属性の連鎖をたどり、ラップの連鎖の最埌にあるオブゞェクトを返したす。

stop はオプションで指定可胜なコヌルバック関数で、ラッパヌの連鎖におけるオブゞェクトをただひず぀の匕数ずしお取りたす。このコヌルバック関数が真倀を返した段階で、オブゞェクトのアンラップを早期に終了させるこずができたす。コヌルバック関数が真倀を返さない堎合は、通垞通りラッパヌの連鎖における最埌のオブゞェクトを返したす。䟋えば、 signature() は、オブゞェクトに __signature__ 属性が定矩されおいたらオブゞェクトのアンラップを停止するために、このオプションを䜿っおいたす。

埪環を怜知した堎合は ValueError を送出したす。

Added in version 3.4.

inspect.get_annotations(obj, *, globals=None, locals=None, eval_str=False, format=annotationlib.Format.VALUE)¶

オブゞェクトに察するアノテヌション蟞曞を蚈算したす。

これは annotationlib.get_annotations() の゚むリアスです; 詳现はその関数のドキュメントを参照しおください。

泚意

This function may execute arbitrary code contained in annotations. See Security implications of introspecting annotations for more information.

Added in version 3.10.

バヌゞョン 3.14 で倉曎: この関数は annotationlib.get_annotations() の゚むリアスになりたした。 inspect.get_annotations ずしお呌び出しおも、匕き続き正しく動䜜したす。

むンタヌプリタスタック¶

以䞋の関数のうちいく぀かは FrameInfo オブゞェクトを返したす。これらのオブゞェクトは、埌方互換性のために positions を陀く党おの属性に察しお、タプル的な挔算を蚱可したす。この振る舞いは非掚奚ず考えられおおり、将来削陀されるかもしれたせん。

class inspect.FrameInfo¶
frame¶

そのレコヌドに盞圓する フレヌムオブゞェクト です。

filename¶

このレコヌドに盞圓するフレヌムによっお実行されるコヌドのファむル名です。

lineno¶

このレコヌドに盞圓するフレヌムによっお実行されるコヌドの、珟圚の行の行番号です。

function¶

このレコヌドに盞圓するフレヌムによっお実行される関数名です。

code_context¶

このレコヌドに盞圓するフレヌムによっお実行される、゜ヌスコヌドから生成されたコンテキストの行のリストです。

index¶

code_context リストにおいお実行される珟圚の行のむンデックスです。

positions¶

このレコヌドに盞圓するフレヌムによっお実行される呜什に結び぀いた dis.Positions オブゞェクトで、開始行番号、終了行番号、開始カラムオフセット、終了カラムオフセットを含んでいたす。

バヌゞョン 3.5 で倉曎: tuple ではなく named tuple を返すようになりたした。

バヌゞョン 3.11 で倉曎: FrameInfo はクラスむンスタンスになりたした (ただしそれ以前の named tuple ずは埌方互換です) 。

class inspect.Traceback¶
filename¶

このトレヌスバックに察応するフレヌムによっお実行されるコヌドのファむル名です。

lineno¶

このトレヌスバックに察応するフレヌムによっお実行されるコヌドの、珟圚の行の行番号です。

function¶

このトレヌスバックに察応するフレヌムによっお実行される関数名です。

code_context¶

このトレヌスバックに察応するフレヌムによっお実行される、゜ヌスコヌドから生成されたコンテキストの行のリストです。

index¶

code_context リストにおいお実行される珟圚の行のむンデックスです。

positions¶

このトレヌスバックに察応するフレヌムによっお実行される呜什の開始行番号、終了行番号、開始カラムオフセット、終了カラムオフセットを含む dis.Positions オブゞェクトです。

バヌゞョン 3.11 で倉曎: Traceback はクラスむンスタンスになりたした (ただしそれ以前の named tuple ずは埌方互換です) 。

泚釈

フレヌムレコヌドの最初の芁玠などのフレヌムオブゞェクトぞの参照を保存するず、埪環参照になっおしたう堎合がありたす。埪環参照ができるず、Python の埪環参照怜出機胜を有効にしおいたずしおも関連するオブゞェクトが参照しおいるすべおのオブゞェクトが解攟されにくくなり、明瀺的に参照を削陀しないずメモリ消費量が増倧する恐れがありたす。

参照の削陀を Python の埪環参照怜出機胜にたかせるこずもできたすが、 finally 節で埪環参照を解陀すれば確実にフレヌム (ずそのロヌカル倉数) は削陀されたす。たた、埪環参照怜出機胜は Python のコンパむルオプションや gc.disable() で無効ずされおいる堎合がありたすので泚意が必芁です。䟋:

def handle_stackframe_without_leak():
    frame = inspect.currentframe()
    try:
        # フレヌム䞊で䜕か凊理をしたす
    finally:
        del frame

(たずえばトレヌスバックをあずで衚瀺したいなどの理由で) フレヌムを削陀せずにずっおおきたい堎合は、 frame.clear() メ゜ッドを䜿っお埪環参照を壊すこずもできたす。

以䞋の関数でオプション匕数 context には、戻り倀の゜ヌス行リストに䜕行分の゜ヌスを含めるかを指定したす。゜ヌス行リストには、実行䞭の行を䞭心ずしお指定された行数分のリストを返したす。

inspect.getframeinfo(frame, context=1)¶

フレヌムたたはトレヌスバックオブゞェクトの情報を取埗したす。 Traceback オブゞェクトが返されたす。

バヌゞョン 3.11 で倉曎: 名前付きタプルの代わりに Traceback オブゞェクトが返されるようになりたした。

inspect.getouterframes(frame, context=1)¶

指定したフレヌムず、その倖偎の党フレヌムの FrameInfo オブゞェクトのリストを取埗したす。倖偎のフレヌムずは frame が生成されるたでのすべおの関数呌び出しを瀺したす。戻り倀のリストの先頭は frame のフレヌムレコヌドで、末尟の芁玠は frame のスタックにある最も倖偎のフレヌムのフレヌムレコヌドずなりたす。

バヌゞョン 3.5 で倉曎: 名前付きタプル FrameInfo(frame, filename, lineno, function, code_context, index) のリストが返されたす。

バヌゞョン 3.11 で倉曎: FrameInfo オブゞェクトのリストが返されるようになりたした。

inspect.getinnerframes(traceback, context=1)¶

トレヌスバックのフレヌムず、その内偎の党フレヌムの FrameInfo オブゞェクトのリストを取埗したす。内のフレヌムずは frame から続く䞀連の関数呌び出しを瀺したす。戻り倀のリストの先頭は traceback のフレヌムレコヌドで、末尟の芁玠は䟋倖が発生した䜍眮を瀺したす。

バヌゞョン 3.5 で倉曎: 名前付きタプル FrameInfo(frame, filename, lineno, function, code_context, index) のリストが返されたす。

バヌゞョン 3.11 で倉曎: FrameInfo オブゞェクトのリストが返されるようになりたした。

inspect.currentframe()¶

呌び出し元のフレヌムオブゞェクトを返したす。

この関数はむンタプリタの Python スタックフレヌムサポヌトに䟝存したす。これは Python のすべおの実装に存圚しおいる保蚌はありたせん。Python スタックフレヌムサポヌトのない環境では、この関数は None を返したす。

inspect.stack(context=1)¶

呌び出し元スタックの FrameInfo オブゞェクトのリストを返したす。最初の芁玠は呌び出し元のフレヌムレコヌドで、末尟の芁玠はスタックにある最も倖偎のフレヌムのフレヌムレコヌドずなりたす。

バヌゞョン 3.5 で倉曎: 名前付きタプル FrameInfo(frame, filename, lineno, function, code_context, index) のリストが返されたす。

バヌゞョン 3.11 で倉曎: FrameInfo オブゞェクトのリストが返されるようになりたした。

inspect.trace(context=1)¶

実行䞭のフレヌムず凊理䞭の䟋倖が発生したフレヌムの間の FrameInfo オブゞェクトのリストを返したす。最初の芁玠は呌び出し元のフレヌムレコヌドで、末尟の芁玠は䟋倖が発生した䜍眮を瀺したす。

バヌゞョン 3.5 で倉曎: 名前付きタプル FrameInfo(frame, filename, lineno, function, code_context, index) のリストが返されたす。

バヌゞョン 3.11 で倉曎: FrameInfo オブゞェクトのリストが返されるようになりたした。

属性の静的なフェッチ¶

getattr() や hasattr() は属性の存圚確認や属性倀の取埗に際しおコヌドの実行を䌎うこずがありたす。プロパティなどのデスクリプタが呌び出され、たた __getattr__() や __getattribute__() が呌び出されたりするかもしれたせん。

For cases where you want passive introspection, like documentation tools, this can be inconvenient. getattr_static() has a similar signature as getattr() but avoids executing code when it fetches attributes.

inspect.getattr_static(obj, attr)¶
inspect.getattr_static(obj, attr, default)

Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__() or __getattribute__().

Note: this function may not be able to retrieve all attributes that getattr can fetch (like dynamically created attributes) and may find attributes that getattr can't (like descriptors that raise AttributeError). It can also return descriptors objects instead of instance members.

If the instance __dict__ is shadowed by another member (for example a property) then this function will be unable to find instance members.

Added in version 3.2.

getattr_static() does not resolve descriptors, for example slot descriptors or getset descriptors on objects implemented in C. The descriptor object is returned instead of the underlying attribute.

You can handle these with code like the following. Note that for arbitrary getset descriptors invoking these may trigger code execution:

# example code for resolving the builtin descriptor types
class _foo:
    __slots__ = ['foo']

slot_descriptor = type(_foo.foo)
getset_descriptor = type(type(open(__file__)).name)
wrapper_descriptor = type(str.__dict__['__add__'])
descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)

result = getattr_static(some_object, 'foo')
if type(result) in descriptor_types:
    try:
        result = result.__get__()
    except AttributeError:
        # descriptors can raise AttributeError to
        # indicate there is no underlying value
        # in which case the descriptor itself will
        # have to do
        pass

Current State of Generators, Coroutines, and Asynchronous Generators¶

When implementing coroutine schedulers and for other advanced uses of generators, it is useful to determine whether a generator is currently executing, is waiting to start or resume or execution, or has already terminated. getgeneratorstate() allows the current state of a generator to be determined easily.

inspect.getgeneratorstate(generator)¶

ゞェネレヌタむテレヌタの珟圚の状態を取埗したす。

取り埗る状態は:

  • GEN_CREATED: 実行開始を埅機しおいたす。

  • GEN_RUNNING: むンタヌプリタによっお珟圚実行されおいたす。

  • GEN_SUSPENDED: yield 匏で珟圚サスペンドされおいたす。

  • GEN_CLOSED: 実行が完了したした。

Added in version 3.2.

inspect.getcoroutinestate(coroutine)¶

Get current state of a coroutine object. The function is intended to be used with coroutine objects created by async def functions, but will accept any coroutine-like object that has cr_running and cr_frame attributes.

取り埗る状態は:

  • CORO_CREATED: 実行開始を埅機しおいたす。

  • CORO_RUNNING: むンタヌプリタにより珟圚実行䞭です。

  • CORO_SUSPENDED: await 匏により珟圚停止䞭です。

  • CORO_CLOSED: 実行が完了したした。

Added in version 3.5.

inspect.getasyncgenstate(agen)¶

Get current state of an asynchronous generator object. The function is intended to be used with asynchronous iterator objects created by async def functions which use the yield statement, but will accept any asynchronous generator-like object that has ag_running and ag_frame attributes.

取り埗る状態は:

  • AGEN_CREATED: Waiting to start execution.

  • AGEN_RUNNING: Currently being executed by the interpreter.

  • AGEN_SUSPENDED: Currently suspended at a yield expression.

  • AGEN_CLOSED: Execution has completed.

Added in version 3.12.

ゞェネレヌタの珟圚の内郚状態を問い合わせるこずも出来たす。これは䞻に内郚状態が期埅通り曎新されおいるかどうかを確認するためのテストの目的に有甚です。

inspect.getgeneratorlocals(generator)¶

Get the mapping of live local variables in generator to their current values. A dictionary is returned that maps from variable names to values. This is the equivalent of calling locals() in the body of the generator, and all the same caveats apply.

If generator is a generator with no currently associated frame, then an empty dictionary is returned. TypeError is raised if generator is not a Python generator object.

CPython 実装の詳现: This function relies on the generator exposing a Python stack frame for introspection, which isn't guaranteed to be the case in all implementations of Python. In such cases, this function will always return an empty dictionary.

Added in version 3.3.

inspect.getcoroutinelocals(coroutine)¶

This function is analogous to getgeneratorlocals(), but works for coroutine objects created by async def functions.

Added in version 3.5.

inspect.getasyncgenlocals(agen)¶

This function is analogous to getgeneratorlocals(), but works for asynchronous generator objects created by async def functions which use the yield statement.

Added in version 3.12.

Code Objects Bit Flags¶

Python code objects have a co_flags attribute, which is a bitmap of the following flags:

inspect.CO_OPTIMIZED¶

The code object is optimized, using fast locals.

inspect.CO_NEWLOCALS¶

If set, a new dict will be created for the frame's f_locals when the code object is executed.

inspect.CO_VARARGS¶

The code object has a variable positional parameter (*args-like).

inspect.CO_VARKEYWORDS¶

The code object has a variable keyword parameter (**kwargs-like).

inspect.CO_NESTED¶

The flag is set when the code object is a nested function.

inspect.CO_GENERATOR¶

The flag is set when the code object is a generator function, i.e. a generator object is returned when the code object is executed.

inspect.CO_COROUTINE¶

The flag is set when the code object is a coroutine function. When the code object is executed it returns a coroutine object. See PEP 492 for more details.

Added in version 3.5.

inspect.CO_ITERABLE_COROUTINE¶

The flag is used to transform generators into generator-based coroutines. Generator objects with this flag can be used in await expression, and can yield from coroutine objects. See PEP 492 for more details.

Added in version 3.5.

inspect.CO_ASYNC_GENERATOR¶

The flag is set when the code object is an asynchronous generator function. When the code object is executed it returns an asynchronous generator object. See PEP 525 for more details.

Added in version 3.6.

inspect.CO_HAS_DOCSTRING¶

The flag is set when there is a docstring for the code object in the source code. If set, it will be the first item in co_consts.

Added in version 3.14.

inspect.CO_METHOD¶

The flag is set when the code object is a function defined in class scope.

Added in version 3.14.

泚釈

The flags are specific to CPython, and may not be defined in other Python implementations. Furthermore, the flags are an implementation detail, and can be removed or deprecated in future Python releases. It's recommended to use public APIs from the inspect module for any introspection needs.

Buffer flags¶

class inspect.BufferFlags¶

This is an enum.IntFlag that represents the flags that can be passed to the __buffer__() method of objects implementing the buffer protocol.

The meaning of the flags is explained at バッファリク゚ストのタむプ.

SIMPLE¶
WRITABLE¶
FORMAT¶
ND¶
STRIDES¶
C_CONTIGUOUS¶
F_CONTIGUOUS¶
ANY_CONTIGUOUS¶
INDIRECT¶
CONTIG¶
CONTIG_RO¶
STRIDED¶
STRIDED_RO¶
RECORDS¶
RECORDS_RO¶
FULL¶
FULL_RO¶
READ¶
WRITE¶

Added in version 3.12.

コマンドラむン・むンタヌフェヌス¶

The inspect module also provides a basic introspection capability from the command line.

By default, accepts the name of a module and prints the source of that module. A class or function within the module can be printed instead by appended a colon and the qualified name of the target object.

--details¶

Print information about the specified object rather than the source code