Chapter 10: Advanced Topics / Lesson 58

Context Managers

Introduction to Context Managers

Context managers are Python objects that manage resources using the with statement. They ensure proper setup and cleanup of resources, like files, automatically. Context managers make code cleaner and prevent resource leaks.

The with statement is the most common way to use context managers, especially for file operations.

Using with Statement

The with statement automatically handles resource management:

with_statement.py
# File handling with context manager with open("file.txt", "w") as file: file.write("Hello, World!") # File is automatically closed here # Reading with context manager with open("file.txt", "r") as file: content = file.read() print(content) # File automatically closed # Multiple context managers with open("input.txt", "r") as infile, open("output.txt", "w") as outfile: data = infile.read() outfile.write(data.upper())

Creating Custom Context Managers

You can create your own context managers using classes:

custom_context.py
class Timer: def __enter__(self): import time self.start = time.time() return self def __exit__(self, exc_type, exc_val, exc_tb): import time elapsed = time.time() - self.start print(f"Elapsed time: {elapsed:.2f} seconds") # Use custom context manager with Timer(): # Some code here sum(range(1000000))

Benefits of Context Managers

Context managers provide several advantages:

  • Automatic resource cleanup
  • Exception-safe resource handling
  • Cleaner, more readable code
  • Prevents resource leaks
  • Standard pattern for resource management

Best Practices

✅ Context Manager Tips

• Always use with for file operations

• Context managers ensure cleanup even if errors occur

• Use contextlib module for simpler context managers

• Context managers are essential for proper resource management

• Prefer context managers over manual cleanup

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...