Python 3.3+inspectterm
inspect.Parameter
signatures
A single parameter of a signature: its name, kind (positional, keyword, *args, **kwargs), default value and annotation.
Syntax
inspect.Parameter(name, kind, *, default=Parameter.empty, annotation=Parameter.empty)
'No default' is Parameter.empty, not None: default=None is a real default, so checking 'p.default is None' mixes up the two cases. Read the kind from p.kind (POSITIONAL_ONLY … VAR_KEYWORD) instead of guessing from the stars in str(p); kinds are ordered and compare with <. The object is immutable: assigning p.default raises AttributeError, and p.replace(default=...) gives a modified copy.
Examples
import inspect
def f(a, /, b, *args, c, d=None, **kw): pass
for p in inspect.signature(f).parameters.values():
print(p.name, p.kind.name)
# → a POSITIONAL_ONLY / b POSITIONAL_OR_KEYWORD / args VAR_POSITIONAL / c KEYWORD_ONLY / d KEYWORD_ONLY / kw VAR_KEYWORD
# Python 3.11+
import inspect
params = inspect.signature(lambda c, d=None: 0).parameters
print(params['c'].default is inspect.Parameter.empty) # → True
print(params['d'].default is inspect.Parameter.empty, params['d'].default) # → False None
print(params['d'].replace(default=5)) # → d=5
try:
params['d'].default = 5
except AttributeError as e:
print(e) # → property 'default' of 'Parameter' object has no setter
See also
Open in the full glossarydocs.python.orgReport an inaccuracy