Like me, you probably love ipython notebook and can't get enough of it. However, there is one thing that I found lacking - the support for an integrated way to import a notebook as a module into another notebook.

I did come across the --script option (now deprecated), but it creates additional files and I was wondering if there was another way to directly import from the notebook. ( The existence of the --script option does make this effort a bit redundant, but I was curious and also learnt some very interesting things on the way. I have shared those too, so do read on... )

What better way to use python knowledge and ipython notebook's rapid development environment to explore options.

To this end, I came up with this custom notebook importer... (The scripts on this page are also available here...github link )...

One more cool thing related to using import. You can also use the well known if __name__ == '__main__': blocks in your notebook for code that you do not want to import into other notebooks, say, test code or long running simulations or whatever you wish.

Enabling import hooks at startup

Ok, this is great so far... now we can import directly from other notebooks. However, it seems that we will need to add the above script to the top of each notebook that wants to import other notebooks.

If that was the case, this is a disaster. Thankfully, ipython has another gem of a feature. It allows us to specify arbitrary python scripts which get executed by every kernel at startup time.

To make use of the startup script feature, create a file called ~/.ipython/profile_default/startup/10-notebook-import-hook.py with all the contents of the above import code.

Why have I started the name of the script with 10-? Ipython allows us to specify more than 1 startup file. We can specify as many as we want... the prefix 10 is just a way for specifying the order in which the startup scripts will be executed. If you ever want to add more startup scripts at a later time and they need to have some order of execution enforced on them... the numbering is the way to do it. A script with the name 3_wake_up.py will be executed before 5_drink_tea.py.

Restart your notebook kernel and you should now be able to directly import other notebooks using import and __import__.

Adding useful customization at startup

I like to have some other useful things available in every ipython notebook. Like the pprint function (abbreviated to pp), and my own version of timeit.

I added these to the startup process, where these are inserted into the globals, so that they are available in every ipython notebook.