# Python's with Statement: Manage External Resources Safely

DevFeed: [Python's with Statement: Manage External Resources Safely](<https://devfeed.tech/articles/python-s-with-statement-manage-external-resources-safely-99152.md>)

Original publisher: [Read original article](<https://realpython.com/python-with-statement/>)

Author: Leodanis Pozo Ramos

Published: 2026-10-25T14:00:00Z

Content type: tutorial

Language: en

Sources: [Real Python](<https://devfeed.tech/sources/real-python.md>)

Topics: [Python](<https://devfeed.tech/topics/python.md>), [Learning](<https://devfeed.tech/topics/learning.md>), [Pytest](<https://devfeed.tech/topics/pytest.md>), [Boilerplate](<https://devfeed.tech/topics/boilerplate.md>)

Tags: [python](<https://devfeed.tech/tags/python.md>), [resource-management](<https://devfeed.tech/tags/resource-management.md>), [resources](<https://devfeed.tech/tags/resources.md>), [safely](<https://devfeed.tech/tags/safely.md>), [with](<https://devfeed.tech/tags/with.md>)

## AI overview

Python's `with` statement calls a context manager's `.__enter__()` on entry and `.__exit__()` on exit, so cleanup runs even when the block raises an exception. This makes common setup and teardown--such as opening and closing files or acquiring and releasing locks--more concise and less error-prone than repeating `try` ... `finally`. The article contrasts the approaches: `try` ... `finally` works with any object but is more verbose; `with` requires an object that implements the context manager protocol. It also covers multiple managers, standard-library and pytest examples, and custom class-based or `contextlib.contextmanager` implementations. For asynchronous code, `async with` uses awaitable `.__aenter__()` and `.__aexit__()` methods; the tutorial demonstrates this with `aiohttp`.

## Source excerpt

Understand Python's with statement and context managers to streamline the setup and teardown phases in resource management. Start writing safer code today!