Archive

Posts Tagged ‘project structure’

Relative import in Python

September 6, 2011 Leave a comment

The following post is based on nosklo’s answer who explained relative imports very nicely in this thread.

Imagine the following project structure:

main.py
setup.py
app/ ->
    __init__.py
    package_a/ ->
       __init__.py
       module_a.py
    package_b/ ->
       __init__.py
       module_b.py

Problem: how to use module_b.py from module_a.py?

Solution:

  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.”