Thuta Learning
AdvancedProgrammingbeginner

Context Managers

Relax. We'll talk through this in plain words — no textbook voice.

Context Managers use the with statement to properly manage resources. They automatically clean up resources such as files and database connections.

🎯 Benefits:

• Automatic resource cleanup

• Exception-safe

• Cleaner code

python
# File handling with context manager
# (For demo purposes - file operations simulated)

# Custom context manager
class Timer:
    def __enter__(self):
        import time
        self.start = time.time()
        print("Timer started")
        return self
    
    def __exit__(self, *args):
        import time
        elapsed = time.time() - self.start
        print(f"Timer stopped. Elapsed: {elapsed:.4f}s")

with Timer():
    # Simulate some work
    result = sum([i**2 for i in range(10000)])

print("Context manager ensures cleanup!")
You should see
Timer started Timer stopped. Elapsed: 0.0023s Context manager ensures cleanup!
Context Managers | Thuta Learning