How to Update Environment Variables in Python: Tips for Refreshing .env Files

When working with Python applications, you may need to use environment variables to store sensitive information, API keys, or other configurations. A common way to manage environment variables in Python is to use a .env file, which contains key-value pairs that represent the environment variables.

However, sometimes when you update your .env file, your Python code may not get the refreshed version. In this article, we’ll explore some tips for refreshing .env files in Python.

Key Takeaways

  • When you update your .env file, your Python code may not get the refreshed version.
  • You can manually reload the .env file using the dotenv_values() function.
  • Alternatively, you can use python-dotenv, which provides a feature to auto-reload the environment variables from the .env file on change.

Tip #1: Manually Reload the .env File

If you’re using the load_dotenv() function from the dotenv library to load environment variables from a .env file, you may need to manually reload the file when you update it.

This is because the load_dotenv() function only loads the environment variables once when the module is first imported.

To manually reload the .env file, you can use the dotenv_values() function, which reads the current contents of the file and returns them as a dictionary of key-value pairs:


from dotenv import dotenv_values

env_vars = dotenv_values(".env")

for key, value in env_vars.items():
    os.environ[key] = value

Tip #2: Use python-dotenv

An alternative approach is to use a package like python-dotenv, which provides a feature to auto-reload the environment variables from the .env file on change.

To use python-dotenv, you first need to install it using pip:

pip install python-dotenv

Then, instead of using load_dotenv(), you can use load_dotenv(dotenv_path, verbose=True, override=True), where dotenv_path is the path to your .env file, and override=True means that any existing environment variables will be overwritten with the values from the .env file:


from dotenv import load_dotenv

load_dotenv(dotenv_path=".env", verbose=True, override=True)

Using this approach, any changes you make to your .env file will be automatically reloaded into your program.