Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import packages in python using __init__.py

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

1 Answers

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.

like image 101
Maicon Mauricio Avatar answered Oct 25 '25 05:10

Maicon Mauricio