1

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?

1 Answer 1

4

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']
Sign up to request clarification or add additional context in comments.

3 Comments

And it was that easy. I didn't realize that environment variables would respond to a del. I assumed since they are 'special' they would need something special. Thanks!
Wait so do environment variable files not need to be named .env? You had a double period name as an example. Is that 'allowed'. I (again) assumed that it had to be a specifically named file like git_ignore.
@DChaps The load_dotenv function accepts arbitrary dotenv_path as the first argument (see the source code), so it does not need to be named .env. If load_dotenv() is invoked without arguments, it automatically looks for a file named .env (see the doc's usage example); in this case, it is helpful to name the env file as .env.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.