Best Practices
Module Organization and Design
1. Single Responsibility Principle
Each module should have a clear, focused purpose.
## Good: Separate modules for different responsibilities
## math_operations.py
def add(a, b):
return a + b
## string_utils.py
def validate_email(email):
return '@' in email and '.' in email
2. Avoid Circular Imports
graph LR
A[Module A] -->|Avoid| B[Module B]
B -->|Circular Import| A
style A fill:#ff9999
style B fill:#ff9999
Prevent circular dependencies by restructuring your code:
## Incorrect approach
## module_a.py
from module_b import some_function
## module_b.py
from module_a import another_function
## Correct approach
## Use dependency injection or restructure modules
Import Best Practices
Recommended Import Styles
| Style |
Example |
Recommendation |
| Absolute Import |
import package.module |
Preferred |
| Relative Import |
from ..module import function |
Use sparingly |
| Specific Import |
from module import specific_function |
Good for clarity |
Import Examples
## Recommended: Absolute imports
import os.path
from datetime import datetime
## Avoid: Wildcard imports
from module import * ## Not recommended
## Good: Specific imports
from collections import defaultdict
Module Documentation
def complex_calculation(x, y):
"""
Perform a complex mathematical calculation.
Args:
x (float): First input parameter
y (float): Second input parameter
Returns:
float: Result of the calculation
"""
## Detailed implementation
result = x * y + (x / y)
return result
Error Handling and Logging
Proper Error Management
import logging
## Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def safe_division(a, b):
try:
return a / b
except ZeroDivisionError:
logger.error("Division by zero attempted")
return None
Module Optimization
## Use list comprehensions
## Slow
def slow_square_list(numbers):
squared = []
for n in numbers:
squared.append(n ** 2)
return squared
## Fast
def fast_square_list(numbers):
return [n ** 2 for n in numbers]
Version and Dependency Management
Using Virtual Environments
## Create virtual environment
python3 -m venv myproject_env
## Activate virtual environment
source myproject_env/bin/activate
## Install dependencies
pip freeze > requirements.txt
pip install -r requirements.txt
Module Testing
Writing Module Tests
## test_module.py
import unittest
class TestMyModule(unittest.TestCase):
def test_function(self):
self.assertEqual(my_function(2, 3), 5)
if __name__ == '__main__':
unittest.main()
Advanced Module Techniques
Lazy Loading
## Lazy module loading
def get_heavy_module():
global heavy_module
if 'heavy_module' not in globals():
import heavy_computation_module as heavy_module
return heavy_module
Security Considerations
Avoid Executing Untrusted Modules
## Always validate and sanitize module imports
def safe_import(module_name):
try:
return __import__(module_name)
except ImportError:
logging.error(f"Cannot import {module_name}")
return None
Final Recommendations
- Keep modules small and focused
- Use type hints for better code clarity
- Implement comprehensive error handling
- Write unit tests for modules
- Use virtual environments
LabEx encourages developers to continuously improve their module design and follow these best practices for writing clean, efficient Python code.