How to set environment variables in Python?
Setting environment variables in Python is useful when you want to manage sensitive data like API keys or configuration settings outside your main codebase. But how exactly do you define or access these variables within a Python script? Let’s find out.
Setting environment variables in Python is a common practice when you want to keep your code clean and secure — especially when dealing with credentials, API keys, or configuration data that shouldn’t be hard-coded into your script.
How to set environment variables in Python
Python provides the os module to work with environment variables. You can both read and set environment variables using this module.
Setting an environment variable:
You can set an environment variable within a Python script like this:
import os
os.environ["MY_VARIABLE"] = "my_value"However, this variable will only persist for the duration of the script execution.
Reading an environment variable:
To retrieve the value of an environment variable:
value = os.getenv("MY_VARIABLE")
print(value) Tips & Best Practices:
- Use environment variables to manage secrets and sensitive information securely.
- For permanent settings, define them in your system's environment or use a .env file with packages like python-dotenv.
Example using python-dotenv:
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("API_KEY") Note:
- Environment variables set in the script do not affect the system’s environment variables permanently.
- Using environment variables in Python is a clean and secure way to configure your applications, especially when deploying to production environments.