Use python-dotenv library to set environtment variables on Jupyterlab

Shan Dou
1 min readJun 3, 2022

Environment variables that store deployment-specific configurations (see 12-factor manifesto for the full elaboration) is an integral part of the application. In some situations, we may want to run the application’s entry point in Jupyterlab for some quick tests. What if we must change a series of environment variables on the fly? Although Jupyterlab allows variable-by-variable settings via cell magic %env MY_VAR=MY_VALUE , when the number of environment variables grows, we risk having a bloated cell.

A cleaner way is to place all the environment variable assignments inside a .env file. The content of the file are:

env_var1=value1
env_var2=value2
...
env_varN=valueN

The easiest way to load the variables on the fly is to first install the python library python-dotenv. It allows us to use line magic like the following to easily set up all the environment variables mentioned in the .env file:

%dotenv relative/or/absolute/path/to/.env

--

--