ID EN
Contextlib

ExitStack

Python 3.11 🇮🇩 Bahasa Indonesia

Pengelola konteks yang dirancang untuk memudahkan penggabungan pengelola konteks dan fungsi pembersihan lainnya secara terprogram, terutama yang bersifat opsional atau didorong oleh data masukan.

Syntax

PYTHON
class contextlib.ExitStack

Contoh

Example 1
PYTHON
with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
     All opened files will automatically be closed at the end of
     the with statement, even if attempts to open files later
     in the list raise an exception
Example 2
PYTHON
with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
     Hold onto the close method, but don't call it yet.
    close_files = stack.pop_all().close
     If opening any file fails, all previously opened files will be
     closed automatically. If all files are opened successfully,
     they will remain open even after the with statement ends.
     close_files() can then be invoked explicitly to close them all.

See Also

__enter__() ExitStack with with __exit__() __enter__() with TypeError