Thuta Learning
Python
AdvancedProgrammingbeginner

Context Managers

Context Managers များသည် resources များကို properly manage လုပ်ရန် with statement ကို အသုံးပြုသည်။ Files, database connections စသည့် resources များကို automatic cleanup လုပ်ပေးသည်။

🎯 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