Context managers and cleanup
Learn in depth →A context manager defines entry and exit behavior around a with block.
with resource() as value: ...Example
from contextlib import contextmanager
@contextmanager
def owned():
print("enter")
try:
yield "resource"
finally:
print("exit")
with owned() as value:
print(value)Result
enter resource exit
Watch for: Exit logic must define what happens on failures. Returning True from __exit__ suppresses the exception.
Practise this topic →