2

I have a project structure like this...

app/
    main.py
    app/
        __init__.py
        boot.py
        server.py
        controllers/
            __init__.py
            home.py

The imports are...

# main.py
from app import server

# server.py
from . import boot

# boot.py
from . import controllers

# controllers/__init__.py
from . import home

# controllers/home.py
from .. import boot

Now all the imports are working except the last one. The error thrown is...

ImportError: cannot import name boot

What's the problem? (I am using Python 3.2)

treecoder
  • 43,129
  • 22
  • 67
  • 91
  • 3
    Can I ask why you are doing relative imports? They tend to be fragile and also harder to read when doing maintenance down the road. – Silas Ray May 22 '12 at 15:57
  • I have tried everything -- nothing is working. Can you suggest something else? – treecoder May 22 '12 at 15:58

1 Answers1

8

You are importing boot which is importing controllers, which is then asked to import home, and home then tries to import boot, but it wasn't done importing yet. Don't do this, you are creating a circular dependency here.

Also see Circular import dependency in Python

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • So how do I circumvent the circular imports? Because I really need to import `boot.py` into `home.py` – treecoder May 22 '12 at 16:01
  • 3
    By organizing your code better; restructure until you do not need to load parent packages would help, for example. – Martijn Pieters May 22 '12 at 16:02
  • 6
    You have to restructure your code. 99% of the time, if your code fits a naturally hierarchical pattern, and your higher level components have to import your lower level ones, you have a design flaw. – Silas Ray May 22 '12 at 16:02