🔍 Code Extractor

function load_config_v1

Maturity: 46

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

File:
/tf/active/vicechatdev/SPFCsync/grant_sharepoint_access.py
Lines:
10 - 22
Complexity:
simple

Purpose

This function provides a simple configuration loader that reads environment variables from a .env file in the current working directory. It parses each line for key=value pairs, skips comment lines (starting with #), and returns a dictionary containing all configuration values. Useful for managing application settings, API keys, and other configuration parameters without hardcoding them in source code.

Source Code

def load_config():
    """Load configuration from .env file."""
    config = {}
    try:
        with open('.env', 'r') as f:
            for line in f:
                if '=' in line and not line.strip().startswith('#'):
                    key, value = line.strip().split('=', 1)
                    config[key] = value
        return config
    except Exception as e:
        print(f"Error loading config: {e}")
        return None

Return Value

Returns a dictionary (dict) where keys are configuration variable names (strings) and values are their corresponding values (strings) from the .env file. Returns None if an error occurs during file reading or parsing (e.g., file not found, permission denied).

Usage Example

# Create a .env file first:
# API_KEY=abc123
# DATABASE_URL=postgresql://localhost/mydb
# DEBUG=true

config = load_config()
if config:
    api_key = config.get('API_KEY')
    db_url = config.get('DATABASE_URL')
    debug_mode = config.get('DEBUG') == 'true'
    print(f"API Key: {api_key}")
    print(f"Database: {db_url}")
else:
    print("Failed to load configuration")

Best Practices

  • Always check if the returned value is None before accessing configuration keys
  • Use .get() method on the returned dictionary to safely access keys with default values
  • Ensure the .env file is in the current working directory or modify the function to accept a file path parameter
  • Consider using the python-dotenv library for production applications as it handles more edge cases
  • Do not commit .env files to version control; add .env to .gitignore
  • All values are returned as strings; convert to appropriate types (int, bool, etc.) as needed
  • The function does not handle quoted values or escape sequences; values are taken as-is after the first = sign
  • Multi-line values are not supported by this implementation

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function load_env_file 83.1% similar

    Reads and parses environment variables from a .env file in the current directory, returning them as a dictionary.

    From: /tf/active/vicechatdev/SPFCsync/validate_config.py
  • function save_config_to_file 63.8% similar

    Persists current application configuration values from the config module to a .env file, maintaining existing entries and formatting multi-value fields appropriately.

    From: /tf/active/vicechatdev/docchat/app.py
  • function load_config 58.5% 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
  • function check_configuration_v1 56.3% similar

    Validates the presence of a .env configuration file and checks that all required environment variables (TENANT_ID, CLIENT_ID, CLIENT_SECRET, FROM_EMAIL) are defined.

    From: /tf/active/vicechatdev/email-forwarder/run_service.py
  • function load_connection_config 55.6% 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
← Back to Browse