Lawhatre
Lawhatre

Reputation: 1450

Relative import in python packages

Following is my python package structure

PKG
|-->build
|-->dist
|-->src
|   |-->pkg
|   |   |-->data
|   |   |   |-->__init__.py
|   |   |   |-->module1.py
|   |   |-->dataset
|   |   |   |-->__init__.py
|   |   |   |-->module2.py
|   |   |-->__init__.py
|   |-->pkg.egg-info
|   |-->__init__.py
|-->__init__.py  
|-->LICENSE
|-->>README.md
|-->setup.py

I want to use some function of module1 in module2. So I tried

  1. from ..data import module1 which gave ImportError: attempted relative import with no known parent package
import sys 
sys.path.append('../../')
from data import module1

gave ModuleNotFoundError: No module named 'data'

At this point in time, I'm unsure on how to fix this.

Upvotes: 1

Views: 431

Answers (3)

Lawhatre
Lawhatre

Reputation: 1450

  • In development phase
import sys
sys.path.append('/path/to/src')
from pkg.data import module1
  • In deployment phase remove
import sys
sys.path.append('/path/to/src')

and just keep

from pkg.data import module1

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155546

Your problem is almost certainly due to running module2.py as a script "raw", rather than executing it as a qualified module name rooted in pkg, e.g. running python3 path/to/pkg/dataset/module2.py. The problem with that is that it runs module2.py in such a way that it thinks itself a standalone script, it doesn't know it's "supposed" to be pkg.dataset.module2 at all.

The correct solution is to, after installing the package (into system or user site-packages, or installing it into an active virtual environment), execute it in such a way that it knows its qualified name correctly, e.g.:

python3 -m pkg.dataset.module2

That tells Python to import the qualified module by looking it up in the module search path, through the parent packages, so it is run with the knowledge that it is in a package, and can therefore perform relative imports.

Upvotes: 2

Hot Shot
Hot Shot

Reputation: 115

Just try to use sys.path.append("../")

Upvotes: 0

Related Questions