LEGB scope and UnboundLocalError
Predict whether this prints 10 or raises an error, and explain why Python decides at compile time.
Code Snippet
count = 10
def bump():
try:
print(count)
count += 1
except Exception as e:
print(type(e).__name__)
bump()Expected Output & Explanation
UnboundLocalError Because count += 1 assigns to count inside bump(), Python compiles count as a local variable for the entire function body. Reading count on the line before it is assigned raises UnboundLocalError instead of falling back to global.
Follow-up Interview Question · When is nonlocal needed instead of global?
Module Context & References
Python · Predict the output & bug traps Widely asked Python gotchas: defaults, closures, scoping, copies and async
Personal Notes · Markdown