Context Managers (with statement)

Loading

1. What is a Context Manager?

A context manager in Python is an object that manages resources (like files, database connections, network sockets) using the with statement. It ensures that resources are automatically cleaned up when they are no longer needed.

Simplifies resource management
Automatically handles setup and cleanup
Prevents resource leaks (e.g., forgetting to close files)


2. The with Statement (Basic Example)

The with statement ensures that a resource is opened, used, and properly closed, even if an error occurs.

Example: Using with for File Handling

with open("example.txt", "w") as file:
file.write("Hello, World!")
# File is automatically closed after the block

Without with (Manual Cleanup)

file = open("example.txt", "w")
try:
file.write("Hello, World!")
finally:
file.close() # Must manually close the file

The with statement is better because it guarantees file closure.


3. Creating a Custom Context Manager (Class-Based)

To create a custom context manager, define a class with:

  • __enter__(): Runs when entering the with block
  • __exit__(): Runs when exiting the with block

Example: Custom File Handler

class FileManager:
def __init__(self, filename, mode):
self.file = open(filename, mode)

def __enter__(self):
return self.file # Returns the file object

def __exit__(self, exc_type, exc_value, traceback):
self.file.close() # Closes the file automatically

# Using the custom context manager
with FileManager("example.txt", "w") as file:
file.write("Custom context manager!")

If an exception occurs inside with, __exit__() handles cleanup.


4. Using contextlib for Simpler Context Managers

The contextlib module provides @contextmanager for function-based context managers.

Example: Creating a Context Manager Using contextlib.contextmanager

from contextlib import contextmanager

@contextmanager
def open_file(filename, mode):
file = open(filename, mode)
try:
yield file # Provide file object
finally:
file.close() # Ensure cleanup

with open_file("example.txt", "w") as file:
file.write("Using @contextmanager!")

More concise than class-based context managers.


5. Real-World Use Cases of Context Managers

Use CaseExample
File Handlingwith open("file.txt", "r") as f:
Database Connectionwith sqlite3.connect("db.sqlite") as conn:
Thread Lockingwith threading.Lock():
Temporary Fileswith tempfile.TemporaryFile() as tmpfile:
Suppressing Exceptionswith contextlib.suppress(FileNotFoundError):

6. Using contextlib.suppress to Ignore Exceptions

from contextlib import suppress

with suppress(ZeroDivisionError):
print(1 / 0) # No error raised

Prevents unnecessary try-except blocks.

Leave a Reply

Your email address will not be published. Required fields are marked *