function load_config
Loads configuration from multiple fallback locations, returning a Config instance with application settings.
/tf/active/vicechatdev/invoice_extraction/config.py
350 - 390
moderate
Purpose
This function provides a flexible configuration loading mechanism for an invoice extraction application. It searches for configuration files in a prioritized order: explicit path parameter, environment variable, current directory, and user home directory. If no configuration file is found, it returns a Config instance with default values. This pattern allows for easy deployment across different environments (development, staging, production) without code changes.
Source Code
def load_config(config_path: Optional[str] = None) -> Config:
"""
Load configuration from default locations or specified path.
Searches for configuration in:
1. Specified path (if provided)
2. INVOICE_EXTRACTION_CONFIG environment variable
3. ./config.yaml
4. ./config.json
5. ~/invoice_extraction/config.yaml
Args:
config_path: Path to configuration file
Returns:
Config instance
"""
# Use provided path
if config_path:
return Config(config_path)
# Check environment variable
env_config_path = os.environ.get("INVOICE_EXTRACTION_CONFIG")
if env_config_path and os.path.exists(env_config_path):
return Config(env_config_path)
# Check current directory
for name in ["config.yaml", "config.yml", "config.json"]:
if os.path.exists(name):
return Config(name)
# Check user directory
home_dir = os.path.expanduser("~")
for name in ["config.yaml", "config.yml", "config.json"]:
user_config = os.path.join(home_dir, "invoice_extraction", name)
if os.path.exists(user_config):
return Config(user_config)
# No configuration file found, use defaults
logger.info("No configuration file found, using defaults")
return Config()
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
config_path |
Optional[str] | None | positional_or_keyword |
Parameter Details
config_path: Optional string specifying the explicit path to a configuration file. If provided, this takes highest priority and bypasses all other search locations. Accepts absolute or relative file paths. Can be None (default) to trigger automatic search through fallback locations.
Return Value
Type: Config
Returns a Config instance containing application configuration settings. The Config object is initialized either from a found configuration file (YAML or JSON format) or with default values if no configuration file exists. The specific structure and attributes of the Config class depend on its implementation, but it encapsulates all settings needed for invoice extraction operations.
Dependencies
osjsonloggingyamlpathlibtyping
Required Imports
import os
import json
import logging
import yaml
from pathlib import Path
from typing import Optional
Usage Example
# Example 1: Load with explicit path
config = load_config('/path/to/my/config.yaml')
# Example 2: Load from environment variable
import os
os.environ['INVOICE_EXTRACTION_CONFIG'] = '/etc/invoice/config.yaml'
config = load_config()
# Example 3: Load from current directory (config.yaml)
# Assumes config.yaml exists in current working directory
config = load_config()
# Example 4: Load with defaults (no config file found)
config = load_config()
# Example 5: Use the loaded config
config = load_config('config.yaml')
# Access config attributes (depends on Config class implementation)
# e.g., api_key = config.api_key
Best Practices
- Always handle the case where no configuration file exists - this function returns a Config instance with defaults, so ensure your Config class has sensible default values
- Use the explicit config_path parameter in production environments for predictable behavior
- Set the INVOICE_EXTRACTION_CONFIG environment variable in containerized deployments for flexibility
- Ensure configuration files are in valid YAML or JSON format to avoid parsing errors in the Config class
- Consider file permissions when placing config files in user home directories
- The search order is important: explicit path > environment variable > current directory > user directory > defaults
- Log messages indicate when defaults are used, so monitor logs to ensure configuration is loaded as expected
- Keep sensitive information (API keys, passwords) in environment variables rather than config files when possible
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function load_config_v1 76.1% similar
-
class Config_v5 66.6% similar
-
function test_config_loading 60.7% similar
-
function load_connection_config 60.1% similar
-
function load_config_v1 56.5% similar