snippetpythonModeratepending
Python context-dependent imports and conditional features
Viewed 0 times
optional importtry importlazy importtype_checkingconditional import
Problem
Need to handle optional dependencies gracefully, support conditional features, and manage platform-specific code.
Solution
Python conditional import patterns:
# 1. Optional dependency with fallback
try:
import ujson as json # Fast JSON if available
except ImportError:
import json # Fallback to stdlib
# 2. Feature flag based on availability
try:
import numpy as np
HAS_NUMPY = True
except ImportError:
HAS_NUMPY = False
def compute(data):
if HAS_NUMPY:
return np.mean(data)
return sum(data) / len(data)
# 3. Lazy import (defer heavy imports)
def process_image(path):
from PIL import Image # Only imported when function is called
img = Image.open(path)
return img.resize((100, 100))
# 4. Type checking imports (no runtime cost)
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from heavy_module import HeavyClass # Only for type hints
from sqlalchemy.orm import Session
def process(session: 'Session') -> None: # String annotation
...
# 5. Platform-specific code
import sys
if sys.platform == 'win32':
from .windows_impl import get_path
elif sys.platform == 'darwin':
from .macos_impl import get_path
else:
from .linux_impl import get_path
# 6. Version-specific code
import sys
if sys.version_info >= (3, 11):
from tomllib import load as load_toml
else:
from tomli import load as load_toml
# 7. Optional dependency with helpful error
def require_package(name):
try:
return __import__(name)
except ImportError:
raise ImportError(
f'{name} is required for this feature. '
f'Install it with: pip install {name}'
)
def use_pandas():
pd = require_package('pandas')
return pd.DataFrame()Why
Optional dependencies let packages stay lightweight while offering enhanced features when extra packages are installed. Lazy imports improve startup time for rarely-used features.
Context
Python package design and imports
Revisions (0)
No revisions yet.