Skip to content

Instantly share code, notes, and snippets.

@wolever
Created March 3, 2014 20:35
Show Gist options
  • Save wolever/9334108 to your computer and use it in GitHub Desktop.
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`.
"""
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