Skip to content
IT Vizag
← Advanced Python Features

▶ Sign up free for the video, slides & prompts

The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.

Checking…

Context managers

Lesson 6 of 10 · 2 min read

How with works, and writing your own.

🎬 Video version coming soon — read it now

You've used with open(...) since the files course. That with statement works with any context manager: an object that sets something up, and guarantees cleanup afterwards, even if an error happens.

What with really does

🔒 Code example: sign up free (above) to unlock it.

is roughly:

🔒 Code example: sign up free (above) to unlock it.

The with version is shorter and impossible to get wrong.

Where context managers appear

  • Files: open
  • Locks in threaded code: with lock:
  • Database connections and transactions
  • Temporary folders: tempfile.TemporaryDirectory()
  • Suppressing an expected error: contextlib.suppress

Writing one with a class

Implement __enter__ and __exit__:

🔒 Code example: sign up free (above) to unlock it.

__exit__ receives details of any exception. Returning False lets it continue upwards, which is almost always what you want.

The easy way: contextlib.contextmanager

🔒 Code example: sign up free (above) to unlock it.

Everything before yield is setup; everything after, in finally, is cleanup. This combines a generator and a decorator, two lessons in one.

Handy built-ins

🔒 Code example: sign up free (above) to unlock it.

Several context managers can share one with.

Tip: Whenever you write "open/start/connect ... then remember to close/stop/disconnect", that's a context manager waiting to happen.

In one line

Context managers guarantee cleanup with the with statement; write them with __enter__/__exit__ or, more simply, @contextmanager and yield.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend