# Context Managers

> Context managers in Python provide a clean way to manage resources that need setup and teardown, such as database connections, locks, or temporary state...

Canonical: https://www.internhack.in/learn/python/advanced-python/context-managers
Last updated: 2026-11-28

Difficulty: Advanced

Context managers in Python provide a clean way to manage resources that need setup and teardown, such as database connections, locks, or temporary state changes. The \`with\` statement ensures that cleanup code always runs, even if an exception occurs inside the block.

The context manager protocol requires two methods: \__enter_\_() and \__exit_\_(). When a \`with\` block begins, Python calls \__enter_\_() on the context manager, and the return value is bound to the variable after \`as\`. When the block ends (normally or due to an exception), Python calls \__exit_\_(), which receives exception information as arguments. If \__exit_\_ returns True, the exception is suppressed; otherwise it propagates.

For simpler cases, the contextlib module provides the @contextmanager decorator, which lets you write a context manager as a generator function with a single yield. Code before yield runs as \__enter_\_, the yielded value is bound to the \`as\` variable, and code after yield runs as \__exit_\_. This avoids the boilerplate of writing a full class.

Context managers are used throughout Python's standard library and popular frameworks. The open() function is the most common example, but they also appear in threading (locks), decimal (local precision), and database libraries (transactions). Understanding context managers is essential for writing robust, resource-safe Python code.

You can also nest context managers or use contextlib.ExitStack to manage a dynamic number of context managers. These advanced patterns are useful when the number of resources to manage is not known until runtime.

## Code examples

### Class-Based Context Manager

```
class ManagedResource:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print(f"Acquiring {self.name}")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f"Releasing {self.name}")
        return False

with ManagedResource("database") as res:
    print(f"Using {res.name}")
```

\__enter_\_ is called when entering the with block and returns self (bound to 'res'). \__exit_\_ is called when leaving the block, ensuring cleanup always happens.

### Context Manager with Exception Handling

```
class SafeBlock:
    def __enter__(self):
        print("Entering safe block")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is not None:
            print(f"Caught exception: {exc_val}")
        print("Exiting safe block")
        return True

with SafeBlock():
    print("Inside block")
    raise ValueError("something went wrong")

print("After block")
```

Returning True from \__exit_\_ suppresses the exception. Without return True, the ValueError would propagate after \__exit_\_ runs.

### Using contextlib.contextmanager

```
from contextlib import contextmanager

@contextmanager
def tag(name):
    print(f"<{name}>")
    yield name
    print(f"</{name}>")

with tag("div") as t:
    print(f"Content inside {t}")
```

The @contextmanager decorator turns a generator into a context manager. Code before yield is \__enter_\_, the yielded value is the 'as' variable, and code after yield is \__exit_\_.

### Nested Context Managers

```
class Indent:
    level = 0

    def __init__(self, label):
        self.label = label

    def __enter__(self):
        Indent.level += 1
        print("  " * Indent.level + f"Enter {self.label}")
        return self

    def __exit__(self, *args):
        print("  " * Indent.level + f"Exit {self.label}")
        Indent.level -= 1
        return False

with Indent("outer"):
    with Indent("inner"):
        print("  " * Indent.level + "Deep inside")
```

Each nested with block calls \__enter_\_ on entry and \__exit_\_ on exit. The class-level 'level' variable tracks nesting depth for proper indentation.

## Key points

- The \__exit_\_ method always receives three arguments (exc_type, exc_val, exc_tb) even if no exception occurred -- they will all be None in that case.
- Returning True from \__exit_\_ suppresses the exception. Returning False (or None) lets it propagate.
- The contextlib module also provides suppress(), redirect_stdout(), and ExitStack for advanced use cases.

## Interview tips

- Explain how \__enter_\_ and \__exit_\_ map to the with statement, and when you'd choose a class-based context manager vs @contextmanager.
- Know that \__exit_\_ receives exception info and that returning True suppresses the exception.

## Concepts covered

with statement, \__enter_\_, \__exit_\_, contextlib.contextmanager

Previous: [Iterators Protocol](https://www.internhack.in/learn/python/advanced-python/iterators-protocol) · Next: [Closures & Functional Programming](https://www.internhack.in/learn/python/advanced-python/closures-and-functional) · [All of Advanced Python](https://www.internhack.in/learn/python/advanced-python)

## More Advanced Python lessons

- [Decorators](https://www.internhack.in/learn/python/advanced-python/decorators)
- [Generators](https://www.internhack.in/learn/python/advanced-python/generators)

## Related

- [Learn](https://www.internhack.in/learn)
- [Python](https://www.internhack.in/learn/python)
- [Advanced Python](https://www.internhack.in/learn/python/advanced-python)
