Bitpath

Boss lesson · Unit 02

With and exceptions

Cleanup that always runs, from try/finally to your own with block

13 exercisesabout 3 min

What you practise

  • __enter__ and __exit__, contextlib.contextmanager, try/except/else/finally in order, re-raising and chaining with from

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?

Python
def read():
    try:
        return "try"
    finally:
        print("cleanup")

print(read())
Hint

The return value is ready, but the function has not finished leaving yet.

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.

Python
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.

One email when Bitpath is ready to try. Nothing else. Privacy