Python's inspect Module: Examining Live Objects at Runtime

This article explains how the inspect module lets a Python program examine signatures, source code, the call stack and the members of its own objects, together with the costs and side effects that each form of introspection carries.

A yellow-green snake coiled tightly on a branch, one eye peering out from between its own coils in low light.
Photo by Samuel Weissgerber on Unsplash

A Python program can examine its own objects while it runs: it can ask a function which parameters it accepts, read the source code of a class, discover which function called the current one or list the members of an instance. This capacity is called introspection, and the module inspect of the standard library gathers the tools that make it reliable. The present article examines the four tasks for which the module is used most often, namely signatures, source code, the call stack and the members of objects, and for each one it identifies a cost or a side effect that the simplest examples conceal. Asking a running program about itself, instead of guessing from its documentation, is the secret weapon of this module.

Signatures: What a Function Accepts

The function inspect.signature returns a Signature object that describes every parameter of a callable: its name, its kind, its default value and its annotation. Its method bind goes further and checks a set of arguments against the signature without calling the function.

import inspect

def register(name, age, country="PE", *, active=True, **extra):
    return name

signature = inspect.signature(register)
print(signature)  # Output: (name, age, country='PE', *, active=True, **extra)
for parameter in signature.parameters.values():
    print(parameter.name, parameter.kind.name, parameter.default is inspect.Parameter.empty)
# Output: name POSITIONAL_OR_KEYWORD True
# Output: age POSITIONAL_OR_KEYWORD True
# Output: country POSITIONAL_OR_KEYWORD False
# Output: active KEYWORD_ONLY False
# Output: extra VAR_KEYWORD True

bound = signature.bind("Ada", 36, active=False)
bound.apply_defaults()
print(bound.arguments)  # Output: {'name': 'Ada', 'age': 36, 'country': 'PE', 'active': False, 'extra': {}}
try:
    signature.bind("Ada")
except TypeError as error:
    print(error)        # Output: missing a required argument: 'age'

The kinds distinguish ordinary parameters from keyword-only parameters, placed after *, and from the collector **extra; a parameter without a default value reports the marker inspect.Parameter.empty. The method bind, followed by apply_defaults, produces the exact mapping that the call would receive, which is how frameworks validate requests or build command-line interfaces from ordinary functions. For a function wrapped with functools.wraps, signature follows the attribute __wrapped__ by default and reports the parameters of the original function, a detail examined in the article devoted to decorators. Python 3.14 added the parameter annotation_format, which controls how annotations are returned now that they are evaluated lazily.

Source Code of Live Objects

The function inspect.getsource returns the text of a function, class, method or module, read from the file in which it was defined. That text can be parsed and analysed with the tools described in the article devoted to abstract syntax trees.

import ast
import inspect

def area(width, height):
    # The comment is part of the source text.
    return width * height

source = inspect.getsource(area)
print(source.splitlines()[0])                       # Output: def area(width, height):
print(type(ast.parse(source).body[0]).__name__)     # Output: FunctionDef

namespace = {}
exec("def generated():\n    return 1\n", namespace)
try:
    inspect.getsource(namespace["generated"])
except OSError as error:
    print(type(error).__name__)                     # Output: OSError
try:
    inspect.getsource(len)
except TypeError as error:
    print(type(error).__name__)                     # Output: TypeError

The source of area is read from its file, comments included, and parses into a single function definition. The function getsource does not keep the text in memory; it opens the file named by the code object, so it fails with OSError when no file exists, as for code created with exec or distributed only as compiled .pyc files, and it fails with TypeError for built-in functions such as len, which are written in C. If the file changed after the module was imported, the text returned may no longer match the code that is running.

Kill Cam: Reading the Call Stack

Many shooting games show a kill cam, a short replay that shows a defeated player how the decisive moment happened; the call stack offers the same retrospective view of a program, because it records the chain of calls that led to the current line. The function inspect.stack returns that chain as a list of records, whereas inspect.currentframe gives direct access to the current frame and, through f_back, to its caller.

import inspect
import timeit

def caller_name():
    frame = inspect.currentframe()
    try:
        return frame.f_back.f_code.co_name
    finally:
        del frame

def checkout():
    return caller_name()

print(checkout())  # Output: checkout

def full_stack():
    return [info.function for info in inspect.stack()]

def outer():
    return full_stack()

print(outer()[:2])  # Output: ['full_stack', 'outer']

fast = min(timeit.repeat(checkout, number=10_000, repeat=5))
slow = min(timeit.repeat(lambda: inspect.stack(), number=10_000, repeat=5))
print(slow > 20 * fast)  # Output: True

Both approaches identify the caller, but their costs differ by orders of magnitude. On the test machine, with CPython 3.12, reading f_back took about 0.14 microseconds, whereas inspect.stack() took about 295 microseconds, because by default it reads a line of source code for every frame of the stack; inspect.stack(0), which skips the source lines, still took about 55 microseconds. The finally clause follows the advice of the documentation: a frame kept in a local variable creates a reference cycle with the frame that contains it, and deleting the reference allows both to be released at once.

Members of Objects

The function inspect.getmembers lists the attributes of an object as pairs of name and value, optionally filtered by a predicate such as inspect.ismethod. The filter, however, is applied after each value has been obtained, which has a consequence for properties.

import inspect

class Account:
    def __init__(self, owner):
        self.owner = owner

    @property
    def balance(self):
        print("query executed")
        return 100

    def deposit(self, amount):
        pass

    def _audit(self):
        pass

account = Account("Ada")
methods = [name for name, _ in inspect.getmembers(account, inspect.ismethod)]
# Output: query executed
print(methods)  # Output: ['__init__', '_audit', 'deposit']

static = inspect.getattr_static(account, "balance")
print(type(static).__name__)  # Output: property

Although only methods were requested, the property balance was executed, because getmembers reads every attribute with getattr before applying the filter; with a property that queries a database or a remote service, a simple listing triggers that work. The list also contains __init__ and _audit, so excluding names that begin with a double underscore does not remove private helpers with a single one. The function inspect.getattr_static, available since Python 3.2, retrieves an attribute without running descriptors, __getattr__ or __getattribute__, and returns the property object itself, the mechanism explained in the article devoted to descriptors.

Pitfalls of Introspection

Introspection observes a program from the inside, so every observation can alter what it measures or depend on details outside the code. Six pitfalls are distinguished, which are the following:

  1. Expensive stack inspection. inspect.stack() reads source lines for every frame; in code that runs often, currentframe().f_back or stack(0) is far cheaper.
  2. Frame reference cycles. Frames kept in variables delay the release of every object they reference; they must be deleted in a finally clause or cleared.
  3. Side effects of listing. getmembers evaluates properties and dynamic attributes; getattr_static inspects without evaluating.
  4. Missing or stale source. getsource depends on files that may not exist or may have changed since the import.
  5. Wrapped functions. signature follows __wrapped__ by default; follow_wrapped=False returns the signature of the wrapper itself.
  6. Implementation details. Frame attributes and the behaviour of built-in objects vary between interpreters; code that depends on them may not run on implementations other than CPython.

Choosing an Introspection Tool

Consequently, each question about a running program has a tool that answers it at the lowest cost, as the following table summarizes.

Question Recommended approach
Which arguments does a callable accept? inspect.signature
Are these arguments valid for that callable? Signature.bind and apply_defaults
What is the source of a function or class? inspect.getsource, with OSError and TypeError handled
Which function called the current one? inspect.currentframe().f_back, deleting the frame afterwards
What is the complete chain of calls, occasionally? inspect.stack() or traceback.extract_stack()
Which attributes does an object have, without side effects? inspect.getattr_static or dir
Is an object a function, method, class or module? The predicates isfunction, ismethod, isclass, ismodule

Conclusion

It is concluded that the module inspect lets a program read the signatures, source code, call stack and members of its own objects, and that each of these readings has a price: the stack is expensive to traverse in full, frames create reference cycles, listing members runs properties and source code depends on files outside the program. This magic is the basis of debuggers, test frameworks and tools that adapt to the functions they receive. Objects can also be built to deceive these inspections, presenting themselves as other objects, and such proxies are developed in a future article of this series.