On this page
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
- Break reference cycles when holding stack frames: If you store
frame = inspect.currentframe(), delete it infinally: del frameto avoid keeping local variables alive. getsource()fails on dynamically generated or REPL-defined functions: HandleOSError/TypeErrorwhen source files aren't on disk.inspect.signature()follows__wrapped__automatically: Decorators using@functools.wrapsexpose the original function's parameters cleanly.- Avoid
inspect.stack()in hot loops: Walking frames and reading source files is slow; usesys._getframe()ortraceback.extract_stack()if you only need filenames and line numbers.
Common Functions
- inspect.classify_class_attrs() —
classify_class_attrs(cls)— Return list of attribute-descriptor tuples. - inspect.cleandoc() —
cleandoc(doc)— Clean up indentation from docstrings. - inspect.currentframe() —
currentframe()— Return the frame of the caller or None if this is not possible. - inspect.findsource() —
findsource(object)— Return the entire source file and starting line number for an object. - inspect.formatannotation() —
formatannotation(annotation, base_module=None, *, quote_annotation_strings=True)—inspect.formatannotation()function. - inspect.formatannotationrelativeto() —
formatannotationrelativeto(object)—inspect.formatannotationrelativeto()function. - inspect.formatargvalues() —
formatargvalues(args, varargs, varkw, locals, formatarg=<class 'str'>, formatvarargs=<function <lambda> at 0x109399850>, formatvarkw=<function <lambda> at 0x109399900>, formatvalue=<function <lambda> at 0x1093999b0>)— Format an argument spec from the 4 values returned by getargvalues. - inspect.get_annotations() —
get_annotations(obj, *, globals=None, locals=None, eval_str=False, format=<Format.VALUE: 1>)— Compute the annotations dict for an object. - inspect.getabsfile() —
getabsfile(object, _filename=None)— Return an absolute path to the source or compiled file for an object. - inspect.getargs() —
getargs(co)— Get information about the arguments accepted by a code object. - inspect.getargvalues() —
getargvalues(frame)— Get information about arguments passed into a particular frame. - inspect.getasyncgenlocals() —
getasyncgenlocals(agen)— Get the mapping of asynchronous generator local variables to their current values. - inspect.getasyncgenstate() —
getasyncgenstate(agen)— Get current state of an asynchronous generator object. - inspect.getattr_static() —
getattr_static(obj, attr, default=<object object at 0x1040b4700>)— Retrieve attributes without triggering dynamic lookup via the descriptor protocol, getattr or getattribute. - inspect.getblock() —
getblock(lines)— Extract the block of code at the top of the given list of lines. - inspect.getcallargs() —
getcallargs(func, /, *positional, **named)— Get the mapping of arguments to values. - inspect.getclasstree() —
getclasstree(classes, unique=False)— Arrange the given list of classes into a hierarchy of nested lists. - inspect.getclosurevars() —
getclosurevars(func)— Get the mapping of free variables to their current values. - inspect.getcomments() —
getcomments(object)— Get lines of comments immediately preceding an object's source code. - inspect.getcoroutinelocals() —
getcoroutinelocals(coroutine)— Get the mapping of coroutine local variables to their current values. - inspect.getcoroutinestate() —
getcoroutinestate(coroutine)— Get current state of a coroutine object. - inspect.getdoc() —
getdoc(object)— Get the documentation string for an object. - inspect.getfile() —
getfile(object)— Work out which source or compiled file an object was defined in. - inspect.getframeinfo() —
getframeinfo(frame, context=1)— Get information about a frame or traceback object. - inspect.getfullargspec() —
getfullargspec(func)— Get the names and default values of a callable object's parameters. - inspect.getgeneratorlocals() —
getgeneratorlocals(generator)— Get the mapping of generator local variables to their current values. - inspect.getgeneratorstate() —
getgeneratorstate(generator)— Get current state of a generator-iterator. - inspect.getinnerframes() —
getinnerframes(tb, context=1)— Get a list of records for a traceback's frame and all lower frames. - inspect.getlineno() —
getlineno(frame)— Get the line number from a frame object, allowing for optimization. - inspect.getmembers() —
getmembers(object, predicate=None)— Return all members of an object as (name, value) pairs sorted by name. - inspect.getmembers_static() —
getmembers_static(object, predicate=None)— Return all members of an object as (name, value) pairs sorted by name without triggering dynamic lookup via the descriptor protocol, getattr or getattribute. Optionally, only return members that - inspect.getmodule() —
getmodule(object, _filename=None)— Return the module an object was defined in, or None if not found. - inspect.getmodulename() —
getmodulename(path)— Return the module name for a given file, or None. - inspect.getmro() —
getmro(cls)— Return tuple of base classes (including cls) in method resolution order. - inspect.getouterframes() —
getouterframes(frame, context=1)— Get a list of records for a frame and all higher (calling) frames.
Classes & Objects
- inspect.ArgInfo — ArgInfo(args, varargs, keywords, locals) (Methods:
.count(),.index()) - inspect.Arguments — Arguments(args, varargs, varkw) (Methods:
.count(),.index()) - inspect.Attribute — Attribute(name, kind, defining_class, object) (Methods:
.count(),.index()) - inspect.BlockFinder — Provide a tokeneater() method to detect the end of a code block. (Methods:
.tokeneater()) - inspect.BoundArguments — Result of
Signature.bindcall. Holds the mapping of arguments to the function's parameters. (Methods:.apply_defaults(),.args(),.kwargs(),.signature()) - inspect.BufferFlags —
inspect.BufferFlagsclass. (Methods:.as_integer_ratio(),.bit_count(),.bit_length(),.conjugate(),.from_bytes(),.is_integer()) - inspect.ClassFoundException —
inspect.ClassFoundExceptionclass. (Methods:.add_note(),.with_traceback()) - inspect.ClosureVars — ClosureVars(nonlocals, globals, builtins, unbound) (Methods:
.count(),.index()) - inspect.EndOfBlock —
inspect.EndOfBlockclass. (Methods:.add_note(),.with_traceback()) - inspect.FrameInfo —
inspect.FrameInfoclass. (Methods:.count()) - inspect.FullArgSpec — FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations) (Methods:
.count(),.index()) - inspect.Parameter — Represents a parameter in a function signature. (Methods:
.annotation(),.default(),.empty(),.kind(),.name(),.replace()) - inspect.Signature — A Signature object represents the overall signature of a function. (Methods:
.bind(),.bind_partial(),.empty(),.format(),.from_callable(),.parameters()) - inspect.Traceback —
inspect.Tracebackclass. (Methods:.count())
Constants & Attributes
inspect.AGEN_CLOSED(str) ='AGEN_CLOSED'inspect.AGEN_CREATED(str) ='AGEN_CREATED'inspect.AGEN_RUNNING(str) ='AGEN_RUNNING'inspect.AGEN_SUSPENDED(str) ='AGEN_SUSPENDED'inspect.CORO_CLOSED(str) ='CORO_CLOSED'inspect.CORO_CREATED(str) ='CORO_CREATED'inspect.CORO_RUNNING(str) ='CORO_RUNNING'inspect.CORO_SUSPENDED(str) ='CORO_SUSPENDED'inspect.CO_ASYNC_GENERATOR(int) =512inspect.CO_COROUTINE(int) =128inspect.CO_GENERATOR(int) =32inspect.CO_HAS_DOCSTRING(int) =67108864inspect.CO_ITERABLE_COROUTINE(int) =256inspect.CO_METHOD(int) =134217728inspect.CO_NESTED(int) =16
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/importlib
- tuts/python3/stdlib_module/inspect/ArgInfo
- tuts/python3/stdlib_module/inspect/Arguments
- tuts/python3/stdlib_module/inspect/Attribute
- tuts/python3/stdlib_module/inspect/BlockFinder
- tuts/python3/stdlib_module/inspect/BoundArguments
- tuts/python3/stdlib_module/inspect/BufferFlags
- tuts/python3/stdlib_module/inspect/ClassFoundException
- tuts/python3/stdlib_module/inspect/classify_class_attrs
- tuts/python3/stdlib_module/inspect/cleandoc
- tuts/python3/stdlib_module/inspect/ClosureVars
- tuts/python3/stdlib_module/inspect/currentframe
- tuts/python3/stdlib_module/inspect/EndOfBlock
- tuts/python3/stdlib_module/inspect/findsource
- tuts/python3/stdlib_module/inspect/formatannotation
- tuts/python3/stdlib_module/inspect/formatannotationrelativeto
- tuts/python3/stdlib_module/inspect/formatargvalues
- tuts/python3/stdlib_module/inspect/FrameInfo
- tuts/python3/stdlib_module/inspect/FullArgSpec
- tuts/python3/stdlib_module/inspect/get_annotations
- tuts/python3/stdlib_module/inspect/getabsfile
- tuts/python3/stdlib_module/inspect/getargs
- tuts/python3/stdlib_module/inspect/getargvalues
- tuts/python3/stdlib_module/inspect/getasyncgenlocals
- tuts/python3/stdlib_module/inspect/getasyncgenstate
- tuts/python3/stdlib_module/inspect/getattr_static
- tuts/python3/stdlib_module/inspect/getblock
- tuts/python3/stdlib_module/inspect/getcallargs
- tuts/python3/stdlib_module/inspect/getclasstree
- tuts/python3/stdlib_module/inspect/getclosurevars
- tuts/python3/stdlib_module/inspect/getcomments
- tuts/python3/stdlib_module/inspect/getcoroutinelocals
- tuts/python3/stdlib_module/inspect/getcoroutinestate
- tuts/python3/stdlib_module/inspect/getdoc
- tuts/python3/stdlib_module/inspect/getfile
- tuts/python3/stdlib_module/inspect/getframeinfo
- tuts/python3/stdlib_module/inspect/getfullargspec
- tuts/python3/stdlib_module/inspect/getgeneratorlocals
- tuts/python3/stdlib_module/inspect/getgeneratorstate
- tuts/python3/stdlib_module/inspect/getinnerframes
- tuts/python3/stdlib_module/inspect/getlineno
- tuts/python3/stdlib_module/inspect/getmembers
- tuts/python3/stdlib_module/inspect/getmembers_static
- tuts/python3/stdlib_module/inspect/getmodule
- tuts/python3/stdlib_module/inspect/getmodulename
- tuts/python3/stdlib_module/inspect/getmro
- tuts/python3/stdlib_module/inspect/getouterframes
- tuts/python3/stdlib_module/inspect/Parameter
- tuts/python3/stdlib_module/inspect/Signature
- tuts/python3/stdlib_module/inspect/Traceback
- tuts/python3/stdlib_module/io
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/tutorials/advanced_python_internals/python_object_mro_and_initialization
- tuts/python3/tutorials/core_fundamentals/functions
- tuts/python3/tutorials/intermediate_python_and_software_engineering/type_hinting_and_static_analysis
Related notes
- tuts/python3/stdlib_module/importlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/inspect/ArgInfo Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/inspect/Arguments Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/inspect/Attribute Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/inspect/BlockFinder Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/inspect/BoundArguments Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/inspect/BufferFlags Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/inspect/ClassFoundException Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/inspect/classify_class_attrs Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/inspect/cleandoc Linked here; links to this page; shared tags: #stdlib