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.
Python code
15 linesdef 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
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
- Use traceback or logging with extra data to log context at exception
- 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
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.