contextlib — Easy Playground
Context manager utilities: @contextmanager, suppress, ExitStack
Python Playground
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")
Output
Click "Run" to execute your code
The contextlib module is part of Python's standard library. Context manager utilities: @contextmanager, suppress, ExitStack.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?