Context Manager

Domain: Programming Fundamentals

🎯 Motivation

Managing resources (files, connections) safely is error-prone. Context managers (the with statement) handle setup and cleanup automatically.

πŸ“‹ Concrete Example

with open('data.txt') as f: data = f.read() - the file is automatically closed when the block ends, even if an error occurred.

πŸ”— Analogy

A self-cleaning paint roller - when you’re done painting (exit the with block), it automatically cleans itself. You don’t have to remember to clean up.