Issue
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
Solution
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.
Answered By - Maicon Mauricio
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.