Python Glossary Русский

all Python 3OOPconstruct

with

context manager

The with statement runs a block under a context manager: __exit__ is called on any exit from the block — normal, via return, or by an exception.

Syntax

with expr as name:
    ...
with a as x, b as y:
    ...
with (
    open('a') as fa,
    open('b') as fb,
):
    ...

with guarantees cleanup (closing a file, releasing a lock) but does not catch the error: the exception propagates unless __exit__ returns True — that is how contextlib.suppress works, and how you can swallow every error by accident. Several managers are separated by commas and exit in reverse order; since 3.10 they can be wrapped in parentheses across lines. The name after as survives the block: the file f is still there as an object but already closed, so f.read() raises ValueError. And as receives what __enter__ returns, not the manager itself — the same thing for open(), but not for every manager.

Examples

with open('a.txt', 'w', encoding='utf-8') as f:
    f.write('данные')
print(f.closed)  # → True — имя f живо, но файл закрыт
# Python 3.9+
class Tag:
    def __init__(self, name, swallow=False):
        self.name, self.swallow = name, swallow
    def __enter__(self):
        print('вход', self.name)
        return self.name.upper()
    def __exit__(self, exc_type, exc, tb):
        print('выход', self.name, exc_type.__name__ if exc_type else None)
        return self.swallow  # True — исключение подавлено
with (
    Tag('a', swallow=True) as x,
    Tag('b') as y,
):
    print(x, y)  # → A B
    1 / 0
print('дошли сюда')  # → дошли сюда
from contextlib import suppress
with suppress(FileNotFoundError):
    open('нет-такого.txt')
print('ошибка подавлена')  # → ошибка подавлена

See also

Open in the full glossarydocs.python.orgReport an inaccuracy