tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Modern Python > Type Hints and Dataclasses > Python Context Managers and the with Statement

Python Context Managers and the with Statement

Author: Venkata Sudhakar

A Python context manager is an object that defines a runtime context for use with the with statement. The with statement guarantees that setup code runs before the block and teardown code runs after - even if an exception occurs inside the block. The most familiar example is with open("file.txt") as f: which guarantees the file is closed when the block exits, regardless of whether an exception was raised. Context managers eliminate the try/finally boilerplate that would otherwise be needed for resource cleanup.

Any class that implements __enter__ and __exit__ methods is a context manager. __enter__ runs on entry to the with block and returns the value bound by the as clause. __exit__ runs on exit and receives exception information if one was raised - returning True suppresses the exception, returning False (or None) re-raises it. The contextlib module provides two easier ways to write context managers: the @contextmanager decorator for generator-based context managers, and contextlib.suppress() for ignoring specific exceptions.

The below example shows practical context managers for database connections, migration timing, and temporary directory management used in data migration pipelines.


It gives the following output,

=== Migration Transaction Example ===
  Connecting to postgresql://prod-db:5432/appdb...
  SQL: INSERT INTO migration_log VALUES (1, CURRENT_TIMESTAMP)...
  SQL: UPDATE customers SET migrated=true WHERE id < 1000...
  COMMIT
  Transaction committed.

=== Migration Phase Timing ===

[START] Initial snapshot - customers table
[DONE] Initial snapshot - customers table in 0.10s

[START] CDC sync validation
[DONE] CDC sync validation in 0.05s

It gives the following output,

Created workspace: /tmp/cdc_export_abc123

[START] Export CDC events to staging
Staged 17 bytes
[DONE] Export CDC events to staging in 0.00s
Cleaned up workspace: /tmp/cdc_export_abc123

customers exists: True
inventory exists: False

When to use context managers:

Use context managers whenever you have setup and teardown logic that must be paired: opening/closing files, acquiring/releasing locks, starting/committing database transactions, beginning/ending timers, creating/deleting temporary resources, and enabling/disabling features for a block of code. The with statement makes the pairing explicit and exception-safe. Prefer @contextlib.contextmanager for simple cases - it avoids the class boilerplate and makes the setup/teardown flow visually clear because the yield clearly separates the two phases.


 
  


  
bl  br