Python Context Managers and with Statement

Learn Python Context Managers and with Statement with practical examples, explanations, best practices, and real-world coding techniques.

Python context managers provide a structured way to manage resources and temporary changes before, during, and after a block of code. They are most commonly used with the with statement, which guarantees that cleanup or restoration logic is performed when execution leaves the block.

Files are one of the most familiar examples. When you open a file, you need to ensure that it is closed afterward, including when an exception occurs. A context manager lets you express that lifecycle directly in the code rather than manually remembering cleanup in every possible execution path.

Context managers are useful far beyond files. They can manage database transactions, locks, network connections, temporary resources, changes to application state, and other operations that have a clear setup-and-cleanup lifecycle.

What You Will Learn

  • What context managers are and why they are useful
  • How the with statement works
  • How __enter__() and __exit__() implement the context manager protocol
  • How exceptions are handled inside a context
  • How to create custom context managers with a class
  • How contextlib.contextmanager simplifies context manager creation
  • How multiple and nested context managers work
  • When context managers improve application reliability

What Is a Context Manager?

A context manager is an object that defines what should happen when entering and leaving a controlled block of code.

The controlled block is normally written using with:

with open("data.txt", "r", encoding="utf-8") as file:
    content = file.read()

print(content)

The file object acts as a context manager. Python opens the resource before the block executes and ensures that the resource is cleaned up when the block is exited.

Why Use Context Managers?

Resources often need cleanup even when the operation fails. Without a context manager, code may have to repeat cleanup logic in several places.

file = open(
    "data.txt",
    "r",
    encoding="utf-8"
)

try:
    content = file.read()
finally:
    file.close()

The same lifecycle can be expressed more clearly using a context manager:

with open(
    "data.txt",
    "r",
    encoding="utf-8"
) as file:
    content = file.read()

The context manager makes the ownership of cleanup explicit and reduces the chance of forgetting to release a resource.

The with Statement

The with statement is Python's syntax for working with context managers. It asks the object to perform its entry behavior, executes the body, and then asks the object to perform its exit behavior.

Conceptually, the process looks like this:

1. Enter the context

Setup logic runs before the with-block body.

↓

2. Execute the block

Your application code uses the managed resource or temporary state.

↓

3. Exit the context

Cleanup logic runs when the block finishes, including when an exception occurs.

The Context Manager Protocol

A class-based context manager typically implements two special methods: __enter__() and __exit__().

  • __enter__() runs when execution enters the with block.
  • The value returned by __enter__() becomes the value after as, when used.
  • __exit__() runs when the block is leaving.
  • __exit__() also receives exception information when an exception occurs inside the block.

Creating a Custom Context Manager

A simple custom context manager can be created with a class that implements __enter__() and __exit__().

class Connection:
    def __enter__(self):
        print("Connection opened")
        return self

    def __exit__(
        self,
        exc_type,
        exc_value,
        traceback
    ):
        print("Connection closed")


with Connection() as connection:
    print("Using connection")

The object returned by __enter__() becomes the value of connection.

Understanding __enter__()

The __enter__() method performs setup work. It can open a resource, acquire a lock, create a transaction, change state, or prepare anything needed by the block.

class Resource:
    def __enter__(self):
        print("Preparing resource")
        return "Managed value"


with Resource() as value:
    print(value)

The return value does not have to be the context manager object itself. It should be whatever value makes sense to the code inside the block.

Understanding __exit__()

The __exit__() method is responsible for cleanup and receives three arguments describing an exception if one occurred:

Parameter Meaning
exc_type The exception class, or None when no exception occurred.
exc_value The exception instance, or None.
traceback The traceback object, or None.

Context Managers and Exceptions

A major advantage of a context manager is that cleanup still happens when an exception is raised inside the block.

class Resource:
    def __enter__(self):
        print("Resource acquired")
        return self

    def __exit__(
        self,
        exc_type,
        exc_value,
        traceback
    ):
        print("Resource released")

        if exc_type is not None:
            print(f"Exception: {exc_value}")


try:
    with Resource():
        print("Working")
        raise ValueError("Something failed")
except ValueError:
    print("Handled outside context")

Even though the block raises an exception, Python still calls __exit__() before the exception continues outward.

Suppressing an Exception

The return value of __exit__() determines whether an exception raised inside the context should be suppressed. Returning a true value suppresses the exception.

class IgnoreValueError:
    def __enter__(self):
        return self

    def __exit__(
        self,
        exc_type,
        exc_value,
        traceback
    ):
        return exc_type is ValueError


with IgnoreValueError():
    raise ValueError("This is suppressed")

print("Program continues")

Exception suppression should be used carefully. Silently swallowing an error can make failures difficult to diagnose. Most context managers should perform cleanup and allow unexpected exceptions to propagate.

Context Manager with a Real Resource

Consider a simple connection object that must be opened before use and closed afterward.

class DatabaseConnection:
    def __init__(self):
        self.connected = False

    def __enter__(self):
        self.connected = True
        print("Database connected")
        return self

    def query(self, sql: str):
        if not self.connected:
            raise RuntimeError(
                "Connection is not open"
            )

        print(f"Executing: {sql}")

    def __exit__(
        self,
        exc_type,
        exc_value,
        traceback
    ):
        self.connected = False
        print("Database connection closed")


with DatabaseConnection() as db:
    db.query("SELECT * FROM users")

The example keeps resource lifecycle management inside the object while allowing the caller to focus on the operation being performed.

Using contextlib.contextmanager

Python's contextlib module provides the @contextmanager decorator, which allows many context managers to be written as generator functions instead of classes.

from contextlib import contextmanager


@contextmanager
def managed_resource():
    print("Resource acquired")

    try:
        yield "Resource value"
    finally:
        print("Resource released")


with managed_resource() as value:
    print(value)

The code before yield represents setup. The yielded value becomes the value after as. The code in finally performs cleanup.

Why finally Matters with contextmanager

When using @contextmanager, cleanup code should normally be placed in a finally block so it runs when the context exits normally and when the body raises an exception.

from contextlib import contextmanager


@contextmanager
def transaction():
    print("Transaction started")

    try:
        yield
    except Exception:
        print("Transaction rolled back")
        raise
    else:
        print("Transaction committed")
    finally:
        print("Transaction closed")


with transaction():
    print("Performing operations")

This pattern makes success, failure, and cleanup behavior explicit. The exact transaction implementation in a real database library will depend on that library's API.

Class-Based vs contextmanager

Class-Based Context Manager @contextmanager
Uses __enter__() and __exit__(). Uses a generator function with yield.
Useful when the context object needs substantial state or methods. Often concise for simple setup and cleanup flows.
Can expose additional operations on the resource. Focuses on entering and leaving a context.

Multiple Context Managers

Multiple resources can be managed in a single with statement.

with open(
    "input.txt",
    "r",
    encoding="utf-8"
) as source, open(
    "output.txt",
    "w",
    encoding="utf-8"
) as destination:

    destination.write(
        source.read()
    )

Each context manager is entered and exited as part of the same statement. This keeps related resource management compact and makes ownership clear.

Nested Context Managers

Context managers can also be nested when the lifecycle of one resource depends on another resource.

with open(
    "users.txt",
    "r",
    encoding="utf-8"
) as source:

    with open(
        "users-copy.txt",
        "w",
        encoding="utf-8"
    ) as destination:

        for line in source:
            destination.write(line)

The compact multiple-context form is often easier to read when the contexts are independent:

with open(
    "users.txt",
    "r",
    encoding="utf-8"
) as source, open(
    "users-copy.txt",
    "w",
    encoding="utf-8"
) as destination:

    for line in source:
        destination.write(line)

Using ExitStack

The contextlib.ExitStack helper is useful when the number of context managers is determined dynamically or when several cleanup operations need to be registered incrementally.

from contextlib import ExitStack


filenames = [
    "first.txt",
    "second.txt",
    "third.txt"
]

with ExitStack() as stack:
    files = [
        stack.enter_context(
            open(
                filename,
                "r",
                encoding="utf-8"
            )
        )
        for filename in filenames
    ]

    for file in files:
        print(file.readline())

When the ExitStack exits, it cleans up the contexts that were entered through it.

Context Managers for Temporary State

A context manager does not have to manage an external resource. It can also temporarily change application state and restore the previous state afterward.

from contextlib import contextmanager


@contextmanager
def temporary_mode(settings, mode: str):
    previous_mode = settings["mode"]
    settings["mode"] = mode

    try:
        yield
    finally:
        settings["mode"] = previous_mode


settings = {
    "mode": "normal"
}

print(settings["mode"])

with temporary_mode(settings, "maintenance"):
    print(settings["mode"])

print(settings["mode"])

The state is changed only for the duration of the context and restored afterward. This pattern is useful for temporary configuration, testing state, and controlled environment changes.

Locking with Context Managers

Synchronization primitives such as threading.Lock can be used as context managers. The lock is acquired when entering the block and released when leaving it.

import threading


lock = threading.Lock()
counter = 0


def increment():
    global counter

    with lock:
        counter += 1

This pattern is safer than manually calling acquire() and release() because the release is tied to leaving the context.

Context Managers and Transactions

Database transactions are another natural context-manager pattern. A transaction can begin when entering the context, commit after successful work, and roll back if an exception occurs.

from contextlib import contextmanager


@contextmanager
def transaction():
    print("BEGIN")

    try:
        yield
    except Exception:
        print("ROLLBACK")
        raise
    else:
        print("COMMIT")
    finally:
        print("CLOSE")


try:
    with transaction():
        print("Update account")
        print("Insert transaction")
except Exception:
    print("Operation failed")

The example shows the transaction lifecycle without depending on a specific database library. In a real application, the setup and cleanup calls would be replaced by the database connection or ORM's transaction API.

Reusable Context Managers

A useful context manager should represent a clear lifecycle. If the same setup and cleanup sequence appears in several parts of an application, encapsulating it in a context manager can reduce duplication and make the ownership of cleanup explicit.

Good examples include:

  • Opening and closing files
  • Acquiring and releasing locks
  • Starting and finishing transactions
  • Opening and closing connections
  • Creating and cleaning temporary resources
  • Temporarily changing application state

Async Context Managers

Python also supports context managers for asynchronous code. An asynchronous context manager implements __aenter__() and __aexit__() and is used with async with.

class AsyncConnection:
    async def __aenter__(self):
        print("Async connection opened")
        return self

    async def __aexit__(
        self,
        exc_type,
        exc_value,
        traceback
    ):
        print("Async connection closed")


async def load_data():
    async with AsyncConnection() as connection:
        print("Using async connection")

The asynchronous form is designed for resources whose setup or cleanup may itself require awaiting asynchronous operations.

Async Context Managers with contextlib

The contextlib module also provides @asynccontextmanager for generator-based asynchronous context managers.

from contextlib import asynccontextmanager


@asynccontextmanager
async def connection():
    print("Opening connection")

    try:
        yield "connection"
    finally:
        print("Closing connection")


async def load():
    async with connection() as value:
        print(value)

The asynchronous lifecycle follows the same general idea as a normal context manager while allowing asynchronous setup and cleanup.

Context Manager vs try/finally

try/finally Context Manager
Explicit lifecycle code at each call site. Reusable lifecycle abstraction.
Good for one-off cleanup logic. Good for repeated setup and cleanup patterns.
Can become repetitive across many call sites. Makes resource ownership and cleanup easier to see.

Common Mistakes

Forgetting Cleanup

A context manager that acquires a resource but does not reliably release it defeats the main purpose of the abstraction.

Suppressing Exceptions Unnecessarily

Returning a true value from __exit__() can hide errors. Suppression should be intentional and narrowly scoped.

Putting Too Much Work in the Context

The managed block should contain work that genuinely depends on the resource or temporary state.

Overengineering Simple Cleanup

Use existing context managers when possible. Creating a custom class for a trivial one-off operation can add unnecessary complexity.

Best Practices for Context Managers

  • Use with for resources that have a clear setup and cleanup lifecycle.
  • Use existing standard-library context managers when they already solve the problem.
  • Use @contextmanager for concise setup-and-cleanup flows.
  • Use a class-based context manager when the context needs persistent state or additional behavior.
  • Put cleanup in finally when using generator-based context managers.
  • Allow unexpected exceptions to propagate unless suppression is an explicit part of the context's contract.
  • Keep the managed block focused on work that requires the resource or temporary state.
  • Use ExitStack when the number of managed contexts is dynamic or cleanup must be assembled incrementally.
  • Use async with for asynchronous context managers rather than blocking asynchronous workflows with synchronous resource management.

Practical Example: Temporary Application Mode

The following example shows how a context manager can temporarily change application state and guarantee that the original state is restored.

from contextlib import contextmanager


@contextmanager
def temporary_mode(settings, mode: str):
    previous_mode = settings["mode"]
    settings["mode"] = mode

    try:
        yield
    finally:
        settings["mode"] = previous_mode


settings = {
    "mode": "normal"
}

print(f"Before: {settings['mode']}")

with temporary_mode(settings, "maintenance"):
    print(f"Inside: {settings['mode']}")

print(f"After: {settings['mode']}")

The important property is that the original value is restored even if the code inside the context raises an exception. This makes the state transition predictable and reduces cleanup duplication.

Practical Example: Resource Lifecycle

A custom context manager can also expose the managed resource itself while taking responsibility for its lifecycle.

class ApiClient:
    def __enter__(self):
        print("API client connected")
        return self

    def get(self, endpoint: str):
        print(f"GET {endpoint}")
        return {
            "status": "ok",
            "endpoint": endpoint
        }

    def __exit__(
        self,
        exc_type,
        exc_value,
        traceback
    ):
        print("API client disconnected")


with ApiClient() as client:
    response = client.get("/users")
    print(response)

In a real client, the setup and cleanup methods would manage the actual underlying connection or session. The calling code stays focused on requesting data.

When Should You Create a Custom Context Manager?

Create a custom context manager when a resource or state transition has a meaningful lifecycle that should be reused. A custom context manager is particularly valuable when forgetting cleanup could produce resource leaks, stale state, inconsistent transactions, or synchronization problems.

Before writing one, check whether the library or standard library already provides a suitable context manager. Reusing an established interface usually makes the resulting code easier for other Python developers to recognize.

Interview Questions to Prepare

  • What is a context manager in Python?
  • What does the with statement do?
  • What are __enter__() and __exit__()?
  • What arguments does __exit__() receive?
  • How can a context manager suppress an exception?
  • Why is a context manager useful for file handling?
  • How do you create a context manager using @contextmanager?
  • What is the difference between a class-based context manager and a generator-based one?
  • What is ExitStack and when is it useful?
  • What is the difference between a normal and asynchronous context manager?

Summary

Python context managers provide a reliable structure for setup and cleanup around a block of code. The with statement works with the context manager protocol, while __enter__() and __exit__() define the lifecycle for class-based context managers.

The contextlib.contextmanager decorator provides a concise generator-based alternative, and tools such as ExitStack help manage dynamic groups of contexts. Context managers are most valuable when an operation owns something that must be released or restored reliably, including files, locks, connections, transactions, and temporary application state.

Code Examples

Basic Class-Based Context Manager

python
class Connection:
    def __enter__(self):
        print("Connection opened")
        return self

    def __exit__(
        self,
        exc_type,
        exc_value,
        traceback
    ):
        print("Connection closed")


with Connection() as connection:
    print("Using connection")
    

Context Manager with Exception Handling

python
class Resource:
    def __enter__(self):
        print("Resource acquired")
        return self

    def __exit__(
        self,
        exc_type,
        exc_value,
        traceback
    ):
        print("Resource released")

        if exc_type is not None:
            print(f"Exception: {exc_value}")


try:
    with Resource():
        raise ValueError("Operation failed")
except ValueError:
    print("Handled outside context")
    

Using @contextmanager

python
from contextlib import contextmanager


@contextmanager
def managed_resource():
    print("Resource acquired")

    try:
        yield "Resource value"
    finally:
        print("Resource released")


with managed_resource() as value:
    print(value)
    

Temporary State Context Manager

python
from contextlib import contextmanager


@contextmanager
def temporary_mode(settings, mode: str):
    previous_mode = settings["mode"]
    settings["mode"] = mode

    try:
        yield
    finally:
        settings["mode"] = previous_mode


settings = {
    "mode": "normal"
}

with temporary_mode(settings, "maintenance"):
    print(settings["mode"])

print(settings["mode"])
    

Dynamic Contexts with ExitStack

python
from contextlib import ExitStack


filenames = [
    "first.txt",
    "second.txt"
]

with ExitStack() as stack:
    files = [
        stack.enter_context(
            open(
                filename,
                "r",
                encoding="utf-8"
            )
        )
        for filename in filenames
    ]

    for file in files:
        print(file.readline())
    

Pro Tip

Use context managers whenever a resource or temporary state has a clear acquire-use-release lifecycle. Prefer existing context managers, use @contextmanager for simple flows, and keep cleanup reliable with finally.

More Python lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.