🔍 Code Extractor

function load_config

Maturity: 44

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

  • Ensure the .env file exists before calling this function or handle the None return value appropriately
  • This is a basic implementation; consider using the python-dotenv library for production use cases with better error handling and features
  • The function reads from the current working directory; ensure your script is executed from the correct location or modify to use absolute paths
  • All values are returned as strings; convert to appropriate types (int, bool, etc.) after retrieval
  • Never commit .env files containing sensitive information to version control
  • The function splits on the first '=' only, allowing values to contain '=' characters
  • Empty lines and lines without '=' are silently skipped

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 test_configuration 47.4% similar

    A test function that validates configuration settings by importing and calling the Config.validate_config() method, printing the result and returning a boolean status.

    From: /tf/active/vicechatdev/SPFCsync/test_connections.py
  • function main_v19 45.5% similar

    A validation function that checks SharePoint configuration settings from environment variables and provides diagnostic feedback on their validity.

    From: /tf/active/vicechatdev/SPFCsync/validate_config.py
  • function load_analysis_data 42.2% similar

    Loads CSV dataset(s) into pandas DataFrames based on dataset configuration, supporting both single dataset and comparison (two-dataset) modes.

    From: /tf/active/vicechatdev/data_quality_dashboard.py
  • function parse_log_line 35.8% similar

    Parses a structured log line string and extracts timestamp, logger name, log level, and message components into a dictionary.

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