Predictive Hacks

How to Store Variables in Jupyter Notebook

With the storemagic command %store we can store variables in IPython’s database. More particularly, the variables are stored under ~/.ipython/profile_default/db/autorestore/<variable_name>.

Let’s continue with some examples.

# create a dictionary of your credentials

my_creds = {'username':'George',
            'password': 'StrongPassword'}

my_creds
{'username': 'George', 'password': 'StrongPassword'}
# store the my_creds under IPython database

%store my_creds
Stored 'my_creds' (dict)

Now let’s open a new Jupyter notebook. If we try to run the my_creds variables, we get a NameError because we have not loaded it yet.

In order to load the variables, we need to run the following magic cell command.

%store -r

And as we can see, the file has been created under the expected path.

If we want to delete all the variables from storage, we type:

%store -z

If we want to delete specif variables from storage, we type:

# Remove the variable "my_creds" and its value from storage
%store -d my_creds

If we want to restore stored variables automatically whenever you launch a new Jupyter notebook, we will need to add the following line to the ipython_config.py file:

c.StoreMagics.autorestore = True

Another usage of the store magic cell:

  • %store – Show list of all variables and their current values
  • %store spam bar – Store the current value of the variables spam and bar to disk
  • %store -d spam – Remove the variable and its value from storage
  • %store -z – Remove all variables from storage
  • %store -r – Refresh all variables, aliases and directory history from store (overwrite current values)
  • %store -r spam bar – Refresh specified variables and aliases from store (delete current variables)
  • %store foo >a.txt – Store value of foo to new file a.txt
  • %store foo >>a.txt – Append value of foo to file a.txt

References

[1] IPython Documentation

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s