Reputation: 3534
I have a directory structure like this:
PYTHONPATHDIR
App1
someModule.py
utils.py
utils
hasClassIWantToImport.py
And I want someModule to import something from utils.hasClassIWantToImport. When I call:
from utils.hasClassIWantToImport import ClassIWant
it cannot resolve "hasClassIWantToImport" because it thinks I'm talking about the utils.py in the current directory.
How do I get around this? I know I can rename one of the "utils" but would rather not...
Upvotes: 0
Views: 3982
Reputation: 4937
There isn't any way that you are going to be able to maintain access to both PYTHONPATHDIR/utils
and PYTHONPATHDIR/App1/utils.py
simultaneously without referring to one of them relative to something else.
If you modify your path so that PYTHONPATHDIR
is at the head of the list, then you can import utils.hasClassIWantToImport
but you will lose access to utils.py
.
About the best you can do is make App1
a package by placing a __init__.py
file into it and munge your path like @Gryphius suggested (i.e. put /path/to/utils
at the head of sys.path
). When you want access to utils.hasClassIWantToImport
, you
from utils.hasClassIWantToImport import ClassIWant
To import files relative to utils.py
, you will then
from App1.utils import ClassIWantFromApp1
However, this is a horrible hack just to avoid renaming utils.py
. I recommend saving yourself the long-term headache of path manipulation and just rename that file.
Upvotes: 1
Reputation: 78976
not sure if I have understood your directory setup correctly, but you could try:
import sys
sys.path.insert(0,'/path/to/utils')
from hasClassIwantToImport import ClassIWant
Upvotes: 1