Control flow ↩
Control flow statements
- choice
- if / elif / else
- loops
- for
- while
- context
- with
- exceptions
- try / except / finally
The ‘try’ statement
# setup
try:
# action
finally:
# 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
try:
txt = f.read() # action
finally:
f.close() # cleanup
Managing the graphics state in DrawBot:
with savedState():
scale(1.5)
# same as:
save() # setup
scale(1.5) # action
restore() # cleanup
Managing undo history in RoboFont:
with glyph.undo():
glyph.removeOverlap()
# same as:
glyph.prepareUndo() # setup
glyph.removeOverlap() # action
glyph.performUndo() # cleanup