Python Context Managers and the `with` Statement

Python Logo

A context manager is an object that defines a temporary context for a block of code. It's most commonly used with the `with` statement and is fantastic for managing resources like files, network connections, or database sessions, ensuring they are properly set up and torn down.

The `with` Statement

The most common example is file handling. The `with` statement ensures the file is automatically closed even if errors occur.

# This is the recommended way to handle files
with open('example.txt', 'w') as f:
    f.write('Hello, world!')
# The file f is automatically closed here

Creating a Custom Context Manager

You can create your own context manager by defining a class with `__enter__` and `__exit__` methods.

  • `__enter__`: Executed at the start of the `with` block. Its return value is bound to the variable after `as`.
  • `__exit__`: Executed at the end of the `with` block. It receives exception details if an error occurred.
import time

class Timer:
    def __enter__(self):
        self.start_time = time.time()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        end_time = time.time()
        execution_time = end_time - self.start_time
        print(f"The block took {execution_time:.4f} seconds to execute.")

with Timer():
    # Some long-running process
    time.sleep(1)

Comments