I can't figure out how to import modules from sibling directories in Python 3 using absolute imports.
sys.path
. __init__.py
and setup.py
. For option 1. I figured out how to import modules from sibling directories by modifying the sys.path
, but this method seems a little hackey to me. Also, I've read that it is not preferred. Why? Is there something inherently wrong or dangerous about modifying the sys.path
?
For option 2. What exactly do I need to do make my package pip installable? I've alreay created my __init__.py
file, but it seems that I need to create and configure a setup.py
script to prepare my package for distribution? I'm still in the development mode, so is this really the best/pythonic method? If it is, then do I just type python setup.py install
into my terminal after creating the setup.py
?
Edit: I'm now trying to figure this out using absolute imports as python 3 does support relative imports.
From what I've read, Python 3 does not support relative imports
It does.
To import myproject/foo/__init__.py
from myproject/bar/baz.py
, you can use this:
from .. import foo
Or if you want to import an object/module in foo
:
from ..foo import object
This requires myproject
to be a package, so myproject/__init__.py
has to exist.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.