Python22 min read

Python Context Managers

Learn context managers: why 'with' matters, how __enter__/__exit__ work, and how to build safe resource management.

Michael Brown
September 6, 2025
5.6k130

Context managers are Python’s way to manage resources safely.

  A resource is anything that must be cleaned up:
  - files must be closed
  - database connections must be closed
  - locks must be released
  
  The `with` statement guarantees cleanup even if an error happens.
  
  ## The best example: files
  
  ```python
  with open("data.txt", "r") as file:
      content = file.read()
      print(content)
  # file is closed automatically here
  ```
  
  ## Why not open() without with?
  
  If you do this and forget `close()`, resources may leak:
  
  ```python
  file = open("data.txt", "r")
  content = file.read()
  file.close()
  ```
  
  `with` makes this safer and cleaner.
  
  ## Create your own context manager (class)
  
  ```python
  class DatabaseConnection:
      def __enter__(self):
          print("Opening connection...")
          return self
  
      def __exit__(self, exc_type, exc_val, exc_tb):
          print("Closing connection...")
  
      def query(self, sql):
          print(f"Running: {sql}")
  
  with DatabaseConnection() as db:
      db.query("SELECT * FROM users")
  ```
  
  Expected output:
  
  ```
  Opening connection...
  Running: SELECT * FROM users
  Closing connection...
  ```
  
  ## Using contextlib (cleaner for small cases)
  
  ```python
  from contextlib import contextmanager
  import time
  
  @contextmanager
  def timer():
      start = time.time()
      yield
      end = time.time()
      print(f"Time: {end - start:.4f}s")
  
  with timer():
      sum([i for i in range(1000000)])
  ```
  
  Expected output example:
  
  ```
  Time: 0.0xxx s
  ```
  
  ## Multiple context managers
  
  ```python
  with open("input.txt", "r") as infile, open("output.txt", "w") as outfile:
      outfile.write(infile.read().upper())
  ```
  
  ## Graph: context manager lifecycle
  
  ```mermaid
  flowchart TD
    A[Enter with] --> B[__enter__ runs]
    B --> C[Work inside block]
    C --> D[__exit__ runs]
    D --> E[Cleanup done]
  ```
  
  In the next lesson, you will learn the collections module, which gives you powerful data structures for real-world problems.
#Python#Intermediate#Context Managers