E is for environment variables - Python A to Z
Code in this blog post was written with versions: Python: 3.14
Python A-Z is a blog series about Python. Each day, I share insights, ideas and examples for different parts of Python development that match with the letter of the day. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month.
The code that a program runs is provided by the developer of the program. The inputs and interactions are initiated by the user of the program. The environment variables are data provided by the system that runs it. They are used to abstract configuration to the system level so that the same code can be ran in different environments and act differently (for example, development vs production environments).
Accessing environment variables
In Python, you can access environment variables through os.environ dictionary.
If you run the following in a REPL, you’ll see all the environment variables Python has access to.
>>> for variable, value in os.environ.items():
... print(f'{variable}: {value}')
...
The os.environ is created at the time
Python started and won’t update to reflect changes in environment variables
that happen while the program is running. You can use
os.reload_environ
to update the values.
Automatically read variables from .env
It’s common to store project-specific configuration values in a
.env file instead of managing the
operating system level variables and having to remember to do that on every
machine when they change.
To automatically read the values from
.env, you can use
python-dotenv.
# Example from dotenv documentation
# https://pypi.org/project/python-dotenv/
from dotenv import load_dotenv
load_dotenv()
Environment variables are often used to store secrets and accidentally leaking such secrets can be catastrophic. There’s a command line tool dotenvx that enables you to encrypt your secrets and then inject them to Python programs at runtime.
If something above resonated with you, let's start a discussion about it! Email me at juhis@hamatti.org and share your thoughts. This year, I want to have more deeper discussions with people from around the world and I'd love if you'd be part of that.