🔍 Code Extractor

function setup_environment

Maturity: 40

Loads environment variables from a .env file located in the same directory as the script, if the file exists.

File:
/tf/active/vicechatdev/e-ink-llm/main.py
Lines:
104 - 109
Complexity:
simple

Purpose

This function provides a convenient way to initialize environment variables from a .env file for application configuration. It checks for the existence of a .env file in the parent directory of the current script and loads all variables from it into the environment. This is commonly used for managing API keys, database credentials, and other configuration settings without hardcoding them in the source code. The function also provides user feedback by printing the path of the loaded .env file.

Source Code

def setup_environment():
    """Load environment variables from .env file if it exists"""
    env_file = Path(__file__).parent / '.env'
    if env_file.exists():
        load_dotenv(env_file)
        print(f"📁 Loaded environment from {env_file}")

Return Value

This function does not return any value (implicitly returns None). It performs a side effect by loading environment variables into the process environment using load_dotenv().

Dependencies

  • python-dotenv
  • pathlib

Required Imports

from pathlib import Path
from dotenv import load_dotenv

Usage Example

from pathlib import Path
from dotenv import load_dotenv

def setup_environment():
    """Load environment variables from .env file if it exists"""
    env_file = Path(__file__).parent / '.env'
    if env_file.exists():
        load_dotenv(env_file)
        print(f"📁 Loaded environment from {env_file}")

# Call at the start of your application
setup_environment()

# Now you can access environment variables
import os
api_key = os.getenv('API_KEY')
database_url = os.getenv('DATABASE_URL')

Best Practices

  • Call this function early in your application startup, before accessing any environment variables
  • Ensure the .env file is added to .gitignore to prevent committing sensitive credentials
  • The function gracefully handles missing .env files, so it's safe to call even if the file doesn't exist
  • Use Path(__file__).parent to ensure the .env file is located relative to the script location
  • Consider calling this function only once at application startup to avoid redundant file reads
  • The .env file should follow the KEY=VALUE format with one variable per line
  • Environment variables loaded this way can be accessed using os.getenv() or os.environ

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function load_env_file 73.7% 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 load_config_v1 68.2% 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
  • function check_configuration_v1 61.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 save_config_to_file 58.5% 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 test_setup 56.7% similar

    Validates the presence of required API keys (OpenAI and SERPER) and sets them as environment variables with fallback default values.

    From: /tf/active/vicechatdev/find_email/test_enrichment.py
← Back to Browse