Safe Resource Management
Understanding Resource Management
Resource management is critical in Python programming to ensure efficient system performance and prevent resource leaks. This involves managing system resources like files, network connections, and memory.
Context Managers: The Core of Safe Resource Management
graph TD
A[Resource Allocation] --> B{Context Manager}
B --> C[Automatic Resource Setup]
B --> D[Guaranteed Resource Release]
B --> E[Exception Handling]
Creating Custom Context Managers
Using contextlib
Decorator
from contextlib import contextmanager
@contextmanager
def managed_resource(filename):
try:
## Resource setup
file = open(filename, 'r')
yield file
finally:
## Guaranteed resource cleanup
file.close()
## Usage
with managed_resource('/tmp/example.txt') as file:
content = file.read()
Resource Management Techniques
1. File Handling
## Safe file reading
def safe_file_read(filename):
try:
with open(filename, 'r') as file:
return file.read()
except FileNotFoundError:
print(f"File {filename} not found")
except PermissionError:
print(f"Permission denied for {filename}")
2. Network Connection Management
import socket
from contextlib import contextmanager
@contextmanager
def managed_socket(host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host, port))
yield sock
finally:
sock.close()
Resource Management Patterns
Pattern |
Description |
Use Case |
Context Managers |
Automatic resource handling |
Files, Connections |
try-finally |
Manual resource cleanup |
Complex scenarios |
contextlib |
Flexible resource management |
Custom resources |
Garbage Collection
import gc
## Manually trigger garbage collection
gc.collect()
Resource Tracking
import sys
## Check object reference count
ref_count = sys.getrefcount(my_object)
Advanced Resource Management
Using __enter__
and __exit__
Methods
class ResourceManager:
def __init__(self, filename):
self.filename = filename
self.file = None
def __enter__(self):
self.file = open(self.filename, 'r')
return self.file
def __exit__(self, exc_type, exc_value, traceback):
if self.file:
self.file.close()
Best Practices for LabEx Developers
- Always use context managers
- Implement proper error handling
- Close resources explicitly
- Monitor resource usage
- Use
with
statement for predictable cleanup
Common Mistakes to Avoid
## Incorrect: Potential resource leak
def process_file(filename):
file = open(filename, 'r')
## No guarantee of file closure
## Correct: Safe resource management
def process_file(filename):
with open(filename, 'r') as file:
## Guaranteed file closure
return file.read()
By mastering these resource management techniques, you'll write more robust, efficient, and reliable Python applications.