Environment variables
Understanding environment config
Let's explore environment variables, a fundamental concept for managing application settings and keeping sensitive information secure.
What are environment variables?
Environment variables are unique key-value pairs stored in your operating system. Think of them as named storage places for bits of information your programs might need. They're available to processes running within that environment.
They aren't part of your program's code itself. Instead, your program can ask the operating system to provide these values.
The problem they solve
Imagine your Python app needs to connect to a database. The database address and password will change if you move your app from your laptop to a live server. Hardcoding these details directly into your code is a bad idea for a few reasons.
- Secret information (like passwords) would be visible to anyone with access to your code.
- You'd have to change your code every time you switch environments (development, testing, production).
- This makes your code less flexible and harder to maintain.
Environment variables offer a clean solution by separating configuration from code.
How environment variables work
When you run a command or an application, it inherits a set of environment variables from its parent process or the shell it was launched from. These variables form the "environment" for that running program.
Setting environment variables
The way you set environment variables depends on your operating system and how long you want them to last.
For the current shell session (Windows Command Prompt):
set MY_APP_SETTING=helloWorldFor the current shell session (Linux/macOS Bash/Zsh):
export MY_APP_SETTING="helloWorld"
# Or, for temporary use with a single command:
MY_APP_SETTING="helloWorld" python my_script.pyYou can also set them permanently via system settings, but that's usually only for global system paths and less common for application-specific settings.
Reading in Python
Python makes it very easy to access environment variables using the built-in os module.
import os
# Get the value of an environment variable
db_password = os.environ.get("DB_PASSWORD")
# Or, if you know it MUST exist, use direct access (can raise KeyError)
debug_mode = os.environ["DEBUG_MODE"]
print(f"Database Password: {db_password}")
print(f"Debug Mode: {debug_mode}")You can also provide a default value to get() if the variable isn't found.
import os
log_level = os.environ.get("LOG_LEVEL", "INFO")
print(f"Current log level: {log_level}")Common uses
- Database Credentials: Usernames, passwords, hostnames.
- API Keys: Secrets for third-party services like payment gateways or social media APIs.
- Configuration Flags: Enabling/disabling debug modes, setting logging levels.
- Paths: Defining where certain files or resources are located.
- Environment Type: Indicating if the application is running in 'development', 'testing', or 'production'.
Using environment variables helps keep your codebase clean and avoids committing sensitive data to version control like Git.
Important notes
For local development, tools like python-dotenv can help you load variables from a .env file into your environment, mimicking a production setup without actually changing your system-wide environment variables.
What's next?
Now that you understand environment variables, try setting a simple one and reading it in a Python script. Explore how different shell commands (printenv, env on Linux/macOS or set on Windows) show you current environment variables.