Why do we need environment variables?
Imagine you have a Python application that needs:- An API key for OpenAI
- A database connection string
- A secret key for authentication
- A port number
- A debug mode flag
- Secrets become visible in your source code.
- They may accidentally be committed to GitHub.
- Every developer needs to edit the source code.
- Different environments (development, testing, production) require different values.
What are environment variables?
Environment variables are key-value pairs maintained by the operating system. They are available to every program running in that environment. Think of them as configuration values provided from outside your application.Creating environment variables manually
macOS / Linux
Viewing environment variables
List all variables:The problem with manual environment variables
Althoughexport works, it becomes difficult to manage.
Imagine setting ten variables every time you open a terminal.
- Easy to forget one variable
- Time-consuming
- Difficult for teammates
- Different values for different projects
.env file.
What is a .env file?
A .env file is simply a text file that stores environment variables.
Instead of typing multiple export commands, you write them once.
Example:
How does Python read a .env file?
Python cannot read .env files automatically.
We use the python-dotenv package.
Install
Loading the .env file
Accessing variables safely
Instead ofProject structure
.env file normally lives in the project root.
Complete example
.envCritical: Never commit .env
Sharing projects safely
Instead of sharing your real.env, create a template named .env.example.
Best practices
✅ Use UPPERCASE names=
Common environment variables
Complete workflow
Quick tips
- Call
load_dotenv()at the beginning of your application. - Use
os.environ.get()instead of hardcoding values. - Never commit
.envto GitHub. - Share
.env.exampleinstead. - Keep configuration outside your source code.
Summary
Environment variables provide configuration outside your application, making your code more secure, flexible, and portable. A.env file is a convenient way to store these variables during development, and the python-dotenv package loads them automatically into your application’s environment.
Using .env files is a standard practice in modern Python development, including FastAPI, Flask, Django, and many other frameworks.