Created
March 14, 2016 04:11
-
-
Save ambv/1143f0d0b86977059bed to your computer and use it in GitHub Desktop.
Behavior of exception name binding in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import sys | |
def example1(): | |
try: | |
pass # nothing is raised | |
except Exception as e1: | |
pass | |
print(e1) | |
# py2: raises UnboundLocalError | |
# py3: raises UnboundLocalError | |
def example2(): | |
e2 = 'old local value' | |
try: | |
pass # nothing is raised | |
except Exception as e2: | |
pass | |
print(e2) | |
# py2: prints 'old local value' | |
# py3: prints 'old local value' | |
e3 = 'global value' | |
def example3(): | |
try: | |
pass # nothing is raised | |
except Exception as e3: | |
pass | |
print(e3) | |
# py2: raises UnboundLocalError | |
# py3: raises UnboundLocalError | |
def example4(): | |
try: | |
raise ValueError('ve4') | |
except Exception as e4: | |
pass | |
print(e4) | |
# py2: prints 've4' | |
# py3: raises UnboundLocalError | |
def example5(): | |
e5 = 'old local value' | |
try: | |
raise ValueError('ve5') | |
except Exception as e5: | |
pass | |
print(e5) | |
# py2: prints 've5' | |
# py3: raises UnboundLocalError | |
e6 = 'global value' | |
def example6(): | |
try: | |
raise ValueError('ve6') | |
except Exception as e6: | |
pass | |
print(e6) | |
# py2: prints 've6' | |
# py3: raises UnboundLocalError | |
if __name__ == '__main__': | |
if len(sys.argv) != 2: | |
print('usage: exceptions.py [EXAMPLE_NUMBER]', file=sys.stderr) | |
sys.exit(1) | |
func_name = 'example{}'.format(sys.argv[1]) | |
func = globals().get( | |
func_name, | |
lambda: print('error: `{}` not found'.format(func_name)), | |
) | |
func() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment