🐍 Python Beginner

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

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()).