Q25: How do Context Managers and the 'with' statement operate under the hood?

The with statement manages resource lifecycles via the Context Manager Protocol:

  1. Invokes __enter__() on setup, assigning return value to target variable (as var).
  2. Guarantees invocation of __exit__(exc_type, exc_val, exc_tb) on block exit, handling exceptions cleanly.
Custom Context Manager Class
class ManagedFile:
    def __init__(self, filename):
        self.filename = filename
        
    def __enter__(self):
        self.file = open(self.filename, 'w')
        return self.file
        
    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()
        return False # Propagate exceptions if any occurred
💡 __exit__ guarantees file stream closure even if exceptions are thrown inside the with block.
Key Takeaways
  • Executes deterministic cleanup via __enter__ and __exit__.
  • Can also implement using @contextlib.contextmanager decorator.
Knowledge Check

What does returning True from an __exit__ method accomplish when an exception occurs inside a with block?