Introspection with inspect

Published by Brayan K

The inspect module lets your program examine its own functions, classes, and modules at runtime — reading signatures, source code, and members on the fly.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A signature describes how arguments bind, not what values mean

inspect lets a program examine live Python objects. A command registry can use signatures to explain accepted arguments, while a documentation tool can inspect a function without calling it. Treat this as metadata about an interface, not proof that arbitrary input is valid or that executing the object is safe.

from inspect import signature

def schedule(task, /, retries=2, *, urgent=False):
    return task, retries, urgent

sig = signature(schedule)
print(sig)
print([(name, parameter.kind.name)
       for name, parameter in sig.parameters.items()])
print(sig.parameters["retries"].default)

# ✅ Expected output:
# (task, /, retries=2, *, urgent=False)
# [('task', 'POSITIONAL_ONLY'), ('retries', 'POSITIONAL_OR_KEYWORD'), ('urgent', 'KEYWORD_ONLY')]
# 2

The slash marks positional-only parameters and the star introduces keyword-only parameters. Signature.parameters preserves declaration order and gives Parameter objects with kind, default and annotation metadata. Advanced Functions & Parameters Masterclass owns parameter syntax; inspect reads that already-defined contract.

from inspect import signature

def schedule(task, /, retries=2, *, urgent=False):
    return task, retries, urgent

bound = signature(schedule).bind("review", urgent=True)
print(dict(bound.arguments))
bound.apply_defaults()
print(dict(bound.arguments))
print(schedule(*bound.args, **bound.kwargs))

# ✅ Expected output:
# {'task': 'review', 'urgent': True}
# {'task': 'review', 'retries': 2, 'urgent': True}
# ('review', 2, True)

bind checks call shape and returns BoundArguments; it does not call the function. Defaults omitted by the caller are absent until apply_defaults fills them. The args and kwargs views can then forward the bound call. This separates interface checking from the operation itself.

from inspect import signature

def schedule(task, *, urgent=False):
    return task

signature(schedule).bind()

# ✅ Expected error:
# TypeError: missing a required argument: 'task'

bind_partial permits a partial argument set, which is useful while constructing a call. It does not certify that the function can be called yet. A partially bound call can still be missing required arguments after defaults have been applied.

Annotations are metadata, not automatic runtime validation

from inspect import signature

def double(value: int) -> int:
    return value * 2

bound = signature(double).bind("ha")
print(bound.arguments["value"])
print(double(*bound.args, **bound.kwargs))
print(signature(double).parameters["value"].annotation is int)

# ✅ Expected output:
# ha
# haha
# True

The string fits the one-argument call shape. Python does not enforce the int annotation here, and multiplying the string repeats it. A schema validator or explicit domain checks must enforce value constraints. Advanced Type Hints (Generics, Protocol, TypedDict) owns static typing contracts.

Do not evaluate annotation strings from untrusted objects merely to display help. Annotation resolution can execute code, and Python 3.14 adds further annotation-introspection options. The examples use simple trusted annotations and APIs available across Python 3.11–3.14.

Bound methods and wrappers change the visible interface

from inspect import signature, ismethod, isfunction

class Worker:
    def run(self, count=1):
        return count

worker = Worker()
print(signature(Worker.run))
print(signature(worker.run))
print(isfunction(Worker.run))
print(ismethod(worker.run))

# ✅ Expected output:
# (self, count=1)
# (count=1)
# True
# True

The class attribute is a function whose signature includes self. Access through an instance creates a bound method, so the visible call signature no longer requires the caller to supply self. Calling every callable a function loses this distinction.

from functools import wraps
from inspect import signature, unwrap

def original(value, *, scale=2):
    return value * scale

@wraps(original)
def wrapper(*args, **kwargs):
    return original(*args, **kwargs)

print(signature(wrapper))
print(signature(wrapper, follow_wrapped=False))
print(unwrap(wrapper) is original)

# ✅ Expected output:
# (value, *, scale=2)
# (*args, **kwargs)
# True

wraps records the original function through __wrapped__. signature follows that chain by default, which is usually the useful public interface. follow_wrapped=False reveals the wrapper’s own argument list. Decorators & Advanced Features owns preserving wrapper metadata; inspect lets you choose which interface to examine.

Ordinary attribute inspection can run code

from inspect import getattr_static

events = []
class Record:
    @property
    def score(self):
        events.append("computed")
        return 8

record = Record()
descriptor = getattr_static(record, "score")
print(isinstance(descriptor, property))
print(events)
print(getattr(record, "score"))
print(events)

# ✅ Expected output:
# True
# []
# 8
# ['computed']

getattr_static avoids ordinary descriptor and dynamic attribute lookup for the requested attribute. It can return the property object rather than the property’s value, and it can miss attributes created dynamically. Do not immediately invoke the returned descriptor if the purpose was to avoid running it.

from inspect import getmembers, getmembers_static

events = []
class Record:
    @property
    def score(self):
        events.append("read")
        return 8

record = Record()
static_members = dict(getmembers_static(record))
print(isinstance(static_members["score"], property))
print(events)
ordinary_members = dict(getmembers(record))
print(ordinary_members["score"])
print(events)

# ✅ Expected output:
# True
# []
# 8
# ['read']

getmembers performs ordinary attribute lookup and can trigger properties. getmembers_static is available throughout the supported versions and returns unresolved descriptors where appropriate. Neither should be described as a security sandbox for arbitrary hostile objects; dynamic member discovery has its own limits. Properties & Descriptors owns descriptor execution rules.

Source retrieval depends on source actually being available

from importlib.util import spec_from_file_location, module_from_spec
from inspect import getsource
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    module_file = Path(directory) / "example.py"
    module_file.write_text("def square(value):\n    return value * value\n",
                           encoding="utf-8")
    spec = spec_from_file_location("inspection_example", module_file)
    module = module_from_spec(spec)
    spec.loader.exec_module(module)
    source = getsource(module.square)
    print(source.strip())
    print(module.square(3))

# ✅ Expected output:
# def square(value):
#     return value * value
# 9

A live function is not a guarantee that its source file is accessible. Dynamically generated code, removed files, interactive environments and native implementations can lack retrievable source. Handle OSError for unavailable source and TypeError for unsupported object kinds instead of promising a source viewer for every callable.

from inspect import getsource

getsource(len)

# ✅ Expected error:
# TypeError: module, class, method, function, traceback, frame, or code object was expected, got builtin_function_or_method

The worked example creates its own small module file, inspects it while it exists and prints only its source text. It does not depend on the editor exposing an internal filename. Temporary Files & Directories owns the scratch-file lifetime.

A generator function and a generator object are different objects

from inspect import isgeneratorfunction, isgenerator, getgeneratorstate

def values():
    yield 3

iterator = values()
print(isgeneratorfunction(values))
print(isgenerator(iterator))
print(getgeneratorstate(iterator))
print(next(iterator))
print(getgeneratorstate(iterator))
iterator.close()
print(getgeneratorstate(iterator))

# ✅ Expected output:
# True
# True
# GEN_CREATED
# 3
# GEN_SUSPENDED
# GEN_CLOSED

Calling the generator function creates the generator object; advancing it executes the body. Classification functions answer specific questions rather than a single “is callable” question. Generators & Iterators Mastery owns generator execution and cleanup. Avoid retaining frame objects casually during debugging: references to frames can keep local objects alive.

Complete a bound call with defaults

Inspect a function, bind its required value, fill its default scale, and forward the bound args and kwargs. The hints supply the binding and default-application methods.

from inspect import signature

def scale(value, *, factor=3):
    return value * factor

bound = signature(scale).___(4)
bound.___()
print(dict(bound.arguments))
print(scale(*bound.args, **bound.kwargs))

# 👉 replace ___ with bind
# 👉 replace ___ with apply_defaults

# ✅ Expected output:
# {'value': 4, 'factor': 3}
# 12

Build help and call-shape checking for an explicit command registry

Register two trusted functions: add with two required operands, and scale with one operand and a keyword-only factor defaulting to 2. Generate sorted help lines from their signatures. Bind and execute scale with value 5 and factor 3, then show a clear binding error when add is missing its second operand. Keep the command registry explicit; do not discover and execute every attribute of an arbitrary object.

from inspect import signature

def add(left, right):
    return left + right

def scale(value, *, factor=2):
    return value * factor

commands = {"scale": scale, "add": add}
for name in sorted(commands):
    print(name + str(signature(commands[name])))

operation = commands["scale"]
bound = signature(operation).bind(5, factor=3)
bound.apply_defaults()
print(operation(*bound.args, **bound.kwargs))
try:
    signature(commands["add"]).bind(1)
except TypeError as error:
    print(error)

# ✅ Expected output:
# add(left, right)
# scale(value, *, factor=2)
# 15
# missing a required argument: 'right'

Practice quiz

What does this program print? from inspect import signature def f(value, *, scale=2): return value * scale bound = signature(f).bind(3) print(dict(bound.arguments))

  • {'value': 3}
  • {'value': 3, 'scale': 2}
  • 6
  • {}

Answer: {'value': 3}. bind records supplied arguments; defaults are added only by apply_defaults.

What does this program print? from inspect import signature def f(value, *, scale=2): return value * scale bound = signature(f).bind(3) bound.apply_defaults() print(dict(bound.arguments))

  • {'value': 3}
  • {'value': 3, 'scale': 2}
  • 6
  • {'scale': 3}

Answer: {'value': 3, 'scale': 2}. apply_defaults fills the omitted keyword-only default.

What does successful signature binding validate?

  • All annotated types
  • Business rules and permissions
  • The positional/keyword call shape
  • That the callable is safe to execute

Answer: The positional/keyword call shape. Binding is interface-shape validation, not value or security validation.

What does this program print? from inspect import signature class A: def f(self, x=1): return x print(signature(A().f))

  • (self, x=1)
  • (self)
  • ()
  • (x=1)

Answer: (x=1). The bound instance supplies self.

What does this program print? from inspect import getattr_static class A: @property def x(self): return 7 print(isinstance(getattr_static(A(), "x"), property))

  • True
  • False
  • 7
  • None

Answer: True. Static lookup returns the descriptor without evaluating the property.

Why can getsource fail for a valid callable?

  • Every callable always has a readable .py file
  • The source may be unavailable or the callable implemented natively
  • Only incorrect functions lack source
  • Calling it once always fixes the problem

Answer: The source may be unavailable or the callable implemented natively. Live behavior and retrievable source are separate capabilities.

What does this program print? from inspect import isgeneratorfunction, isgenerator def values(): yield 1 print(isgeneratorfunction(values)) print(isgenerator(values()))

  • False True
  • True False
  • True True
  • False False

Answer: True True. The function is classified by its definition, and the returned object by its runtime kind.

What does follow_wrapped=False request from signature?

  • Execution of the wrapper
  • Deletion of __wrapped__
  • Automatic type checking
  • The wrapper’s own call signature rather than following __wrapped__

Answer: The wrapper’s own call signature rather than following __wrapped__. It changes which interface metadata is inspected.

Continue this course

Related lessons