×

python · level 3 · unit 3 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A sets up, then always cleans up.

You already write with open(...) as f:. The object after with is a context manager. Python calls its __enter__ method as the block starts, and its __exit__ method as the block ends, however it ends.

That is the whole trick. Even if the block crashes, __exit__ still runs, so a like a file or a lock is always given back. Whatever __enter__ returns is caught by the name after as.

Write a class with those two methods and you have your own context manager.

class Job:
    def __init__(self, label):
        self.label = label
    def __enter__(self):
        print(f"{self.label}: start")
        return self
    def __exit__(self, kind, error, trace):
        print(f"{self.label}: tidied up")

with Job("backup") as job:
    print("working on", job.label)
print("after the block")

__exit__ receives three details about any error, or three Nones when nothing went wrong.