abc abc - 1 month ago 8
Python Question

Variable scope in case of an exception in python

while True:
try:
2/0
except Exception as e:
break

print e


Gives: integer division or modulo by zero

I thought scope of
e
is within the
while
block and it will not be accessible in the outside
print
statement. What did I miss ?

Answer

Simple: while does not create a scope in Python. Python has only the following scopes:

  • function scope (may include closure variables)
  • class scope (only while the class is being defined)
  • global (module) scope
  • comprehension/generator expression scope

So when you leave the while loop, e, being a local variable (if the loop is in a function) or a global variable (if not), is still available.

tl;dr: Python is not C.

Comments