xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Context managers and with

More Python9 min readLesson 4 of 7

4.1 Cleanup that cannot be skipped

Opening a file takes a resource that must be released even if the body raises. The with statement guarantees that. The object it receives implements two methods: __enter__ runs on entry, and __exit__ runs on the way out, including on exceptions.

The standard library uses this pattern for files, locks, database transactions and temporary directories. Use it whenever an operation pairs setup with cleanup.

python
with open("notes.txt", "w", encoding="utf-8") as handle:
    handle.write("First line\n")

with open("notes.txt", encoding="utf-8") as handle:
    print(handle.read().strip())

Output

First line

To build your own, either write a class with __enter__ and __exit__, or decorate a generator with contextlib.contextmanager. The generator form yields once; the code after the yield is the cleanup.

python
from contextlib import contextmanager

@contextmanager
def heading(text):
    print("==", text, "==")
    yield
    print("-- end --")

with heading("Result"):
    print("42")

Output

== Result ==
42
-- end --

Interview questions

2 questions from this note. Open one to see the answer; no account needed.

  • 01Does with close the file when an error happens?

    Yes. __exit__ runs on the way out even when the body raises, which is why with is preferred over manual close().

  • 02What does contextlib.contextmanager do?

    It turns a generator that yields once into a context manager, so you do not need a class for simple setup and cleanup.