Eric J Ma's Website

Set environment variables inside a Jupyter notebook

written by Eric J. Ma on 2021-05-14 | tags: til jupyter data science


Did you forget to set an environment variable before launching Jupyter? Today, I learned how you can rescue that situation easily.

Today, I learned that one can set an environment variable from within a Jupyter notebook session.

Let's say you needed an environment variable set for your Jupyter notebook, but you:

  1. Don't want it set globally or project-wide, or
  2. Forgot to set it before you launched Jupyter.

To do so, add the following line(s) to the very, very first cell of the notebook:

%env MY_ENV_VAR=value

Within the same code cell, you can clone that as many times as you want to set environment variables of any kind.

To verify that the environment variable has been set correctly, you can use the following code block to view the value of the environment variable that you set:

import os
os.environ["MY_ENV_VAR"]

Now, one thing has to be stated - according to 12 Factor App development principles, you might need to set environment variables for sensitive information. You should never, ever, ever set those environment variables at the top of your notebook because they will be exposed!


Cite this blog post:
@article{
    ericmjl-2021-set-notebook,
    author = {Eric J. Ma},
    title = {Set environment variables inside a Jupyter notebook},
    year = {2021},
    month = {05},
    day = {14},
    howpublished = {\url{https://ericmjl.github.io}},
    journal = {Eric J. Ma's Blog},
    url = {https://ericmjl.github.io/blog/2021/5/14/set-environment-variables-inside-a-jupyter-notebook},
}
  

I send out a newsletter with tips and tools for data scientists. Come check it out at Substack.

If you would like to sponsor the coffee that goes into making my posts, please consider GitHub Sponsors!

Finally, I do free 30-minute GenAI strategy calls for teams that are looking to leverage GenAI for maximum impact. Consider booking a call on Calendly if you're interested!