Explain Python’s with statement (context manager).
Ask by ICSM Computer
Updated 01 Sep 2025
Explanation
withstatement in Python is used to wrap the execution of a block of code within methods defined by a context manager.__enter__()→ executed when entering the context (before the block starts).__exit__()→ executed when exiting the context (after the block ends, even if an error occurs).Common Example (File Handling)
Same as (Handle by try-catch-finally statement):
Custom Example (Creating a Context Manager)
Output:
Key Points to Mention in an Interview
withensures deterministic cleanup of resources.try...finally.__enter__/__exit__or usecontextlib.contextmanager.