Last active
August 29, 2015 13:56
-
-
Save jhanschoo/8811512 to your computer and use it in GitHub Desktop.
python try/catch/finally
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
def f(): # returns "bar" | |
try: | |
a = "foo" | |
return a | |
finally: | |
a = "bar" | |
return a | |
# order of evaluation: | |
# 3:a = "foo" | |
# 4:return a -eval-> return "foo" | |
# 6:a = "bar" | |
# 7:return a -eval-> return "bar" | |
# 7:return "bar" | |
def g(): # returns "foo" | |
try: | |
a = "foo" | |
return a | |
finally: | |
a = "bar" | |
# order of evaluation: | |
# 17:a = "foo" | |
# 18:return a -eval-> return "foo" | |
# 19:a = "bar" | |
# 18: return "foo" | |
def h(a): # returns ["bar"] | |
try: | |
a[0] = "foo" | |
return a | |
finally: | |
a[0] = "bar" | |
def k(a): # returns "foo" | |
try: | |
a[0] = "foo" | |
return a[0] | |
finally: | |
a[0] = "bar" | |
# The finally block is invoked after the expression in the return statement is evaluated | |
print(f()) # "bar" | |
print(g()) # "foo" | |
print h(["spam"]) # ["bar"] | |
print k(["spam"]) # "foo" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment