Skip to content

Context Manager

In one line

A context manager is an object that manages setup and teardown (cleanup) around a block of code, used with the with statement.

In simple words

A context manager handles resource setup and cleanup around a block of code. You use it with the with statement: with resource as r: .... The context manager ensures cleanup runs even if an exception occurs.

The most common example is file handling: with open('file') as f: guarantees the file is closed, even if an error occurs inside the block. Without with, you'd need try/finally to ensure cleanup.

A context manager implements __enter__ (setup, returns the resource) and __exit__ (cleanup, handles exceptions). You can also create context managers with the @contextmanager decorator from the contextlib module, using a generator function.

Example

python
# Using a built-in context manager
with open("example.txt", "w") as f:
    f.write("Hello")
# File is automatically closed here

# Creating a context manager
class Timer:
    def __enter__(self):
        import time
        self.start = time.time()
        return self

    def __exit__(self, *args):
        import time
        self.elapsed = time.time() - self.start
        print(f"Elapsed: {self.elapsed:.4f}s")

with Timer():
    sum(range(1000000))
# Prints: Elapsed: 0.0xxx s

Context managers handle setup/cleanup with the with statement. __enter__ sets up, __exit__ cleans up.

Common confusions

  • Confused with: try/finally

    The difference: A context manager (with) and try/finally both ensure cleanup. Context managers are cleaner and more reusable. try/finally is more explicit but verbose. Prefer with for resource management when a context manager is available.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary