Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 789
Ankur Agarwal Avatar asked Oct 07 '16 17:10

Ankur Agarwal


2 Answers

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.

like image 119
kindall Avatar answered Sep 27 '22 23:09

kindall


in except ... as e, the e will be drop when Jump out of try except, Whether or not it was defined before.

When an exception has been assigned using as target, it is cleared at the end of the except clause.

refer to offical website link: https://docs.python.org/3/reference/compound_stmts.html#the-try-statement

like image 35
libin Avatar answered Sep 27 '22 22:09

libin