Python Reference ยท Standard Library: Concurrency, Network and Tools
The inspect module
Reference for Python's inspect module: signature, Parameter, getmembers, isfunction and isclass checks, getdoc, getsource, currentframe and stack.
inspect asks questions about live Python objects: what parameters does this function take, which methods does this class have, what is its docstring, which line of source defines it, who called me? It is the tool behind help systems, documentation generators, dependency-injection containers and testing frameworks.
Most programs only need three things from it: inspect.signature() to read a callable's parameters, inspect.getmembers() to list attributes, and the is... predicates such as isfunction() and isclass() to ask what kind of object something is.
import inspect def greet(name, punct="!"): return name + punct print(inspect.signature(greet)) # (name, punct='!')
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Reading source code works for code that lives in files (read-only, because code typed into a browser editor has no file):
import inspect, json print(inspect.getsourcefile(json)) # path of json/__init__.py print(inspect.getsource(json.dumps)[:60]) # the function's source text print(inspect.getsourcelines(json.dumps)[1]) # first line number
Syntax
inspect.signature(callable, *, follow_wrapped=True) inspect.getmembers(object, predicate=None) inspect.getdoc(object) inspect.getsource(object) inspect.stack(context=1) inspect.currentframe()
| Function | Description |
|---|---|
signature(f) |
Returns a Signature with .parameters (an ordered mapping of Parameter), .return_annotation, .bind(*a, **kw) and .bind_partial(). |
Parameter |
Has name, kind, default (or inspect.Parameter.empty) and annotation. Kinds: POSITIONAL_ONLY, POSITIONAL_OR_KEYWORD, VAR_POSITIONAL, KEYWORD_ONLY, VAR_KEYWORD. |
getmembers(obj, predicate) |
List of (name, value) pairs sorted by name, optionally filtered. |
getdoc(obj) |
Docstring with indentation cleaned, inherited from a parent class if missing. |
getsource(obj), getsourcelines(obj), getsourcefile(obj) |
Source text, (lines, first_line) and file path. |
isclass, isfunction, ismethod, ismodule, isbuiltin, iscoroutinefunction, isgeneratorfunction, isabstract |
Predicates returning True or False. |
getmro(cls) |
The method resolution order tuple. |
stack(), currentframe(), getouterframes(frame) |
Call stack records and frame objects. |
getattr_static(obj, name) |
Looks up an attribute without running descriptors or __getattr__. |
get_annotations(obj) |
Returns annotations safely (Python 3.10+). |
Raises: TypeError from signature() when no signature can be found, OSError from getsource() when no source file is available, ValueError from some built-ins.
Usage notes
- Methods versus functions: accessed through the class, a method is a plain function (
isfunctionis true); accessed through an instance, it is a bound method (ismethodis true). getmembers()triggers properties. It reads every attribute, so a property that does work or raises can cause surprises. Usegetattr_static()orClass.__dict__to avoid running them.signature()of built-ins works for many but not all, because some C functions publish no signature metadata.getsource()needs files. It fails for code fromexec(), a REPL, or a browser runner, and for built-in or compiled extensions.- Frames keep objects alive. Delete frame variables (
del frame) when you are done, or reference cycles can delay cleanup. stack()is slow because it reads source lines for every frame. Usesys._getframe(1)orinspect.currentframe().f_backin hot code.- Decorators:
functools.wrapsletssignature()see through the wrapper to the original function (follow_wrapped=True). - Python 3.14 changes how annotations are evaluated lazily; prefer
inspect.get_annotations()orannotationlibover reading__annotations__directly.