Reputation: 4735
I have some scripts that used shared code in a different directory (that happens to be a subdirectory).
For various reasons, I do not want to package the shared code up into a Python package, nor do I want to dump all the files into a single directory, nor do I want to add the subdirectory to the path.
Is there any way to do a relative import & pull in the files in the subdirectory in Python 3?
In IPython3
import subdir.my_shared_library
works fine.
However, this fails in Python3, along with every attempt I've made to add __init__.py
files and do relative imports explicitly like import .subdir.my_shared_library
.
Is there a way to get around this?
Upvotes: 3
Views: 2965
Reputation: 414315
Yes. Use absolute import:
import subdir.my_shared_library
It assumes that the parent of subdir
is in sys.path
as it is the case when you are running a Python script from the same directory (the parent).
It would work even if there were no __init__.py
file in the subdirectory. subdir
would be treated as an implicit namespace package in this case. Though you should not abuse this feature.
If you don't want subdir
to be a Python package i.e., if you want to consider my_shared_library
as a top-level module then add subdir
itself to the python path (assuming bash syntax for the command and the empty original PYTHONPATH
envvar):
$ PYTHONPATH=subdir python -m your_module
where your_module.py
uses import my_shared_library
. Or (worse) add sys.path.insert(1, 'subdir')
to your module directly.
Upvotes: 1
Reputation: 93
You should only need to add an __init__.py
to \subdir
and then import via from subdir import my_shared_library
. If you don't want to compile it into a package with the rest of your code, you could also append it to your PATH
using sys.path.append('subdir')
or the typical export to PYTHONPATH
. If you don't want to touch paths, you can just drop it in the global site-packages
, or, alternatively, create a virtual environment through something like pyvenv
and put your library in the package folder there.
Upvotes: 5
Reputation: 94
Try appending to PYTHONPATH from the shell like
export PYTHONPATH=$PYTHONPATH:subdir; python your_program.py
https://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH
But the better way to do it is to append to sys.path:
sys.path.append('subdir')
Upvotes: 1