Sub topic 13
Inspecting defaults and signatures at runtime
This chapter assumes you can define functions with default values, know the difference between positional and keyword arguments, and understand why defaults are evaluated once at definition time. Here you will read that stored information back from a running program.
Where Python stores a signature
When a def statement runs, Python creates a function object. That object keeps the default values as data. Positional defaults go in __defaults__, a tuple. Keyword-only defaults go in __kwdefaults__, a dict.
import inspect
def f(a, b=2, *, c=3):
pass
print(inspect.signature(f)) # (a, b=2, *, c=3)
print(f.__defaults__) # (2,)
print(f.__kwdefaults__) # {'c': 3}__defaults__ holds only the defaults, not every parameter. It lines up with the last positional parameters, so (2,) belongs to b. For anything beyond a quick look, use inspect.signature, which does that matching for you.
Reading each parameter
inspect.signature(func).parameters is an ordered mapping from names to Parameter objects. Each one has a name, a kind, and a default. If a parameter has no default, default is the marker Parameter.empty. Compare against it with is, because None and 0 are legitimate defaults.
import inspect
def connect(host, port=5432, *, timeout=10, ssl=True):
pass
sig = inspect.signature(connect)
for name, p in sig.parameters.items():
default = "required" if p.default is p.empty else p.default
print(name, p.kind.name, default)This prints:
host POSITIONAL_OR_KEYWORD required
port POSITIONAL_OR_KEYWORD 5432
timeout KEYWORD_ONLY 10
ssl KEYWORD_ONLY TrueThe kind values are POSITIONAL_ONLY, POSITIONAL_OR_KEYWORD, VAR_POSITIONAL (*args), KEYWORD_ONLY, and VAR_KEYWORD (**kwargs). They correspond to the ordering rules from earlier in the tutorial, so a tool can check how a function expects to be called without calling it.
Spotting the mutable default bug
Because defaults live on the function object, you can see the mutable default pitfall directly:
def add_item(item, items=[]):
items.append(item)
return items
add_item("a")
add_item("b")
print(add_item.__defaults__) # (['a', 'b'],)The default list has changed even though no caller passed it. When you suspect this bug, print __defaults__ after a few calls. A default that has grown is the symptom.
Checking a call without making it
Signature.bind applies the same matching rules as a real call. It raises TypeError for a bad call, with no side effects. Call apply_defaults() on the result to fill in the omitted parameters.
import inspect
def connect(host, port=5432, *, timeout=10, ssl=True):
pass
sig = inspect.signature(connect)
bound = sig.bind("db.local", timeout=5)
bound.apply_defaults()
print(dict(bound.arguments))
# {'host': 'db.local', 'port': 5432, 'timeout': 5, 'ssl': True}
try:
sig.bind("db.local", 5432, 5)
except TypeError as err:
print(err) # too many positional argumentsThe second call fails because timeout is keyword-only. Decorators, validators, and documentation tools use this technique to see what a call would receive.
Limits
- Some built-in functions, mostly those implemented in C, have no retrievable signature, and
inspect.signatureraisesValueErrorfor them. - The
__defaults__tuple is writable, so code can change a function's defaults after definition. Do this only in tests or deliberate patching, because it surprises readers. - A default is shown as the stored object. A default created by a function call, such as
x=make_default(), appears as its result, not the expression.
Exercise
A function is defined as def log(msg, level="INFO", *, flush=False). What do log.__defaults__ and log.__kwdefaults__ contain, and which inspect attribute tells you that flush can only be passed by keyword?
Show answer
log.__defaults__ is ('INFO',) and log.__kwdefaults__ is {'flush': False}. The kind of the flush parameter, inspect.signature(log).parameters["flush"].kind, is Parameter.KEYWORD_ONLY.