function setup_environment
Loads environment variables from a .env file located in the same directory as the script, if the file exists.
/tf/active/vicechatdev/e-ink-llm/main.py
104 - 109
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-dotenvpathlib
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function load_env_file 73.7% similar
-
function load_config_v1 68.2% similar
-
function check_configuration_v1 61.3% similar
-
function save_config_to_file 58.5% similar
-
function test_setup 56.7% similar