4

I've spent hours researching this small problem now, but clearly I wasn't able to figure out how to get my packages to work the way I want them to.

Here's an extract from my project structure:

package/
    __init__.py
    code.py
notebooks/
    testing.ipynb

With __init__.py containing:

from .code.py import *

Shouldn't I be able to import the functions from code.py within testing.ipynb as follows?

from ..package import *

The error message I'm getting is:

ImportError: attempted relative import with no known parent package
Maicon Mauricio
  • 2,052
  • 1
  • 13
  • 29
  • Does this answer your question? [Importing files from different folder](https://stackoverflow.com/questions/4383571/importing-files-from-different-folder) – smci Jun 14 '21 at 23:27
  • Does this answer your question? [sys.path different in Jupyter and Python - how to import own modules in Jupyter?](https://stackoverflow.com/questions/34976803/sys-path-different-in-jupyter-and-python-how-to-import-own-modules-in-jupyter) – Maicon Mauricio Jun 15 '21 at 00:01

1 Answers1

4

Shouldn't I be able to import the functions from code.py within testing.ipynb?

1. Try changing the current directory:

cd ..

And then import on the cell below:

from package.code import *

2. Placing the package directory inside the notebooks directory.

Using import package with the following directory structure example:

notebooks/
    package/
        __init__.py
        code.py
    testing.ipynb

3. Adding the paths you want Python to look at for importing at runtime:

import sys
sys.path.insert(0, "..")

from package.code import *

or

import sys
sys.path.insert(0, "../package")

from code import *

Python sets a variable with paths on where it looks for modules and packages. The working directory where the initial script was started is one of those paths. The above code adds the package directory to the path.

Refer to this answer for an in depth look on how Python path works.

Maicon Mauricio
  • 2,052
  • 1
  • 13
  • 29
  • 1
    Thanks, this worked! I still do not understand why my initial code wasn't working out since my project structure is exactly as you laid out, however it did work using `import sys` –  Jun 15 '21 at 14:07