简体   繁体   中英

Better way to import module from subdirectories at the same level

I have the following project structure main - exp1 - mod1.py - exp2 - mod2.py

I can import a module abc from mod2.py in mod1.py using the following

from ..exp2.mod2 import abc

Is there any other way of importing these modules where I do not have to use .. ?

you can always import using the absolute module name

from main.exp2.mod2 import abc  
# or 
# from exp2.mod2 import abc
# (?)

for me this is the preferred way.

this way and yours are the only available options...

Not sure there is an easier way than using '..' unless you alter the project structure:

# mod1.py
    import sys
    sys.path.append('..')
    from exp2.mod2 import abc

You should always set a PYTHONPATH and then import from that path as main.

In your case you should do the following,

export PYTHONPATH=main   (Full path of main dir in shell )
from exp2.mod2 import abc

If you do .. it is not a proper way also you will face some issue when you transfer the code or during the deployment time

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM