Want to save & run Python script in Jupyter Notebook (Anaconda)

Another python newbie here.
Currently, I’m using Jupypter notebook in anaconda framework.

In order to proceed my projects using iPython Notebook,

I need to run some of my python scripts (tp.py file) on the notebook.

from tp import wordtoplural  

Since, it makes life a lot easier instead of defining all function in notebook itself.

How can I do it, currently importerrors occurs on my code.

ImportError: cannot import name wordtoplural

  1. iPython notebook and python script(.py) are in the same folder.
  2. Added empty __init.py__file on that directory too.

Best answer

Make sure your ipython notebook is in the same folder as your python script. Also, you may have to create an empty __init__.py file in the same folder as your python script to make the import work.

Since you will probably be modifying your python script and test it directly on your notebook, you may be interested in the autoreload plugin, which will automatically update the imported modules with the changes you have just made in your python scripts:

%load_ext autoreload
%autoreload 2

Note that you need to place your imports after having called the autoreload plugin.

Note also that in some cases you may need to add this in your IPython notebook at the very top of the first cell (after the % magics):

from __future__ import absolute_import

Limitations: autoreload works well in general to reload any part of a module’s code, but there are some exceptions, such as on new class methods: if you add or change the name of a method, you have to reload the kernel! Else it will continue to either load the old definition of this method or fail in the resolution (method not found), which can be particularly confusing when you are overloading magic methods (so in this case the default magic method will be called instead of your definition!). Then once the method name is defined and the kernel reloaded, you can freely modify the code of this method, the new code will be automagically reloaded.

Also it will fail if you use super() calls in the classes you change, you will also have to reload the kernel if this happens.