Inspect Callable Signatures
Core idea
Use inspect.signature to recover a callable’s parameters, defaults and return annotation when available. Signature.bind checks whether arguments fit the signature without calling the function; apply_defaults fills omitted default values. Parameter.kind distinguishes positional-only, keyword-only and variadic parameters.
from inspect import signaturedef ship(code, /, *, urgent=False): return codes = signature(ship)print(s.parameters['code'].kind.name)print(s.parameters['urgent'].default)The slash marks positional-only arguments; urgent has a default.
Validate a proposed call
from inspect import signaturedef total(qty, price=4): return qty * pricebound = signature(total).bind(3)bound.apply_defaults()print(dict(bound.arguments))print(total(*bound.args, **bound.kwargs))The bound arguments can be forwarded after validation. Binding alone never calls total.
Common mistake
Binding checks argument shape, not annotated types or business constraints. Some callables do not expose a signature; handle TypeError or ValueError at inspection boundaries.
Practice
Bind an omitted required argument and catch TypeError; then bind a valid call and inspect its arguments.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Inspect signatures
Check your understanding of inspect signatures.
What is printed?
from inspect import signaturedef f(x=8): passprint(signature(f).parameters['x'].default)What is printed?
from inspect import signaturedef f(*, x): passprint(signature(f).parameters['x'].kind.name)What does bind validate?
What fills omitted defaults?