Source

python-clinic / Doc / library / inspect.rst

Full commit

:mod:`inspect` --- Inspect live objects

Source code: :source:`Lib/inspect.py`


The :mod:`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 :func:`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 :func:`getmembers`. They also help you determine when you can expect to find the following special attributes:

Type Attribute Description
module __doc__ documentation string
  __file__ filename (missing for built-in modules)
class __doc__ documentation string
  __module__ name of module in which this class was defined
method __doc__ documentation string
  __name__ name with which this method was defined
  __func__ function object containing implementation of method
  __self__ instance to which this method is bound, or None
function __doc__ documentation string
  __name__ name with which this function was defined
  __code__ code object containing compiled function :term:`bytecode`
  __defaults__ tuple of any default values for arguments
  __globals__ global namespace 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_restricted 0 or 1 if frame is in restricted execution mode
  f_trace tracing function for this frame, or None
code co_argcount number of arguments (not including * or ** args)
  co_code string of raw compiled bytecode
  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: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
  co_lnotab encoded mapping of line numbers to bytecode indices
  co_name name with which this code object was defined
  co_names tuple of names of local variables
  co_nlocals number of local variables
  co_stacksize virtual machine stack space required
  co_varnames tuple of names of arguments and local variables
builtin __doc__ documentation string
  __name__ original name of this function or method
  __self__ instance to which a method is bound, or None

Retrieving source code

Introspecting callables with the Signature object

The Signature object represents the call signature of a callable object and its return annotation. To retrieve a Signature object, use the :func:`signature` function.

A Signature object represents the call signature of a function and its return annotation. For each parameter accepted by the function it stores a :class:`Parameter` object in its :attr:`parameters` collection.

Signature objects are immutable. Use :meth:`Signature.replace` to make a modified copy.

Parameter objects are immutable. Instead of modifying a Parameter object, you can use :meth:`Parameter.replace` to create a modified copy.

Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call. Holds the mapping of arguments to the function's parameters.

The :attr:`args` and :attr:`kwargs` 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)

Classes and functions

The interpreter stack

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.

Note

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 :keyword:`finally` clause. This is also important if the cycle detector was disabled when Python was compiled or using :func:`gc.disable`. For example:

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

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.

Fetching attributes statically

Both :func:`getattr` and :func:`hasattr` can trigger code execution when fetching or checking for the existence of attributes. Descriptors, like properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__` may be called.

For cases where you want passive introspection, like documentation tools, this can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr` but avoids executing code when it fetches attributes.

:func:`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 a Generator

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. :func:`getgeneratorstate` allows the current state of a generator to be determined easily.

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: