inspect
— 检查对象¶
源代码: Lib/inspect.py
inspect
模块提供了一些有用的函数帮助获取对象的信息,例如模块、类、方法、函数、回溯、帧对象以及代码对象。例如它可以帮助你检查类的内容,获取某个方法的源代码,取得并格式化某个函数的实参列表,或者获取你需要显示的回溯的详细信息。
该模块提供了4种主要的功能:类型检查、获取源代码、检查类与函数、检查解释器的调用堆栈。
类型和成员¶
getmembers()
函数获取对象的成员,例如类或模块。函数名以”is”开始的函数主要作为 getmembers()
的第 2 个实参使用。它们也可用于判定某对象是否有如下的特殊属性:
类型 |
属性 |
描述 |
---|---|---|
module – 模块 |
__doc__ |
文档字符串 |
__file__ |
文件名(内置模块没有文件名) |
|
class – 类 |
__doc__ |
文档字符串 |
__name__ |
类定义时所使用的名称 |
|
__qualname__ |
qualified name – 限定名称 |
|
__module__ |
该类型被定义时所在的模块的名称 |
|
method – 方法 |
__doc__ |
文档字符串 |
__name__ |
该方法定义时所使用的名称 |
|
__qualname__ |
qualified name – 限定名称 |
|
__func__ |
实现该方法的函数对象 |
|
__self__ |
该方法被绑定的实例,若没有绑定则为 |
|
__module__ |
定义此方法的模块的名称 |
|
function – 函数 |
__doc__ |
文档字符串 |
__name__ |
用于定义此函数的名称 |
|
__qualname__ |
qualified name – 限定名称 |
|
__code__ |
包含已编译函数的代码对象 bytecode |
|
__defaults__ |
所有位置或关键字形参的默认值的元组 |
|
__kwdefaults__ |
mapping of any default values for keyword-only parameters |
|
__globals__ |
global namespace in which this function was defined |
|
__builtins__ |
builtins namespace |
|
__annotations__ |
mapping of parameters
names to annotations;
|
|
__module__ |
name of module in which this function was defined |
|
回溯 |
tb_frame |
此级别的框架对象 |
tb_lasti |
index of last attempted instruction in bytecode |
|
tb_lineno |
current line number in Python source code |
|
tb_next |
next inner traceback object (called by this level) |
|
框架 |
f_back |
next outer frame object (this frame’s caller) |
f_builtins |
builtins namespace seen by this frame |
|
f_code |
code object being executed in this frame |
|
f_globals |
global namespace seen by this frame |
|
f_lasti |
index of last attempted instruction in bytecode |
|
f_lineno |
current line number in Python source code |
|
f_locals |
local namespace seen by this frame |
|
f_trace |
tracing function for this
frame, or |
|
code |
co_argcount |
number of arguments (not including keyword only arguments, * or ** args) |
co_code |
原始编译字节码的字符串 |
|
co_cellvars |
单元变量名称的元组(通过包含作用域引用) |
|
co_consts |
字节码中使用的常量元组 |
|
co_filename |
创建此代码对象的文件的名称 |
|
co_firstlineno |
number of first line in Python source code |
|
co_flags |
bitmap of |
|
co_lnotab |
编码的行号到字节码索引的映射 |
|
co_freevars |
tuple of names of free variables (referenced via a function’s closure) |
|
co_posonlyargcount |
number of positional only arguments |
|
co_kwonlyargcount |
number of keyword only arguments (not including ** arg) |
|
co_name |
定义此代码对象的名称 |
|
co_qualname |
fully qualified name with which this code object was defined |
|
co_names |
tuple of names other than arguments and function locals |
|
co_nlocals |
局部变量的数量 |
|
co_stacksize |
需要虚拟机堆栈空间 |
|
co_varnames |
实参名和局部变量的元组 |
|
generator – 生成器 |
__name__ |
名称 |
__qualname__ |
qualified name – 限定名称 |
|
gi_frame |
框架 |
|
gi_running |
生成器在运行吗? |
|
gi_code |
code |
|
gi_yieldfrom |
object being iterated by
|
|
coroutine – 协程 |
__name__ |
名称 |
__qualname__ |
qualified name – 限定名称 |
|
cr_await |
object being awaited on,
or |
|
cr_frame |
框架 |
|
cr_running |
is the coroutine running? |
|
cr_code |
code |
|
cr_origin |
where coroutine was
created, or |
|
builtin |
__doc__ |
文档字符串 |
__name__ |
此函数或方法的原始名称 |
|
__qualname__ |
qualified name – 限定名称 |
|
__self__ |
instance to which a
method is bound, or
|
在 3.5 版更改: Add __qualname__
and gi_yieldfrom
attributes to generators.
The __name__
attribute of generators is now set from the function
name, instead of the code name, and it can now be modified.
在 3.7 版更改: Add cr_origin
attribute to coroutines.
在 3.10 版更改: Add __builtins__
attribute to functions.
- inspect.getmembers(object[, predicate])¶
Return all the members of an object in a list of
(name, value)
pairs sorted by name. If the optional predicate argument—which will be called with thevalue
object of each member—is supplied, only members for which the predicate returns a true value are included.备注
getmembers()
will only return class attributes defined in the metaclass when the argument is a class and those attributes have been listed in the metaclass’ custom__dir__()
.
- inspect.getmembers_static(object[, predicate])¶
Return all the members of an object in a list of
(name, value)
pairs sorted by name without triggering dynamic lookup via the descriptor protocol, __getattr__ or __getattribute__. Optionally, only return members that satisfy a given predicate.备注
getmembers_static()
may not be able to retrieve all members that getmembers can fetch (like dynamically created attributes) and may find members that getmembers can’t (like descriptors that raise AttributeError). It can also return descriptor objects instead of instance members in some cases.3.11 新版功能.
- inspect.getmodulename(path)¶
Return the name of the module named by the file path, without including the names of enclosing packages. The file extension is checked against all of the entries in
importlib.machinery.all_suffixes()
. If it matches, the final path component is returned with the extension removed. Otherwise,None
is returned.Note that this function only returns a meaningful name for actual Python modules - paths that potentially refer to Python packages will still return
None
.在 3.3 版更改: The function is based directly on
importlib
.
- inspect.ismodule(object)¶
Return
True
if the object is a module.
- inspect.isclass(object)¶
Return
True
if the object is a class, whether built-in or created in Python code.
- inspect.ismethod(object)¶
Return
True
if the object is a bound method written in Python.
- inspect.isfunction(object)¶
Return
True
if the object is a Python function, which includes functions created by a lambda expression.
- inspect.isgeneratorfunction(object)¶
Return
True
if the object is a Python generator function.在 3.8 版更改: Functions wrapped in
functools.partial()
now returnTrue
if the wrapped function is a Python generator function.
- inspect.isgenerator(object)¶
Return
True
if the object is a generator.
- inspect.iscoroutinefunction(object)¶
Return
True
if the object is a coroutine function (a function defined with anasync def
syntax).3.5 新版功能.
在 3.8 版更改: Functions wrapped in
functools.partial()
now returnTrue
if the wrapped function is a coroutine function.
- inspect.iscoroutine(object)¶
Return
True
if the object is a coroutine created by anasync def
function.3.5 新版功能.
- inspect.isawaitable(object)¶
Return
True
if the object can be used inawait
expression.Can also be used to distinguish generator-based coroutines from regular generators:
def gen(): yield @types.coroutine def gen_coro(): yield assert not isawaitable(gen()) assert isawaitable(gen_coro())
3.5 新版功能.
- inspect.isasyncgenfunction(object)¶
Return
True
if the object is an asynchronous generator function, for example:>>> async def agen(): ... yield 1 ... >>> inspect.isasyncgenfunction(agen) True
3.6 新版功能.
在 3.8 版更改: Functions wrapped in
functools.partial()
now returnTrue
if the wrapped function is a asynchronous generator function.
- inspect.isasyncgen(object)¶
Return
True
if the object is an asynchronous generator iterator created by an asynchronous generator function.3.6 新版功能.
- inspect.istraceback(object)¶
Return
True
if the object is a traceback.
- inspect.isframe(object)¶
Return
True
if the object is a frame.
- inspect.iscode(object)¶
Return
True
if the object is a code.
- inspect.isbuiltin(object)¶
Return
True
if the object is a built-in function or a bound built-in method.
- inspect.ismethodwrapper(object)¶
Return
True
if the type of object is aMethodWrapperType
.These are instances of
MethodWrapperType
, such as__str__()
,__eq__()
and__repr__()
- inspect.isroutine(object)¶
Return
True
if the object is a user-defined or built-in function or method.
- inspect.isabstract(object)¶
Return
True
if the object is an abstract base class.
- inspect.ismethoddescriptor(object)¶
Return
True
if the object is a method descriptor, but not ifismethod()
,isclass()
,isfunction()
orisbuiltin()
are true.This, 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 theismethoddescriptor()
test, simply because the other tests promise more – you can, e.g., count on having the__func__
attribute (etc) when an object passesismethod()
.
- inspect.isdatadescriptor(object)¶
Return
True
if the object is a data descriptor.Data descriptors have a
__set__
or a__delete__
method. Examples are properties (defined in Python), getsets, and members. The latter two are defined in C and there are more specific tests available for those types, which is robust across Python implementations. Typically, data descriptors will also have__name__
and__doc__
attributes (properties, getsets, and members have both of these attributes), but this is not guaranteed.
- inspect.isgetsetdescriptor(object)¶
Return
True
if the object is a getset descriptor.CPython implementation detail: getsets are attributes defined in extension modules via
PyGetSetDef
structures. For Python implementations without such types, this method will always returnFalse
.
- inspect.ismemberdescriptor(object)¶
Return
True
if the object is a member descriptor.CPython implementation detail: Member descriptors are attributes defined in extension modules via
PyMemberDef
structures. For Python implementations without such types, this method will always returnFalse
.
检索源代码¶
- 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. ReturnNone
if the documentation string is invalid or missing.在 3.5 版更改: 文档字符串现在如果不被重写就会被继承。
- inspect.getcomments(object)¶
用一个字符串返回紧挨着对象的源代码(对于类、函数或方法)的任何一行注解,或者在 Python 源文件的顶部(如果对象是一个模块)。 如果对象的源代码不可用,则返回
None
。 如果该对象是在 C 语言或交互式 shell 中定义的,就可能发生这种情况。
- inspect.getmodule(object)¶
Try to guess which module an object was defined in. Return
None
if the module cannot be determined.
- 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. This will fail with aTypeError
if the object is a built-in module, class, or function.
- inspect.getsourcelines(object)¶
返回一个对象的源行和起始行号的列表。实参可以是一个模块、类、方法、函数、回溯(traceback)、框架(frame)或代码对象(code object)。源代码被返回为对应于该对象的行的列表,行号表示在原始源文件中找到第一行代码的位置。如果不能检索到源代码,会引发一个
OSError
。
- inspect.getsource(object)¶
返回一个对象的源代码文本。实参可以是一个模块、类、方法、函数、回溯、框架或代码对象。源代码将以单个字符串的形式返回。如果不能检索到源代码,会引发一个
OSError
。
- inspect.cleandoc(doc)¶
清理缩进到与代码块一致的文档字符串的缩进。
所有先导空白都从第一行中删除。从第二行开始,任何可以统一删除的前导空白都被删除。开头和结尾的空行随后被删除。此外,所有的制表符都被扩展为空格。
用 Signature 对象对可调用程序进行自省¶
3.3 新版功能.
Signature 对象代表了一个可调用对象的调用签名和它的 return 注解。要检索签名对象,请使用 signature()
函数。
- inspect.signature(callable, *, follow_wrapped=True, globals=None, locals=None, eval_str=False)¶
返回一个
Signature
对象,用于给定的callable
>>> 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'>
接受广泛的 Python 可调用文件,从普通函数和类到
functools.partial()
对象。对于使用字符串注解的模块中定义的对象(
from __future__ import annotations
),signature()
将尝试使用inspect.get_annotations()
自动解除注解的字符串。global
,locals
, 和eval_str
形参在解析注解时被传入inspect.get_annotations()
;关于如何使用这些形参,请参见inspect.get_annotations()
的文档。如果不能提供签名,则引发
ValueError
,如果不支持该类型的对象,则引发TypeError
。另外,如果注解是字符串化的,并且eval_str
不是假的,eval()
调用来解除注解的字符串化,有可能引发任何类型的异常。函数签名中的斜线(/)表示它前面的形参是仅有位置的。更多信息,请参见 关于仅有位置的形参的常见问题条目。
3.5 新版功能:
follow_wrapped
形参。传递False
以获得具体的callable
的签名(callable.__wrapped__
将不会被用来解除装饰的可调用程序)。3.10 新版功能:
globals
,locals
和eval_str
形参备注
在 Python 的某些实现中,一些可调用函数可能是不可反省的。例如,在 CPython 中,一些用 C 语言定义的内置函数没有提供关于其实参的元数据。
- class inspect.Signature(parameters=None, *, return_annotation=Signature.empty)¶
一个 Signature 对象代表了一个函数的调用签名和它的 return 注解。对于函数接受的每个形参,它在其
parameters
集合中存储一个Parameter
对象。可选的 parameters 实参是一个
Parameter
对象的序列,它被验证以检查是否有名称重复的形参,以及形参的顺序是否正确,即先是仅有位置的形参,然后是有位置或关键字的形参,以及有默认值的形参紧随没有默认值的形参。可选的 return_annotation 实参,可以是一个任意的 Python 对象,是可调用对象的 “return” 注解。
Signature 对象是 不可变的。使用
Signature.replace()
来制作一个修改的副本。在 3.5 版更改: 签名对象是可提取(picklable)和可散列的。
- empty¶
一个特殊的类级标记,用于指定没有 return 注解。
- parameters¶
形参名称与相应的
Parameter
对象的有序映射。形参以严格的定义顺序出现,包括只有关键字的形参。在 3.7 版更改: Python 只明确地保证从 3.7 版开始保留只用关键字的形参的声明顺序,尽管实际上这个顺序在 Python 3 中一直被保留着。
- return_annotation¶
可调用程序的 “return” 注解。如果可调用程序没有 “return” 注解,这个属性将被设置为
Signature.empty
。
- bind(*args, **kwargs)¶
创建一个从位置形参和关键字 arguments 到 parameters 的映射。如果
*args
和**kwargs
符合签名,则返回BoundArguments
,否则引发TypeError
。
- bind_partial(*args, **kwargs)¶
与
Signature.bind()
的工作方式相同,但允许省略一些必要的实参(模仿functools.partial()
的行为)。返回BoundArguments
,如果传递的实参与签名不匹配,则引发TypeError
。
- replace(*[, parameters][, return_annotation])¶
在被替换的实例基础上创建一个新的 Signature 实例。可以通过不同的
parameters
和/或return_annotation
来覆盖基本签名的相应属性。要从复制的签名中移除 return_annotation,请传入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'"
- classmethod from_callable(obj, *, follow_wrapped=True, globalns=None, localns=None)¶
为给定的可调用的
obj
返回一个Signature
(或其子类)对象。通过follow_wrapped=False
来获得obj
的签名,而不需要解开其__wrapped__
链。globalns
和localns
将在解析注解时作为命名空间使用。这个方法简化了
Signature
的子类化class MySignature(Signature): pass sig = MySignature.from_callable(min) assert isinstance(sig, MySignature)
3.5 新版功能.
3.10 新版功能:
globalns
和localns
形参。
- class inspect.Parameter(name, kind, *, default=Parameter.empty, annotation=Parameter.empty)¶
形参对象是 不可变的。你可以使用
Parameter.replace()
来创建一个修改过的副本,而不是修改一个 Parameter 对象。在 3.5 版更改: Parameter 对象是可拾取和可哈希的。
- empty¶
一个特殊的类级标记,用于指定没有默认值和注解。
- name¶
形参的名称,是一个字符串。该名称必须是一个有效的 Python 标识符。
CPython implementation detail: CPython 在用于实现理解和生成器表达式的代码对象上生成形式为
.0
的隐含形参名。在 3.6 版更改: 这些形参名称被本模块暴露为
implicit0
等名称。
- default¶
该形参的默认值。如果该形参没有默认值,这个属性将被设置为
Parameter.empty
。
- annotation¶
形参的注解。如果形参没有注解,这个属性被设置为
Parameter.empty
。
- kind¶
描述了实参值如何被绑定到形参上。可能的值(可通过
Parameter
访问,如Parameter.KEYWORD_ONLY
):名称
含意
POSITIONAL_ONLY
Value 必须作为一个位置实参提供。只有位置形参是那些出现在 Python 函数定义中的
/
条目之前的参数(如果存在的话)。POSITIONAL_OR_KEYWORD
Value may be supplied as either a keyword or positional argument (this is the standard binding behaviour for functions implemented in Python.)
VAR_POSITIONAL
A tuple of positional arguments that aren’t bound to any other parameter. This corresponds to a
*args
parameter in a Python function definition.KEYWORD_ONLY
Value must be supplied as a keyword argument. Keyword only parameters are those which appear after a
*
or*args
entry in a Python function definition.VAR_KEYWORD
A dict of keyword arguments that aren’t bound to any other parameter. This corresponds to a
**kwargs
parameter in a Python function definition.例子:打印所有只有关键字的实参,没有默认值
>>> 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 的一个枚举值。
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.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'"
在 3.4 版更改: 在 Python 3.3 中,如果它们的
kind
被设置为POSITIONAL_ONLY
,则允许name
被设置为None
。这已不再允许。
- class inspect.BoundArguments¶
Signature.bind()
或Signature.bind_partial()
调用的结果。保存实参对函数形参的映射。- arguments¶
A mutable mapping of parameters’ names to arguments’ values. Contains only explicitly bound arguments. Changes in
arguments
will reflect inargs
andkwargs
.Should be used in conjunction with
Signature.parameters
for any argument processing purposes.备注
Arguments for which
Signature.bind()
orSignature.bind_partial()
relied on a default value are skipped. However, if needed, useBoundArguments.apply_defaults()
to add them.在 3.9 版更改:
arguments
is now of typedict
. Formerly, it was of typecollections.OrderedDict
.
- apply_defaults()¶
Set default values for missing arguments.
For variable-positional arguments (
*args
) the default is an empty tuple.For variable-keyword arguments (
**kwargs
) the default is an empty dict.>>> def foo(a, b='ham', *args): pass >>> ba = inspect.signature(foo).bind('spam') >>> ba.apply_defaults() >>> ba.arguments {'a': 'spam', 'b': 'ham', 'args': ()}
3.5 新版功能.
The
args
andkwargs
properties can be used to invoke functions:def test(a, *, b): ... sig = signature(test) ba = sig.bind(10, b=20) test(*ba.args, **ba.kwargs)
参见
- PEP 362 - Function Signature Object.
The detailed specification, implementation details and examples.
类与函数¶
- inspect.getclasstree(classes, unique=False)¶
Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple containing a class and a tuple of its base classes. If the unique argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times.
- inspect.getfullargspec(func)¶
Get the names and default values of a Python function’s parameters. A named tuple is returned:
FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)
args is a list of the positional parameter names. varargs is the name of the
*
parameter orNone
if arbitrary positional arguments are not accepted. varkw is the name of the**
parameter orNone
if arbitrary keyword arguments are not accepted. defaults is an n-tuple of default argument values corresponding to the last n positional parameters, orNone
if there are no such defaults defined. kwonlyargs is a list of keyword-only parameter names in declaration order. kwonlydefaults is a dictionary mapping parameter names from kwonlyargs to the default values used if no argument is supplied. annotations is a dictionary mapping parameter names to annotations. The special key"return"
is used to report the function return value annotation (if any).Note that
signature()
and Signature Object provide the recommended API for callable introspection, and support additional behaviours (like positional-only arguments) that are sometimes encountered in extension module APIs. This function is retained primarily for use in code that needs to maintain compatibility with the Python 2inspect
module API.在 3.4 版更改: This function is now based on
signature()
, but still ignores__wrapped__
attributes and includes the already bound first parameter in the signature output for bound methods.在 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 legacygetargspec()
API.在 3.7 版更改: Python 只明确地保证从 3.7 版开始保留只用关键字的形参的声明顺序,尽管实际上这个顺序在 Python 3 中一直被保留着。
- inspect.getargvalues(frame)¶
Get information about arguments passed into a particular frame. A named tuple
ArgInfo(args, varargs, keywords, locals)
is returned. args is a list of the argument names. varargs and keywords are the names of the*
and**
arguments orNone
. locals is the locals dictionary of the given frame.备注
This function was inadvertently marked as deprecated in Python 3.5.
- inspect.formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])¶
Format a pretty argument spec from the four values returned by
getargvalues()
. The format* arguments are the corresponding optional formatting functions that are called to turn names and values into strings.备注
This function was inadvertently marked as deprecated in Python 3.5.
- inspect.getmro(cls)¶
Return a tuple of class cls’s base classes, including cls, in method resolution order. No class appears more than once in this tuple. Note that the method resolution order depends on cls’s type. Unless a very peculiar user-defined metatype is in use, cls will be the first element of the tuple.
- inspect.getcallargs(func, /, *args, **kwds)¶
Bind the args and kwds to the argument names of the Python function or method func, as if it was called with them. For bound methods, bind also the first argument (typically named
self
) to the associated instance. A dict is returned, mapping the argument names (including the names of the*
and**
arguments, if any) to their values from args and kwds. In case of invoking func incorrectly, i.e. wheneverfunc(*args, **kwds)
would raise an exception because of incompatible signature, an exception of the same type and the same or similar message is raised. For example:>>> 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'
3.2 新版功能.
3.5 版后已移除: Use
Signature.bind()
andSignature.bind_partial()
instead.
- inspect.getclosurevars(func)¶
Get the mapping of external name references in a Python function or method func to their current values. A named tuple
ClosureVars(nonlocals, globals, builtins, unbound)
is returned. nonlocals maps referenced names to lexical closure variables, globals to the function’s module globals and builtins to the builtins visible from the function body. unbound is the set of names referenced in the function that could not be resolved at all given the current module globals and builtins.TypeError
is raised if func is not a Python function or method.3.3 新版功能.
- inspect.unwrap(func, *, stop=None)¶
Get the object wrapped by func. It follows the chain of
__wrapped__
attributes returning the last object in the chain.stop is an optional callback accepting an object in the wrapper chain as its sole argument that allows the unwrapping to be terminated early if the callback returns a true value. If the callback never returns a true value, the last object in the chain is returned as usual. For example,
signature()
uses this to stop unwrapping if any object in the chain has a__signature__
attribute defined.ValueError
is raised if a cycle is encountered.3.4 新版功能.
- inspect.get_annotations(obj, *, globals=None, locals=None, eval_str=False)¶
计算一个对象的注解 dict。
obj
可以是一个 callable,类,或模块。传入任何其他类型的对象会引发TypeError
。返回一个dict。
get_annotations()
每次调用都会返回一个新的 dict;对同一个对象调用两次会返回两个不同但等价的 dict。这个函数为你处理几个细节:
如果
eval_str
为真,str
类型的值将使用eval()
进行解串。这是为了与字符串化的注释一起使用(from __future__ import annotations
))。如果
obj
没有注释 dict,返回一个空 dict。(函数和方法总是有一个注解字典;类、模块和其他类型的可调用程序可能没有)。忽略类上的继承注解。如果一个类没有自己的注解字典,则返回一个空字典。
为了安全起见,访问对象成员和 dict 值使用
getattr()
和dict.get()
。Always, always, always returns a freshly created dict.
eval_str
控制str
类型的值是否被替换成对这些值调用eval()
的结果:如果 eval_str 为真,
eval()
将对str
类型的值进行调用。(注意,get_annotations
不捕捉异常;如果eval()
引发异常,它将在get_annotations
调用后解绑堆栈)。如果 eval_str 为 false(默认),那么
str
类型的值将不会改变。
globals
和locals
被传递到eval()
;更多信息请参见eval()
的文档。如果globals
或locals
是None
,这个函数可能会用特定环境的默认值替换该值,取决于type(obj)
:如果
obj
是一个模块,globals
默认为obj.__dict__
。如果
obj
是一个类,globals
默认为sys.modules[obj.__module__].__dict__
,locals
默认为obj
类的命名空间。如果
obj
是一个可调用的,globals
默认为obj.__globals__
,尽管如果obj
是一个被包裹的函数(使用functools.update_wrapper()
),它首先被解开。
调用
get_annotations
是访问任何对象的注解 dict 的最佳做法。参见 对象注解属性的最佳实践 以了解更多关于注解的最佳实践。3.10 新版功能.
The interpreter stack¶
Some of the following functions return
FrameInfo
objects. For backwards compatibility these objects allow
tuple-like operations on all attributes except positions
. This behavior
is considered deprecated and may be removed in the future.
- class inspect.FrameInfo¶
- frame¶
The frame object that the record corresponds to.
- filename¶
The file name associated with the code being executed by the frame this record corresponds to.
- lineno¶
The line number of the current line associated with the code being executed by the frame this record corresponds to.
- function¶
The function name that is being executed by the frame this record corresponds to.
- code_context¶
A list of lines of context from the source code that’s being executed by the frame this record corresponds to.
- index¶
The index of the current line being executed in the
code_context
list.
- positions¶
A
dis.Positions
object containing the start line number, end line number, start column offset, and end column offset associated with the instruction being executed by the frame this record corresponds to.
在 3.5 版更改: Return a named tuple instead of a tuple.
在 3.11 版更改: Changed the return object from a named tuple to a regular object (that is backwards compatible with the previous named tuple).
- class inspect.Traceback¶
- filename¶
The file name associated with the code being executed by the frame this traceback corresponds to.
- lineno¶
The line number of the current line associated with the code being executed by the frame this traceback corresponds to.
- function¶
The function name that is being executed by the frame this traceback corresponds to.
- code_context¶
A list of lines of context from the source code that’s being executed by the frame this traceback corresponds to.
- index¶
The index of the current line being executed in the
code_context
list.
- positions¶
A
dis.Positions
object containing the start line number, end line number, start column offset, and end column offset associated with the instruction being executed by the frame this traceback corresponds to.
备注
Keeping references to frame objects, as found in the first element of the frame records these functions return, can cause your program to create reference cycles. Once a reference cycle has been created, the lifespan of all objects which can be accessed from the objects which form the cycle can become much longer even if Python’s optional cycle detector is enabled. If such cycles must be created, it is important to ensure they are explicitly broken to avoid the delayed destruction of objects and increased memory consumption which occurs.
Though the cycle detector will catch these, destruction of the frames (and local
variables) can be made deterministic by removing the cycle in a
finally
clause. This is also important if the cycle detector was
disabled when Python was compiled or using gc.disable()
. For example:
def handle_stackframe_without_leak():
frame = inspect.currentframe()
try:
# do something with the frame
finally:
del frame
If you want to keep the frame around (for example to print a traceback
later), you can also break reference cycles by using the
frame.clear()
method.
The optional context argument supported by most of these functions specifies the number of lines of context to return, which are centered around the current line.
- inspect.getframeinfo(frame, context=1)¶
Get information about a frame or traceback object. A
Traceback
object is returned.在 3.11 版更改: A
Traceback
object is returned instead of a named tuple.
- inspect.getouterframes(frame, context=1)¶
Get a list of
FrameInfo
objects for a frame and all outer frames. These frames represent the calls that lead to the creation of frame. The first entry in the returned list represents frame; the last entry represents the outermost call on frame’s stack.在 3.5 版更改: A list of named tuples
FrameInfo(frame, filename, lineno, function, code_context, index)
is returned.在 3.11 版更改: A list of
FrameInfo
objects is returned.
- inspect.getinnerframes(traceback, context=1)¶
Get a list of
FrameInfo
objects for a traceback’s frame and all inner frames. These frames represent calls made as a consequence of frame. The first entry in the list represents traceback; the last entry represents where the exception was raised.在 3.5 版更改: A list of named tuples
FrameInfo(frame, filename, lineno, function, code_context, index)
is returned.在 3.11 版更改: A list of
FrameInfo
objects is returned.
- inspect.currentframe()¶
Return the frame object for the caller’s stack frame.
CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns
None
.
- inspect.stack(context=1)¶
Return a list of
FrameInfo
objects for the caller’s stack. The first entry in the returned list represents the caller; the last entry represents the outermost call on the stack.在 3.5 版更改: A list of named tuples
FrameInfo(frame, filename, lineno, function, code_context, index)
is returned.在 3.11 版更改: A list of
FrameInfo
objects is returned.
- inspect.trace(context=1)¶
Return a list of
FrameInfo
objects for the stack between the current frame and the frame in which an exception currently being handled was raised in. The first entry in the list represents the caller; the last entry represents where the exception was raised.在 3.5 版更改: A list of named tuples
FrameInfo(frame, filename, lineno, function, code_context, index)
is returned.在 3.11 版更改: A list of
FrameInfo
objects is returned.
Fetching attributes statically¶
Both getattr()
and hasattr()
can trigger code execution when
fetching or checking for the existence of attributes. Descriptors, like
properties, will be invoked and __getattr__()
and __getattribute__()
may be called.
For cases where you want passive introspection, like documentation tools, this
can be inconvenient. getattr_static()
has the same signature as getattr()
but avoids executing code when it fetches attributes.
- inspect.getattr_static(obj, attr, default=None)¶
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.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 and Coroutines¶
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)¶
Get current state of a generator-iterator.
- Possible states are:
GEN_CREATED: Waiting to start execution.
GEN_RUNNING: Currently being executed by the interpreter.
GEN_SUSPENDED: Currently suspended at a yield expression.
GEN_CLOSED: Execution has completed.
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 hascr_running
andcr_frame
attributes.- Possible states are:
CORO_CREATED: Waiting to start execution.
CORO_RUNNING: Currently being executed by the interpreter.
CORO_SUSPENDED: Currently suspended at an await expression.
CORO_CLOSED: Execution has completed.
3.5 新版功能.
The current internal state of the generator can also be queried. This is mostly useful for testing purposes, to ensure that internal state is being updated as expected:
- 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 implementation detail: 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.
3.3 新版功能.
- inspect.getcoroutinelocals(coroutine)¶
This function is analogous to
getgeneratorlocals()
, but works for coroutine objects created byasync def
functions.3.5 新版功能.
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.
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 canyield from
coroutine objects. See PEP 492 for more details.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.
3.6 新版功能.
备注
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.
命令行界面¶
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