Import Best Practices
Import Organization
1. Standard Import Order
## Recommended import order
## 1. Standard library imports
import os
import sys
## 2. Third-party library imports
import numpy as np
import pandas as pd
## 3. Local application imports
import local_module
2. Import Style Guidelines
graph TD
A[Import Styles] --> B[Absolute Imports]
A --> C[Explicit Imports]
A --> D[Avoid Star Imports]
Import Techniques
Absolute vs Relative Imports
Import Type |
Example |
Recommendation |
Absolute Import |
import project.module |
Preferred |
Relative Import |
from ..module import function |
Use sparingly |
Explicit Import Patterns
## Good: Explicit imports
from math import sin, cos, tan
## Avoid: Star imports
from math import *
Advanced Import Strategies
Conditional Imports
## Robust import handling
try:
import specialized_module
except ImportError:
specialized_module = None
## Type hinting support
from typing import Optional
def process_data(module: Optional[object] = None):
if module is not None:
## Use module
pass
Lazy Loading
## Lazy module loading
def get_heavy_module():
import heavy_computation_module
return heavy_computation_module
## Only loaded when called
module = get_heavy_module()
Import Optimization
- Minimize import overhead
- Use
importlib
for dynamic imports
- Avoid circular dependencies
Namespace Management
## Clean namespace management
import math as m ## Alias for clarity
result = m.sqrt(16)
LabEx Development Recommendations
Project Structure Best Practices
graph TD
A[Project Root] --> B[src/]
A --> C[tests/]
A --> D[requirements.txt]
A --> E[setup.py]
Dependency Management
- Use virtual environments
- Create
requirements.txt
- Specify exact versions
Error Handling
Import Error Mitigation
## Robust import error handling
def safe_import(module_name):
try:
return __import__(module_name)
except ImportError:
print(f"Could not import {module_name}")
return None
Tool |
Purpose |
isort |
Import sorting |
flake8 |
Style checking |
pylint |
Code analysis |
Key Takeaways
- Be explicit in imports
- Organize imports systematically
- Handle import errors gracefully
- Use virtual environments
- Keep dependencies minimal
Conclusion
Mastering import practices is crucial for:
- Code readability
- Performance optimization
- Maintainability