Created
March 3, 2014 20:35
-
-
Save wolever/9334108 to your computer and use it in GitHub Desktop.
Apparently Python doesn't execute the `else` block of a `try/except/else` block if there is a return in the `try`.
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
""" | |
Python's ``else:`` block is *only* executed when the ``try:`` block does not reutrn: | |
$ python else_block_example.py | |
Running function, returning in 'try:' block: False | |
in 'else' block | |
in 'finally' block | |
Running function, returning in 'try:' block: True | |
in 'finally' block | |
""" | |
def stuff(return_in_try): | |
print "Running function, returning in 'try:' block:", return_in_try | |
try: | |
if return_in_try: | |
return | |
except: | |
print "in 'except' block" | |
else: | |
print "in 'else' block" | |
finally: | |
print "in 'finally' block" | |
stuff(return_in_try=False) | |
stuff(return_in_try=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment