Nbdev: Import from local library in new notebook

I’m trying out nbdev and am stuck with how to import parts of the code I’m developing in one notebook into another notebook.

If I define a class, (e.g. MyClass) in one notebook (e.g. 00_core.ipynb) including an #export core tag in the relevant cell, then when i run nbdev_build_lib I see the code for the class in lib_name/core.py as expected. This is great.

Now I start a new Notebook (e.g. 01_application.ipynb) and I’d like to import that class to use it. But when I try:

from lib_name import core

or

from lib_name.core import MyClass

I get a ModuleNotFoundError

I do have my notebooks in a directory called nbs/ in the project root. This was something I saw in the fastai repo. Do I have to use relative paths to get at my local module and if so, how?

Thanks for any help.

@wooduk, please check out my answer here. All you have to do is to replace my timeseries library name by your lib_name.

1 Like

Thank you. That does indeed work.

But now I’m wondering if it’s just cleaner to take the notebooks back out of nbs/ directory and have them in the root of the project… Not sure.

I had the same, did you export at the end? exporting and in some cases re starting kernel worked for me.

You might do that, and this what I did until I figured out the solution that I posted. However, if you have many notebooks you might end up cluttering your root folder. The second motivation to keep them in the nbs folder is because I wanted to follow the same setup (convention) as the other official fastai projects. By doing that all the project generated by the nbdev template have the same familiar look and that is a big plus for me. Even, when I navigate new projects generated by nbdev they look familiar.

If you aren’t using MS Windows as a development platform, you might just ignore the little hack that I mention. I do use it because I decided to test my library on both Windows and Linux.

Good luck with your project!