Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Doing absolute imports from a subfolder

Basically I'm asking the same question as this guy: How to do relative imports in Python?

But no one gave him a correct answer. Given that you are inside a subfolder and you want to go up a directory and then into ANOTHER subfolder, doing what they suggested does not work (as the OP pointed out in his comments to their answers).

I know that you can do this by using sys.path, but I would prefer a cleaner method.

Example:

App
__init__.py
Package_A
--__init__.py
--Module_A.py
Package_B
--__init__.py
--Module_B.py

How would I import Module_A into Module_B?

like image 455
ryeguy Avatar asked Jan 21 '09 00:01

ryeguy


2 Answers

main.py
setup.py
app/ ->
    __init__.py
    package_a/ ->
       __init__.py
       module_a.py
    package_b/ ->
       __init__.py
       module_b.py
  1. You run python main.py.
  2. main.py does: import app.package_a.module_a
  3. module_a.py does import app.package_b.module_b

Alternatively 2 or 3 could use: from app.package_a import module_a

That will work as long as you have app in your PYTHONPATH. main.py could be anywhere then.

So you write a setup.py to copy (install) the whole app package and subpackages to the target system's python folders, and main.py to target system's script folders.

like image 74
nosklo Avatar answered Oct 14 '22 14:10

nosklo


If I'm reading correctly, in Python 2.5 or higher:

from ..Module_B import Module_B

I thought I was well-versed in Python but I had no idea that was possible in version 2.5.

like image 26
David Z Avatar answered Oct 14 '22 13:10

David Z