🐍 Python Beginner

What is Python's with statement (context manager)?

Why Interviewers Ask This

This is a classic screening question for Python roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.

Answer

The with statement ensures resources are properly released after use, even if an exception occurs. It is equivalent to try/finally but cleaner. Example: with open("file.txt") as f: data = f.read() — the file is automatically closed when the block exits. Objects that support the context manager protocol implement __enter__() (setup, returns the object) and __exit__() (cleanup, receives exception info). Multiple context managers: with open("a") as fa, open("b") as fb. Create custom context managers using the @contextmanager decorator from contextlib: yield between setup and teardown code. Other common uses: database connections, threading locks (with lock), temporary directory (tempfile.TemporaryDirectory()), and mocking in tests (with unittest.mock.patch()).

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.