🔍 Code Extractor

function load_config

Maturity: 59

Loads configuration from multiple fallback locations, returning a Config instance with application settings.

File:
/tf/active/vicechatdev/invoice_extraction/config.py
Lines:
350 - 390
Complexity:
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

  • os
  • json
  • logging
  • yaml
  • pathlib
  • typing

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function load_config_v1 76.1% similar

    Loads configuration settings from a file by instantiating and returning a Config object with the specified configuration file path.

    From: /tf/active/vicechatdev/contract_validity_analyzer/config/config.py
  • class Config_v5 66.6% similar

    A hierarchical configuration manager that loads and manages settings from multiple sources (defaults, files, environment variables) with support for nested structures and dynamic updates.

    From: /tf/active/vicechatdev/invoice_extraction/config.py
  • function test_config_loading 60.7% similar

    A test function that validates configuration loading by instantiating a Config object and verifying access to key configuration parameters across FileCloud, LLM, and output settings.

    From: /tf/active/vicechatdev/contract_validity_analyzer/test_implementation.py
  • function load_connection_config 60.1% similar

    Loads database connection configuration from a specified configuration file and returns a ConnectionConfig object.

    From: /tf/active/vicechatdev/full_smartstat/sql_query_generator.py
  • function load_config_v1 56.5% similar

    Parses a .env file and loads key-value pairs into a dictionary, ignoring comments and handling errors gracefully.

    From: /tf/active/vicechatdev/SPFCsync/grant_sharepoint_access.py
← Back to Browse