Issue
How do I unset an environmental variable in Jupyter Notebook? I set the variables using a .env
file that is loaded by:
from dotenv import load_dotenv
load_dotenv('./.env')
After changing the .env
file and rerunning the import/load does the variable stays the same (the old version). I tried setting the environment variable to None
using the magic command but it's literally now None instead of blank. I didnt see any unset command at https://ipython.readthedocs.io/en/stable/interactive/magics.html
Any way to accomplish this?
Solution
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 an 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']
Answered By - yumemio
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.