Control flow statements

  • choice
    • if / elif / else
  • loops
    • for
    • while
  • context
    • with
  • exceptions
    • try / except / finally

The ‘try’ statement

# setup
    # action
    # cleanup
  • finally is always executed, even if the code that does the work doesn’t finish

The ‘with’ statement

The with statement offers a convenient syntax to express the common pattern of setting up a context, perfoming an action, and then cleaning up when done.

A with statement works together with a context manager – an object that handles the entry into and exit from a context, encapsulating the setup and cleanup actions.

Here are a few examples of with in use, and the corresponding code without it:

Opening a file, processing its contents, and closing the file:

with open('example.txt', 'r') as f:
    txt = f.read()
# same as:
f = open('example.txt', 'r') # setup
    txt = f.read() # action
    f.close() # cleanup

Managing the graphics state in DrawBot:

with savedState():
# same as:
save() # setup
scale(1.5) # action
restore() # cleanup

Managing undo history in RoboFont:

with glyph.undo():
# same as:
glyph.prepareUndo() # setup
glyph.removeOverlap() # action
glyph.performUndo() # cleanup
Last edited on 02/06/2020