TL/DR; You can undo changes made by load_dotenv manually; by storing the original os.environ to a variable, then overwriting os.environ with it later. Alternatively, you can delete envvars with del.
Let's say you have two .env files for development and production (note that FOOGULAR_VERBOSE is defined only in .env.dev):
.env.dev
ROOT_URL=localhost/dev
FOOGULAR_VERBOSE=True
.env.prod
ROOT_URL=example.org
You can store the base environment to a variable, then load .env.dev like such:
from dotenv import load_dotenv
import os
# Preserve the base environment before load_dotenv
base_environ = os.environ.copy()
# Then load an .env file
load_dotenv('./.env.dev')
print(os.environ)
At this stage, the envvars are:
ROOT_URL='localhost/dev'
FOOGULAR_VERBOSE='True'
To switch to the production environment, revert to the base_environ first, then load .env.prod, like this:
os.environ = base_environ # Reset envvars
load_dotenv('./.env.prod') # Then load another .env file
Now the envvars look like this:
ROOT_URL=example.org
Another method is to delete os.environ['MY_VARIABLE'] manually, with the del statement:
del os.environ['FOOGULAR_VERBOSE']