Extract Diagnostics with inspect and traceback
Core idea
inspect exposes information about live callables and frames, while traceback summarizes a failure path. Use inspect.signature to inspect call compatibility and traceback.extract_tb to extract frame summaries. Prefer bounded summaries to retaining live frame objects, which can keep local variables alive.
import inspectdef reserve(code, *, count=1): return code, countsig = inspect.signature(reserve)try: sig.bind('A', 2)except TypeError: print('invalid call shape')print(sig.bind('A', count=2).arguments['count'])Binding catches a positional use of a keyword-only parameter without running the function.
Expected output:
invalid call shape2Collect frame names without locals
import tracebackdef check(): raise ValueError('invalid')try: check()except ValueError as exc: report = traceback.TracebackException.from_exception(exc, capture_locals=False) print(report.stack[-1].name) print(report.stack[-1].locals is None)The summary omits local variable representations. Exception text and paths still need privacy review.
Expected output:
checkTrueCommon mistake
Avoid retaining inspect.currentframe() or capturing locals in production diagnostics without a specific need. Introspection is not a guarantee of safe access or validation.
Practice
Create a nested call raising an exception and retain only the relevant frame names and exception category. Compare with the full traceback locally.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Inspect and traceback
Check your understanding of inspect and traceback.
What is printed?
import inspectdef f(a,*,b=2): passprint(inspect.signature(f).parameters["b"].default)What is printed?
import tracebacktry: raise KeyError("x")except KeyError as e: print(len(traceback.extract_tb(e.__traceback__)))Why avoid retaining live frames?
Does signature.bind enforce annotations?