How to Use Environment Variables in Python Projects
When building real-world Python applications, managing sensitive data like API keys, database credentials, or secret tokens securely is crucial. Hardcoding these values in your code is risky—especially when working in teams or deploying to production.
That’s where environment variables come in. They help you manage configurations outside of your source code, making your projects safer, cleaner, and easier to maintain.
What Are Environment Variables?
Environment variables are key-value pairs stored outside your code, typically in your operating system or .env file. Python can read these variables at runtime, allowing you to separate secrets and configurations from your logic.
Why Use Environment Variables?
- Security: Avoids exposing credentials in your codebase
- Flexibility: Easily change settings for dev, test, or production environments
- Portability: Share code without sharing secrets
- Clean Code: Keeps your scripts simple and maintainable
Using Environment Variables in Python
Python’s built-in os module makes it easy to read environment variables.
Example:
python
Copy code
import os
api_key = os.getenv(“API_KEY”)
print(f”Using API Key: {api_key}”)
If the API_KEY variable is not set, os.getenv() will return None.
Setting Environment Variables
1. Temporarily (on the command line)
Linux/macOS:
bash
Copy code
export API_KEY=’your-secret-key’
python your_script.py
Windows (CMD):
cmd
Copy code
set API_KEY=your-secret-key
python your_script.py
2. Using a .env File with python-dotenv
Create a .env file:
ini
Copy code
API_KEY=your-secret-key
DEBUG=True
Install the python-dotenv package:
bash
Copy code
pip install python-dotenv
Load the .env file in your Python code:
python
Copy code
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv(“API_KEY”)
Best Practices
- Never commit .env files to Git. Add them to .gitignore
- Use different values for dev, staging, and production environments
- Use defaults in case environment variables are missing:
python
Copy code
debug_mode = os.getenv(“DEBUG”, “False”) == “True”
Practice Challenge
- Create a .env file with:
ini
Copy code
DB_USER=admin
DB_PASS=secure123
- Write Python code to read these values using dotenv.
This hands-on task will help you understand how to manage secrets the right way.
Build Smarter Projects, Safer
Using environment variables is one of the first steps toward writing secure and scalable Python applications. Whether you’re working on Flask, Django, or data pipelines—this habit will pay off in every project.
👉 Learn how to apply these skills in real-world projects at https://www.thefullstack.co.in/courses/
You also like this:
What is Backend Development? A Complete Guide for Beginners [2025]

Leave a Reply