Skip to content

Instantly share code, notes, and snippets.

@nepsilon
Last active July 8, 2016 06:20
Show Gist options
  • Save nepsilon/0ef3dfb09066d61a610f to your computer and use it in GitHub Desktop.
Save nepsilon/0ef3dfb09066d61a610f to your computer and use it in GitHub Desktop.
Better Flow Control with Python — First published in fullweb.io issue #32

Better Flow Control with Python

I recently interviewed 4 developers for a Python programming position They all knew how to use requests, call APIs and worked either with Django or Flask, but I saw all of them ignoring most of Python’s specific control flow.

Here are two of them, try/except/else/finally and for/else:

try: 
    # What you want to do, which might
    # very well raise an exception
except IndexError as ex: 
    # What do to when IndexError is raised
except MyModule.itsException as ex: 
    # What do to when MyModule raised an exception
except Exception as ex: 
    # What do to when any other Exception is raised
else:
    # Something specific to Python
    # This is executed when try did NOT raised any exception
finally: 
    # Exception or not, always excecute this block,
    # even if a return statement is above
for item in mylist:
    # Processing each item here
else:
    # This is executed when the loop terminates through
    # exhaustion of the list (with for) or when the
    # condition becomes false (with while), but not when
    # the loop is terminated by a break statement.
@nepsilon
Copy link
Author

A Fullweb reader contacted me to highlight this:

Item 12 of Brett Slatkin’s Effective Python:

"Avoid using else blocks after loops because their behaviour isn’t intuitive and can be confusing."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment