1

I'm trying to create a project with the following structure:

my_file.ipynb
my_package_directory > __init__.py test.py

Within test.py lets say I have a very simple class:

class Test:
    def __init__(self, name):
        self.name = name

from with in a code cell I try to insatiate the class and print out the defined variable:

from my_package_directory.test import Test
test = Test('bob')
print(test.name)

If I try to run the cell I get an error:

ImportError: cannot import name 'Test' from 'my_package_directory.test'

Is there a certain way to do this in a Jupyter notebook?

Thank you.

6
  • Can you double-check your namings with e.g import my_package_directory.test as t; print(dir(t)) ? Commented Oct 25, 2021 at 15:19
  • I think this outputs as expect ['Test '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'const', 'os'] Commented Oct 25, 2021 at 15:27
  • Yeah, that looks correct, so it's not about the import path. What's suspect is the const and os in that output list since those aren't imported or defined in that test.py... Commented Oct 25, 2021 at 15:32
  • They are in the actual file. I was just trying to simplify things. Commenting them out makes no difference. Commented Oct 25, 2021 at 15:36
  • Then I'd just check the spelling of everything. Maybe also restart the notebook kernel just in case... Commented Oct 25, 2021 at 15:38

1 Answer 1

1

Probably the root of your files is not in the python module search path. You can check your module search path with:

import sys
print(sys.path)

If you append the location of your notebook and your package to that path, it should be importable:

sys.path.append('/path/to/where/jupyter/notebook/resides')
from my_package_directory.test import Test # should work

Note that you have to restart the kernel whenever you change the implementation of your module - This can be circumvented with some jupyter notebook magic.

Sign up to request clarification or add additional context in comments.

3 Comments

That seems to solve the import problem but it then gives a TypeError saying the Test() takes no arguments. Does Jupyter have any kind of caching that would cause this maybe? It's like it's not recognising changes to the class file. Even when I delete the cell and try again.
Actually restarting the kernel solved it. Many thanks
See the edit above ;-) Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.