Suppose I have the following directory structure:
workspace/
__init__.py
ys_manage/
__init__.py
manage.py
ys_utils/
__init__.py
project_dicts.py
Now, suppose I need access to project_dicts.py
in manage.py
. Also, my $PATH
includes /home/rico/workspace/ys_manage
.
I need to be able to run manage.py
from any directory on my machine and still be able to access project_dicts.py
.
My $PYTHONPATH
only has /home/rico/workspace
.
If I include the following in manage.py
I can run the file from ~/workspace/ys_manage
but not anywhere else.
import sys
sys.path.append('..')
from ys_utils import project_dicts
It appears that the '..'
gives a relative path to where the directory where the file is run, not where the file is located. Is this correct?
I wanted to try and use ys_manage/__init__.py
to import project_dicts.py
so that it would be available in manage.py
universally. Is this a good idea?
I've never used __init__.py
for anything other than a "package creator". That is, I've never used it for initialization purposes. Perhaps I'm doing it wrong.
Contents of ys_manage/__init__.py
:
import sys
sys.path.append('..')
from ys_utils import project_dicts
Should I include something in manage.py
to look for this import?
When I try and run manage.py
I get the following error:
NameError: global name 'project_dicts' is not defined
As a secondary question, do I need to have workspace/__init__.py
? I'd really rather not have it because ys_manage
and ys_utils
(and about a dozen other packages) are all under revision control and used by several other developers...workspace
is not.
Generally, I've found trying to use relative paths for imports dangerous and very error prone. I'd suggest just putting workspace on your PYTHONPATH (or adding it programatically in __init__.py
) and importing everything relative to that static location. It will make your code more easily readable too, as you'll be able to track down where imports are coming from much more quickly and clearly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With