Spex3
    

Context Managers in Python 🎯🐍


    

    

A context manager is a Python construct that manages resource allocation and cleanup automatically. It ensures resources like files, database connections, and network sockets are properly released, even if an error occurs.

1️⃣ Why Use Context Managers?
βœ” Automatic resource management (e.g., closing files, releasing locks)
βœ” Prevents resource leaks
βœ” Makes code cleaner and more readable

2️⃣ Using with Statements (Built-in Context Managers)
βœ… Example: File Handling (without explicit close())


with open("example.txt", "r") as file:
content = file.read()
print(content) # File closes automatically when 'with' block ends
βœ” No need to call file.close() manually
βœ” Ensures the file is closed even if an exception occurs

3️⃣ Creating a Custom Context Manager
You can create a custom context manager using a class with __enter__() and __exit__() methods.

βœ… Example: A Simple Timer Context Manager


import time

class Timer:
def __enter__(self):
self.start_time = time.time() # Start time
return self # Allows using 'as' in 'with'

def __exit__(self, exc_type, exc_value, traceback):
elapsed_time = time.time() - self.start_time
print(f"Elapsed time: {elapsed_time:.2f} seconds")

with Timer():
time.sleep(2) # Simulating a task
βœ” Automatically measures execution time
βœ” Handles exceptions gracefully

4️⃣ Using contextlib to Create Context Managers
Python’s contextlib module provides an easy way to create context managers using a decorator instead of a class.

βœ… Example: Creating a Context Manager Using @contextmanager


from contextlib import contextmanager

@contextmanager
def open_file(filename, mode):
file = open(filename, mode)
try:
yield file # Code inside 'with' block executes here
finally:
file.close() # Ensures file is closed

with open_file("example.txt", "w") as f:
f.write("Hello, Python!")
βœ” Simpler than writing a class
βœ” Automatically handles cleanup

5️⃣ Summary

Concept Description

with Statement Ensures resources are cleaned up properly

Built-in Context Managers open(), threading.Lock(), sqlite3.connect()

Custom Context Manager (Class-based) Uses __enter__() and __exit__() methods

contextlib Decorator (@contextmanager) A simpler way to create context managers


    Date: 2025-03-24 00:00:00.000000