advanced

Context Managers

7 min readLast updated: 2026-07-12

Overview

Context managers clean up resources automatically (like file descriptors and network sockets) using the with statement.

Learning Objectives

  • Implement enter and exit protocols.
  • Create custom context managers using contextlib.
  • Ensure resource cleanup runs unconditionally.

Concept Explanation

Context managers manage resources within with blocks. They enter context using __enter__ and exit via __exit__. If an exception occurs, it is passed to __exit__, which can suppress it by returning True.

Code Examples

Example 1 — Basics

This example introduces the fundamental syntax and concepts.

python
class Dummy:
    def __enter__(self): return self
    def __exit__(self, exc_type, exc_val, exc_tb): pass

Example 2 — Everyday Usage

This example demonstrates a realistic scenario handling business parameters.

python
class ConsoleHeader:
    def __enter__(self):
        print('=== Start ===')
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('=== End ===')
        return False # Propagate errors if any

with ConsoleHeader():
    print('Running middle tasks...')

Example 3 — Advanced Example

This example shows clean, production-grade code structure following senior development standards.

python
from contextlib import contextmanager

@contextmanager
def file_session(filepath, mode):
    # Generator context manager
    f = open(filepath, mode, encoding='utf-8')
    try:
        yield f
    finally:
        # Unconditional resource release
        f.close()
        print('File closed safely.')

with file_session('temp.txt', 'w') as session:
    session.write('Temporary records data')""

Visual Flow

The following execution flow represents the step-by-step evaluation inside the interpreter:

text
Run __enter__ block → Yield resource → Execute statements inside with block → Run __exit__ cleanup

Common Mistakes

Review these common pitfalls when working with this topic:

  • Suppressing exceptions silently in exit by returning True without validation.
  • Forgetting to release resource locks when exceptions occur inside custom context blocks.
  • Not implementing all required exit parameters (exc_type, exc_val, exc_tb).
  • Using context managers for simple loops that do not manage resources.

Best Practices

Enforce these Pythonic best practices in your codebase:

❌ Don't
python
conn.open()
try:
    queries(conn)
finally:
    conn.close() # Verbose try-finally boilerplate
✅ Do
python
with Connection() as conn:
    queries(conn) # Clean automated context manager

Quick Revision

Use these key summaries for last-minute revision:

  • with triggers context managers.
  • enter sets up the resource.
  • exit cleans up the resource.
  • exit takes 3 exception parameters.
  • Return True to suppress exceptions.
  • contextlib.contextmanager converts generators.