On this page
  1. inspect
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Validating & Inspecting Callable Parameters Dynamically
  7. 2. Classifying Callables & Coroutines
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

inspect

Prev: importlib | Up: stdlib_module | Next: io
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — inspect
Tags: #public #python3 #stdlib


Import

import inspect

Overview

Runtime introspection of live Python objects: function signatures (signature), parameter defaults and annotations, source code (getsource, getfile), class hierarchies (getmro), coroutine/generator state, and call-stack frames. Essential for CLI builders, dependency injection, test runners, and documentation generators.

Quick Start

import inspect

def greet(name: str, count: int = 1, *, loud: bool = False) -> str:
    return (f"Hello, {name}!" * count).upper() if loud else f"Hello, {name}!" * count

sig = inspect.signature(greet)
bound = sig.bind("Ada", loud=True)
bound.apply_defaults()
assert bound.arguments == {"name": "Ada", "count": 1, "loud": True}

Implementation Walkthrough

1. Validating & Inspecting Callable Parameters Dynamically

import inspect

def required_params(fn) -> list[str]:
    sig = inspect.signature(fn)
    return [
        name
        for name, param in sig.parameters.items()
        if param.default is inspect.Parameter.empty
        and param.kind not in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)
    ]

assert required_params(lambda a, b=2, *args, c: None) == ["a", "c"]

2. Classifying Callables & Coroutines

import inspect

async def fetch() -> str:
    return "ok"

assert inspect.iscoroutinefunction(fetch)
assert not inspect.isgeneratorfunction(fetch)

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes