Sub topic 13
Inspecting Defaults and Signatures at Runtime
Earlier chapters covered how Python binds arguments to parameters and when defaults are evaluated. This chapter shows how to read that information from a live function object. I assume you know how to define functions with defaults, keyword-only parameters (*), positional-only parameters (/), and *args/**kwargs. I also assume you can read a short traceback.
Runtime inspection lets you check your understanding of the rules, debug mutable-default bugs, and write tools such as decorators, validators, and documentation generators. Python offers two levels: the raw attributes on the function object, and the inspect module, which presents the same facts in a structured form.
The raw attributes: `__defaults__` and `__kwdefaults__`
Every function object stores its default values when the def statement runs. They live in two attributes.
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__is a tuple holding the defaults for positional parameters. It has no names, so you match it to parameters by position.__kwdefaults__is a dict mapping keyword-only parameter names to their defaults.
How the tuple lines up
The tuple covers only the last N positional parameters, where N is the tuple's length. Positional-only parameters count as positional here.
def g(a, b=2, c=3, /, d=4, *, e=5, h):
pass
print(inspect.signature(g)) # (a, b=2, c=3, /, d=4, *, e=5, h)
print(g.__defaults__) # (2, 3, 4)
print(g.__kwdefaults__) # {'e': 5}The three values in (2, 3, 4) belong to b, c, and d. The keyword-only parameter h has no default, so it does not appear in __kwdefaults__. A required keyword-only parameter after a defaulted one is legal, because keyword-only parameters are matched by name, not position.
Edge cases
- A function with no positional defaults has
__defaults__equal toNone, not an empty tuple. - A function with no keyword-only defaults has
__kwdefaults__equal toNone. *argsand**kwargsnever appear in either attribute. They cannot have defaults.- Bound methods forward attribute lookups to the underlying function, so
Client().get.__defaults__works the same asClient.get.__defaults__.
Seeing the mutable default bug directly
The stored default is the very object that gets mutated. You can watch it change:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item.__defaults__) # ([],)
add_item("a")
add_item("b")
print(add_item.__defaults__) # (['a', 'b'],)No call passed items, yet the stored default grew. This is the clearest proof that the default was created once, at definition time, and is shared by every call that omits the argument.
`inspect.signature`: the structured view
The raw attributes are low-level. inspect.signature(func) returns a Signature object that merges positional defaults, keyword-only defaults, parameter kinds, and annotations into one description.
Because the diagram type must be declared in a diagram fence, here is the relationship between the pieces.
A Signature has a parameters attribute, an ordered mapping from name to Parameter. Each Parameter has these attributes:
| Attribute | Meaning |
|---|---|
| `name` | The parameter's name |
| `kind` | One of five constants, described below |
| `default` | The default value, or `inspect.Parameter.empty` if there is none |
| `annotation` | The annotation, or `inspect.Parameter.empty` |
The five kinds match the parameter categories from earlier chapters:
| Kind | Declared as |
|---|---|
| `POSITIONAL_ONLY` | Before `/` |
| `POSITIONAL_OR_KEYWORD` | Ordinary parameters |
| `VAR_POSITIONAL` | `*args` |
| `KEYWORD_ONLY` | After `*` or `*args` |
| `VAR_KEYWORD` | `**kwargs` |
This loop prints each parameter's kind and default:
import inspect
def demo(a, /, b, c=3, *args, d, e=5, **kwargs):
pass
for name, p in inspect.signature(demo).parameters.items():
default = "no default" if p.default is inspect.Parameter.empty else repr(p.default)
print(name, p.kind.name, default)The output is:
a POSITIONAL_ONLY no default
b POSITIONAL_OR_KEYWORD no default
c POSITIONAL_OR_KEYWORD 3
args VAR_POSITIONAL no default
d KEYWORD_ONLY no default
e KEYWORD_ONLY 5
kwargs VAR_KEYWORD no defaultCompare against inspect.Parameter.empty with is, not ==. A parameter whose default is None has default equal to None, which is different from having no default at all.
Previewing a call with `bind`
A Signature can apply Python's binding rules to a set of arguments without calling the function. bind returns a BoundArguments object, or raises the same kind of TypeError a real call would.
import inspect
def connect(host, port=5432, *, timeout=10):
return (host, port, timeout)
sig = inspect.signature(connect)
bound = sig.bind("db.local", timeout=5)
print(bound.arguments) # {'host': 'db.local', 'timeout': 5}
bound.apply_defaults()
print(bound.arguments) # {'host': 'db.local', 'port': 5432, 'timeout': 5}
try:
sig.bind("db.local", 5432, 5)
except TypeError as exc:
print(exc) # too many positional arguments
try:
sig.bind()
except TypeError as exc:
print(exc) # missing a required argument: 'host'Before apply_defaults(), arguments contains only what the caller supplied. After it, every parameter with a default is filled in, in parameter order. This is a convenient way to log the effective arguments of a call. sig.bind_partial(...) works like bind but does not require all mandatory parameters, which suits validators that check arguments in stages.
A practical use: finding mutable defaults
Since Parameter.default exposes the stored object, you can write a small linter for the pitfall from earlier chapters:
import inspect
def mutable_defaults(func):
found = []
for name, p in inspect.signature(func).parameters.items():
if isinstance(p.default, (list, dict, set)):
found.append(name)
return found
def add_item(item, items=[], *, seen={}):
items.append(item)
seen[item] = True
return items
print(mutable_defaults(add_item)) # ['items', 'seen']This covers the common built-in mutable types. A custom class instance used as a default can be shared and mutated in the same way, and a type check cannot detect that in general.
Gotchas
Decorators hide the real signature
A wrapper that takes *args, **kwargs has the signature (*args, **kwargs), so tools that read the signature learn nothing. functools.wraps sets __wrapped__ on the wrapper, and inspect.signature follows that link by default.
import functools
import inspect
def logged(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@logged
def greet(name, greeting="Hello"):
return f"{greeting}, {name}"
print(inspect.signature(greet)) # (name, greeting='Hello')
print(inspect.signature(greet, follow_wrapped=False)) # (*args, **kwargs)
print(greet.__defaults__) # Noneinspect.signature reports the original parameters. greet.__defaults__ belongs to the wrapper function, which has no defaults, so it is None. When you decorate functions, rely on inspect.signature, not the raw attributes.
Methods and `self`
Accessing a method through the class gives a plain function that includes self. Accessing it through an instance gives a bound method, and inspect.signature drops the first parameter.
import inspect
class Client:
def get(self, path, retries=3):
return (path, retries)
print(inspect.signature(Client.get)) # (self, path, retries=3)
print(inspect.signature(Client().get)) # (path, retries=3)
print(Client().get.__defaults__) # (3,)Not every callable has a signature
Some built-in functions implemented in C do not expose enough metadata, and inspect.signature raises ValueError for them. Objects that are not callable raise TypeError. Code that inspects arbitrary callables should handle both exceptions.
The signature reflects definition time
Everything shown here describes the defaults stored when def ran. If a default is a mutable object, inspect.signature shows its current contents, not the value it had at definition. After the add_item calls above, the signature would display items=['a', 'b'].
Choosing between the two views
| Need | Use |
|---|---|
| Quick check of stored defaults while debugging | `__defaults__`, `__kwdefaults__` |
| Parameter names, kinds, and defaults together | `inspect.signature` |
| Handling decorated functions or bound methods | `inspect.signature` |
| Checking whether a call would be valid | `Signature.bind` |
Exercise
For def f(a, b=1, /, c=2, *, d=3, e):, what are f.__defaults__ and f.__kwdefaults__, and what is the kind of each parameter?
Show answer
f.__defaults__ is (1, 2), covering b and c, the last two positional parameters. f.__kwdefaults__ is {'d': 3}, because e is keyword-only with no default. The kinds are: a and b are POSITIONAL_ONLY, c is POSITIONAL_OR_KEYWORD, and d and e are KEYWORD_ONLY.
Exercise
Write a function effective_args(func, *args, **kwargs) that returns a dict of the arguments func would receive, including defaults, without calling func. What does it raise if the call is invalid?
Show answer
Use inspect.signature, bind, and apply_defaults:
import inspect
def effectiveargs(func, args, kwargs):
bound = inspect.signature(func).bind(args, **kwargs)
bound.applydefaults()
return dict(bound.arguments)
If the arguments do not fit the signature, bind raises TypeError, for example "missing a required argument" or "too many positional arguments".