Python 3.3+inspectterm
inspect.Signature
signatures
A signature object: the ordered parameters of a callable plus its return annotation. inspect.signature() returns it; bind() checks a call.
Syntax
sig = inspect.signature(func); sig.parameters; sig.return_annotation; sig.bind(*args, **kwargs)
You rarely call the constructor: get a signature from inspect.signature(f), and build one by hand only to expose it via __signature__. The object is immutable, so changes go through replace(). bind() checks arguments without calling the function and raises a TypeError just like a real call would. Some built-ins (max, range, dict) have no signature at all, which is a ValueError rather than an empty result; the legacy getfullargspec is no better and also loses the '/'.
Examples
import inspect
def f(a, b=2, *args, c, **kw): pass
sig = inspect.signature(f)
print(sig) # → (a, b=2, *args, c, **kw)
print(list(sig.parameters)) # → ['a', 'b', 'args', 'c', 'kw']
try:
sig.bind(1)
except TypeError as e:
print(e) # → missing a required argument: 'c'
import inspect
P = inspect.Parameter
params = [P('x', P.POSITIONAL_OR_KEYWORD), P('y', P.KEYWORD_ONLY, default=0)]
print(inspect.Signature(params, return_annotation=int)) # → (x, *, y=0) -> int
bad = [P('a', P.POSITIONAL_OR_KEYWORD, default=1), P('b', P.POSITIONAL_OR_KEYWORD)]
try:
inspect.Signature(bad)
except ValueError as e:
print(e) # → non-default argument follows default argument
import inspect
print(inspect.signature(len)) # → (obj, /)
try:
inspect.signature(max)
except ValueError as e:
print(e) # → no signature found for builtin <built-in function max>
See also
Open in the full glossarydocs.python.orgReport an inaccuracy