Loading…
A short voice session: one question, one follow-up, then instant feedback — up to 5 minutes.
with calls an object's __enter__ on entry and __exit__ on exit, even when an exception occurs, guaranteeing cleanup; you can write one as a class or with contextlib.contextmanager.
with open(path) as f guarantees the file is closed when the block ends, whether normally or through an exception. Any object with enter and exit methods works: enter returns the value bound by as, and exit receives exception details and can suppress the exception by returning True. For simple cases, @contextlib.contextmanager lets you write a generator where code before yield is setup and code after yield, inside try/finally, is cleanup. Context managers are used for files, locks, database transactions, timers and temporary settings.