ID EN
Contextlib

closing

Python 3.11

Return a context manager that closes thing upon completion of the block. This is basically equivalent to:

Syntax

PYTHON
contextlib.closing(thing)

Examples

Example 1
PYTHON
from contextlib import contextmanager

@contextmanager
def closing(thing):
    try:
        yield thing
    finally:
        thing.close()
Example 2
PYTHON
from contextlib import closing
from urllib.request import urlopen

with closing(urlopen('https://www.python.org')) as page:
    for line in page:
        print(line)

See Also

with context manager with urlopen()