Python 3.3+inspectfunction
inspect.signature()
signatures
Returns a Signature object for a callable: its parameters, their kinds, default values and annotations.
Syntax
inspect.signature(callable, *, follow_wrapped=True, eval_str=False) -> Signature
Its main use is checking arguments before a call: signature(f).bind(*args, **kw) raises TypeError for the same reason the call would, but runs nothing. By default it follows __wrapped__ and shows the original signature of a decorated function, and for a class the __init__ parameters without self. Some built-ins (max, dict) have no signature and raise ValueError. Since 3.14 annotations are lazy: a def naming a not-yet-defined name succeeds, but signature() raises NameError unless you pass annotation_format.
Examples
import inspect
def send(to, text='', *, retries=3):
pass
sig = inspect.signature(send)
print(sig) # → (to, text='', *, retries=3)
try:
sig.bind(text='hi') # send не вызывается
except TypeError as e:
print(e) # → missing a required argument: 'to'
print(sig.bind('ann', retries=5).arguments) # → {'to': 'ann', 'retries': 5}
import inspect
class Point:
def __init__(self, x, y=0):
pass
print(inspect.signature(Point)) # → (x, y=0)
try:
inspect.signature(max)
except ValueError as e:
print(type(e).__name__) # → ValueError
# Python 3.14+
import annotationlib, inspect
def load(path: Config) -> None: # Config ещё не определён — def проходит
pass
fmt = annotationlib.Format.STRING
print(inspect.signature(load, annotation_format=fmt)) # → (path: 'Config') -> 'None'
try:
inspect.signature(load)
except NameError as e:
print(e) # → name 'Config' is not defined
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy