Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Files Module 6 - File Handling & Errors Python Python Basics Python Programming: From Zero to Real-World Applications

Context Managers - The with Statement in Python

Reviewed & accurate
AI Summary

What You Will Learn

Intermediate

  • What context managers are
  • __enter__ and __exit__ methods
  • Using contextlib.contextmanager
Terminalpython
# Built-in context manager: file handling
with open("file.txt", "w") as f:
    f.write("Hello")
# File is automatically closed, even if error occurs!

# Creating your own context manager
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: {elapsed:.2f}s")

with Timer():
    # Code to time
    total = sum(range(1000000))
print(f"Result: {total}")

Using contextlib

Terminalpython
from contextlib import contextmanager
import time

@contextmanager
def timer():
    start = time.time()
    yield   # Code inside the with block runs here
    elapsed = time.time() - start
    print(f"Elapsed: {elapsed:.2f}s")

with timer():
    total = sum(range(1000000))

Practical Exercise

Use with open() as f - note auto-close
Create a Timer class with __enter__/__exit__
Use it with: with Timer(): ...
Try @contextmanager from contextlib

Key Takeaways

  • Context managers: setup + teardown via with statement.
  • __enter__: setup (return resource). __exit__: cleanup (always runs).
  • with open(): auto-closes file. with lock(): auto-releases.
  • contextlib.contextmanager: simpler way to create them.
  • Use for: files, database connections, locks, timers.
Previously: Lesson 40 covered custom exceptions.
Today: You learned: Manage resources with the with statement.
Next: Lesson 42 covers logging.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments