Boss lesson · Unit 02
With and exceptions
Cleanup that always runs, from try/finally to your own with block
What you practise
__enter__and__exit__,contextlib.contextmanager,try/except/else/finallyin order, re-raising and chaining withfrom
Try a question from this lesson
Pick one
The boss problem: release a resource whatever happens. Start here: a function returns from inside try. What prints?
def read():
try:
return "try"
finally:
print("cleanup")
print(read())Hint
The return value is ready, but the function has not finished leaving yet.
Correct answer
cleanup, then try
Why
finally runs on the way out of the try, whatever the reason: an exception, a return, a break. The return value is already decided, then cleanup runs, then the caller gets the value and prints it.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The four clauses
except runs only if the try block raised a matching exception. else runs only if it raised nothing. finally runs always, and last.
Put in try only the line that can fail, and the code that depends on its success in else.
def risky():
return int("7")
try:
risky()
except ValueError:
print("only if it raised ValueError")
else:
print("only if nothing was raised")
finally:
print("always, and last")Concept
with calls two methods
with is cleanup you cannot forget. It calls __enter__ before the block and __exit__ after it, whether the block finished, returned or raised.
__exit__ receives the exception (or three Nones). If it returns a true value, the exception is swallowed.
with make() as x:
use(x)
# does roughly this:
mgr = make()
x = mgr.__enter__()
try:
use(x)
finally:
mgr.__exit__(...)10 more exercises in the app
- 2× type the answer
- 4× multiple choice
- 2× fill the blanks
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.