Always validate environment variables with proper fallback logic and avoid unnecessary usage in tests or when defaults suffice. Check for truthiness rather than explicit None comparisons to handle empty strings, and ensure configuration values match their declared types and intended usage.
Always validate environment variables with proper fallback logic and avoid unnecessary usage in tests or when defaults suffice. Check for truthiness rather than explicit None comparisons to handle empty strings, and ensure configuration values match their declared types and intended usage.
Key practices:
if cache_home and Path(cache_home).is_dir()
instead of if cache_home is None
env.get()
calls in tests when the environment variable is never setExample from XDG cache directory handling:
cache_home = os.getenv("XDG_CACHE_HOME")
if cache_home and Path(cache_home).is_dir():
parent_dir = Path(cache_home)
else:
parent_dir = Path.home() / ".cache"
This approach handles both None values and empty strings while providing a clear fallback path.
Enter the URL of a public GitHub repository