contextlib

Stdlib — MiscPython 2.5+Advanced

Context manager utilities: @contextmanager, suppress, ExitStack

Quick Info

Documentation
Official Docs
Python Version
2.5+
Dependencies
None — Python Standard Library
Install
Included with Python

Learn by Difficulty

Quick Example

python
from contextlib import contextmanager, suppress

@contextmanager
def managed_resource(name):
    print(f"Opening {name}")
    try:
        yield name
    finally:
        print(f"Closing {name}")

with managed_resource("database") as db:
    print(f"Using {db}")

# suppress
with suppress(FileNotFoundError):
    open("nonexistent.txt")
    print("This won't print")
print("Continued safely")

The contextlib module is part of Python's standard library. Context manager utilities: @contextmanager, suppress, ExitStack.

Try in Playground

Tags

stdlibcontext-managerwithresource-management

Related Items