Reputation: 183
I have 2 identical files:
a.py
and b.py
.
they both contain the line
from mypackage.utils import common
I also have a package:
mypackage/
__init__.py
mymodule.py
utils/
__init__.py
common.py
myutils1.py
b.py
data_classes/
__init__.py
command_file.py
myclass.py
I preliminarly do a
pip install mypackage
Then I run:
python a.py
which succeeds
and then I run
python b.py
(note that b.py is a file within mypackage)
b.py fails with no module named utils
Any ideas?
(note: I am fairly new to stackoverflow, this is not really related to Python modules import fails , although somehow a followup question, so if I am doing something wrong by asking on a new question please let me know :)
edit:
I install mypackage (and specifically the file b within mypackage) in:
$HOME\github\mypackage\mypackage\utils\b.py
I copy b.py to a.py in: $HOME\github\mypackage this works
I copy b.py to a.py in: $HOME\github\ this doesn't work
so this somewhat explains this... although I still don't know how to fix it!
edit: I edited setup.py from the following line:
packages=['mypackage'],
to
packages=['mypackage','mypackage.data_classes','mypackage.utils']
this seems to fix my problem: now everything works.
is there any good reason why I should not do this?
Upvotes: 3
Views: 157
Reputation: 702
The issue is that Python doesn't know where to find your package in the first place. In the first explain, it looks at the current directory and is able to understand that it is a module, thanks to your __init__.py
file. So it is able to search for your utils.
In the 2nd example, there is no __init__.py
file in the current directory and so Python doesn't know where to search for the modules.
The PYTHONPATH
variable tells Python the directories/modules to search for accessed methods/packages.
So in your case, if you can add your current directory to the PYTHONPATH
like export PYTHONPATH=$(pwd)
while in "$HOME\github\", that should help resolve your issue.
P.S: The OP wants to use the installed package instead of the local module. This solution is applicable when your local modules are not visible for the Python interpreter. For more details, check the comments below.
Upvotes: 1
Reputation: 183
I edited setup.py from the following line:
packages=['mypackage'],
to
packages=['mypackage','mypackage.data_classes','mypackage.utils']
this seems to fix my problem: now everything works.
is there any good reason why I should not do this?
Upvotes: 0
Reputation: 1137
i have found a couple of solutions to this:
import common
or
import sys
sys.path.append("..\\..") # relative path to mypackage, check the slash if you're on linux
from mypackage.utils import common
some questions:
why are you moving b.py?
have you installed your package?
Upvotes: 1