How to Inspect Local Variables in an except Block in Python

Capture and print local variables at the moment an exception occurs using locals() inside an except block.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 13 views 0 copies

Python code

15 lines
Python 3.9+
def risky_operation(value):
    try:
        result = 10 / value
        return result
    except ZeroDivisionError as e:
        local_vars = dict(locals())
        print(f"Error: {e}")
        print("Local variables at exception:")
        for key, val in local_vars.items():
            print(f"  {key} = {val}")
        return None

if __name__ == "__main__":
    result = risky_operation(0)
    print(f"Result: {result}")

Output

stdout
Error: division by zero
Local variables at exception:
  result = 0
  e = division by zero
  value = 0
  local_vars = {'result': 0, 'e': ZeroDivisionError('division by zero'), 'value': 0}
Result: None

How it works

Inside the except block, locals() returns a snapshot of the current local scope, which includes the function arguments (value), any variables assigned before the exception (result), the exception object (e), and anything assigned in the handler itself (local_vars). By converting it to a dict, you freeze the snapshot so printing it doesn't change the contents while iterating. This pattern is a quick, dependency-free way to debug state at the failure point without a debugger. Note that the returned None is the explicit function return, which is what gets printed as Result: None.

Common mistakes

  • Modifying locals() or trying to assign to it—raises TypeError
  • Assuming locals() in a comprehension or lambda sees the block's scope
  • Forgetting that the exception object itself is in locals()
  • Using locals() after variables are reassigned in the except block

Variations

  1. Use traceback or logging with extra data to log context at exception
  2. Use sys.exc_info() to get exception type, value, and traceback without relying on the as clause

Real-world use cases

  • Debugging a failed API call by printing query parameters and response status in the except handler.
  • Logging snapshot of function arguments in a batch processing job when a record fails validation.
  • Capturing context for error reporting in a data pipeline before raising a wrapped exception.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.