Practical Import Techniques
Selective Module Importing
Partial Module Imports
## Importing specific functions or classes
from math import sqrt, pow
## Avoiding full module execution
def custom_calculation():
return sqrt(pow(5, 2))
Dynamic Import Strategies
graph TD
A[Dynamic Imports] --> B[Conditional Import]
A --> C[Lazy Loading]
A --> D[Import on Demand]
Conditional Imports
def load_database_module():
try:
import psycopg2
return psycopg2
except ImportError:
print("Database module not available")
return None
Technique |
Benefit |
Use Case |
Lazy Import |
Reduced Memory |
Large Libraries |
Conditional Import |
Flexible Dependencies |
Optional Features |
Import Caching |
Performance Optimization |
Repeated Imports |
Lazy Loading Implementation
class LazyLoader:
def __init__(self, module_name):
self._module = None
self._module_name = module_name
def __getattr__(self, attr):
if self._module is None:
self._module = __import__(self._module_name)
return getattr(self._module, attr)
## Usage
numpy = LazyLoader('numpy')
Advanced Import Techniques
Import Hooks
import sys
from importlib.abc import MetaPathFinder, Loader
class CustomImportHandler(MetaPathFinder, Loader):
def find_spec(self, fullname, path, target=None):
## Custom import logic
pass
Best Practices
- Use conditional imports for optional dependencies
- Implement lazy loading for resource-intensive modules
- Minimize global import side effects
At LabEx, we recommend thoughtful import strategies to optimize Python module performance and maintainability.