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?
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.
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')
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