inspect — Inspect live objects¶
Source code: 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.
There are four main kinds of services provided by this module: type checking, getting source code, inspecting classes and functions, and examining the interpreter stack.
Types and members¶
The getmembers() function retrieves the members of an object such as a
class or module. The 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 (see Import-related attributes on module objects for module attributes):
Type |
Attribute |
Description |
|---|---|---|
class |
__doc__ |
documentation string |
__name__ |
name with which this class was defined |
|
__qualname__ |
qualified name |
|
__module__ |
name of module in which this class was defined |
|
__type_params__ |
A tuple containing the type parameters of a generic class |
|
method |
__doc__ |
documentation string |
__name__ |
name with which this method was defined |
|
__qualname__ |
qualified name |
|
__func__ |
function object containing implementation of method |
|
__self__ |
instance to which this
method is bound, or
|
|
__module__ |
name of module in which this method was defined |
|
function |
__doc__ |
documentation string |
__name__ |
name with which this function was defined |
|
__qualname__ |
qualified name |
|
__code__ |
code object containing compiled function bytecode |
|
__defaults__ |
tuple of any default values for positional or keyword parameters |
|
__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;
|
|
__type_params__ |
A tuple containing the type parameters of a generic function |
|
__module__ |
name of module in which this function was defined |
|
traceback |
tb_frame |
frame object at this level |
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) |
|
frame |
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_generator |
returns the generator or
coroutine object that
owns this frame, or
|
|
f_trace |
tracing function for this
frame, or |
|
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 |
|
code |
co_argcount |
number of arguments (not including keyword only arguments, * or ** args) |
co_code |
string of raw compiled bytecode |
|
co_cellvars |
tuple of names of cell variables (referenced by containing scopes) |
|
co_consts |
tuple of constants used in the bytecode |
|
co_filename |
name of file in which this code object was created |
|
co_firstlineno |
number of first line in Python source code |
|
co_flags |
bitmap of |
|
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 |
name with which this code object was defined |
|
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 |
number of local variables |
|
co_stacksize |
virtual machine stack space required |
|
co_varnames |
tuple of names of arguments and local variables |
|
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 |
|
generator |
__name__ |
name |
__qualname__ |
qualified name |
|
gi_frame |
frame |
|
gi_running |
is the generator running? |
|
gi_suspended |
is the generator suspended? |
|
gi_code |
code |
|
gi_yieldfrom |
object being iterated by
|
|
gi_state |
state of the generator,
one of |
|
async generator |
__name__ |
name |
__qualname__ |
qualified name |
|
ag_await |
object being awaited on,
or |
|
ag_frame |
frame |
|
ag_running |
is the generator running? |
|
ag_suspended |
is the generator suspended? |
|
ag_code |
code |
|
ag_state |
state of the async
generator, one of
|
|
coroutine |
__name__ |
name |
__qualname__ |
qualified name |
|
cr_await |
object being awaited on,
or |
|
cr_frame |
frame |
|
cr_running |
is the coroutine running? |
|
cr_suspended |
is the coroutine suspended? |
|
cr_code |
code |
|
cr_origin |
where coroutine was
created, or |
|
cr_state |
state of the coroutine,
one of |
|
builtin |
__doc__ |
documentation string |
__name__ |
original name of this function or method |
|
__qualname__ |
qualified name |
|
__self__ |
instance to which a
method is bound, or
module object a function
was defined in, or
|
Changed in version 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.
Changed in version 3.7: Add cr_origin attribute to coroutines.
Changed in version 3.10: Add __builtins__ attribute to functions.
Changed in version 3.11: Add gi_suspended attribute to generators.
Changed in version 3.11: Add cr_suspended attribute to coroutines.
Changed in version 3.12: Add ag_suspended attribute to async generators.
Changed in version 3.14: Add f_generator attribute to frames.
Changed in version 3.15: Add gi_state attribute to generators, cr_state attribute to
coroutines, and ag_state attribute to async generators.
- 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 thevalueobject of each member—is supplied, only members for which the predicate returns a true value are included.Note
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.Note
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.Added in version 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,Noneis 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.Changed in version 3.3: The function is based directly on
importlib.
- inspect.ismodule(object)¶
Return
Trueif the object is a module.
- inspect.isclass(object)¶
Return
Trueif the object is a class, whether built-in or created in Python code.This function returns
Falsefor generic aliases of classes, such aslist[int].
- inspect.ismethod(object)¶
Return
Trueif the object is a bound method written in Python.Note
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 theGreeternamespace) through an instance of theGreeterclass:>>> 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_hellothrough theGreeterclass will return the function itself. For this function,ismethod()will returnFalse, butisfunction()will returnTrue:>>> Greeter.say_hello <function Greeter.say_hello at 0x7f7503854a90> >>> ismethod(Greeter.say_hello) False >>> isfunction(Greeter.say_hello) True
See Methods for details.
- inspect.isfunction(object)¶
Return
Trueif the object is a Python function, which includes functions created by a lambda expression.See the note for
ismethod()for an example.
- inspect.isgeneratorfunction(object)¶
Return
Trueif the object is a Python generator function.It also returns
Truefor bound methods created from Python generator functions (see Methods for more information).Changed in version 3.8: Functions wrapped in
functools.partial()now returnTrueif the wrapped function is a Python generator function.Changed in version 3.10.6: Duck-typed function-like objects now return
Trueif their code object has theCO_GENERATORflag.Changed in version 3.13: Functions wrapped in
functools.partialmethod()now returnTrueif the wrapped function is a Python generator function.
- inspect.isgenerator(object)¶
Return
Trueif the object is a generator.
- inspect.iscoroutinefunction(object)¶
Return
Trueif the object is a coroutine function (a function defined with anasync defsyntax), afunctools.partial()wrapping a coroutine function, or a sync function marked withmarkcoroutinefunction().Added in version 3.5.
Changed in version 3.8: Functions wrapped in
functools.partial()now returnTrueif the wrapped function is a coroutine function.Changed in version 3.10.6: Duck-typed function-like objects now return
Trueif their code object has theCO_COROUTINEflag.Changed in version 3.12: Sync functions marked with
markcoroutinefunction()now returnTrue.Changed in version 3.13: Functions wrapped in
functools.partialmethod()now returnTrueif the wrapped function is a coroutine function.
- inspect.markcoroutinefunction(func)¶
Decorator to mark a callable as a coroutine function if it would not otherwise be detected by
iscoroutinefunction().This may be of use for sync functions that return a coroutine, if the function is passed to an API that requires
iscoroutinefunction().When possible, using an
async deffunction is preferred. Also acceptable is calling the function and testing the return withiscoroutine().Added in version 3.12.
- inspect.iscoroutine(object)¶
Return
Trueif the object is a coroutine created by anasync deffunction.Added in version 3.5.
- inspect.isawaitable(object)¶
Return
Trueif the object can be used inawaitexpression.Can also be used to distinguish generator-based coroutines from regular generators:
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)¶
Return
Trueif the object is an asynchronous generator function, for example:>>> async def agen(): ... yield 1 ... >>> inspect.isasyncgenfunction(agen) True
Added in version 3.6.
Changed in version 3.8: Functions wrapped in
functools.partial()now returnTrueif the wrapped function is an asynchronous generator function.Changed in version 3.10.6: Duck-typed function-like objects now return
Trueif their code object has theCO_ASYNC_GENERATORflag.Changed in version 3.13: Functions wrapped in
functools.partialmethod()now returnTrueif the wrapped function is a asynchronous generator function.
- inspect.isasyncgen(object)¶
Return
Trueif the object is an asynchronous generator iterator created by an asynchronous generator function.Added in version 3.6.
- inspect.istraceback(object)¶
Return
Trueif the object is a traceback.
- inspect.isframe(object)¶
Return
Trueif the object is a frame.
- inspect.iscode(object)¶
Return
Trueif the object is a code.
- inspect.isbuiltin(object)¶
Return
Trueif the object is a built-in function or a bound built-in method.
- inspect.ismethodwrapper(object)¶
Return
Trueif the type of object is aMethodWrapperType.These are instances of
MethodWrapperType, such as__str__(),__eq__()and__repr__().Added in version 3.11.
- inspect.isroutine(object)¶
Return
Trueif the object is a user-defined or built-in function or method.
- inspect.isabstract(object)¶
Return
Trueif the object is an abstract base class.
- inspect.ismethoddescriptor(object)¶
Return
Trueif the object is a method descriptor, but not ifisclass(),ismethod()orisfunction()is true.This, for example, is true of
int.__add__. An object passing this test has a__get__()method, but not a__set__()method or a__delete__()method. Beyond that, the set of attributes varies. A__name__attribute is usually sensible, and__doc__often is.Method descriptors that also pass any of the other tests (
isclass(),ismethod()orisfunction()) make this function returnFalse, simply because those other tests promise more – you can, for example, count on having the__func__attribute when an object passesismethod().Changed in version 3.13: This function no longer incorrectly reports objects with
__get__()and__delete__(), but not__set__(), as being method descriptors (such objects are data descriptors, not method descriptors).
- inspect.isdatadescriptor(object)¶
Return
Trueif the object is a data descriptor, but not ifisclass(),ismethod()orisfunction()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()andismemberdescriptor(), 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.Changed in version 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)¶
Return
Trueif the object is a getset descriptor.CPython implementation detail: getsets are attributes defined in extension modules via
PyGetSetDefstructures. For Python implementations without such types, this method will always returnFalse.
- inspect.ismemberdescriptor(object)¶
Return
Trueif the object is a member descriptor.CPython implementation detail: Member descriptors are attributes defined in extension modules via
PyMemberDefstructures. For Python implementations without such types, this method will always returnFalse.
Retrieving source code¶
- inspect.getdoc(object, *, inherit_class_doc=True, fallback_to_class_doc=True)¶
Get the documentation string for an object, cleaned up with
cleandoc(). If the documentation string for an object is not provided:if the object is a class and inherit_class_doc is true (by default), retrieve the documentation string from the inheritance hierarchy;
if the object is a method, a property or a descriptor, retrieve the documentation string from the inheritance hierarchy;
otherwise, if fallback_to_class_doc is true (by default), retrieve the documentation string from the class of the object.
Return
Noneif the documentation string is invalid or missing.Changed in version 3.5: Documentation strings are now inherited if not overridden.