简体   繁体   中英

Import a module named the same as the grandparent package

In Python 2.6.6, I have a module named the same as its grandparent. My project structure (a web app using Flask) looks roughly like this:

panel/
  run.py
  panel/
    __init__.py
    database.py
    views/
      __init__.py
      root.py
      dash.py
      panel.py
    users/
      __init__.py
      models.py

Note that the package name, next to run.py, is panel . I also have a module named panel.views.panel . If from within panel/__init__.py I import panel.views.panel, using any of these three styles:

from panel.views import panel
from panel.views import panel as panel_view
import panel.views.panel as panel_view

After importing panel.py , none of my other imports work. For example, panel.users.models attempts to import database.py, and this traceback is thrown:

Traceback (most recent call last):
  File "run.py", line 5, in <module>
    from panel import app
  File "/opt/www/panel/panel/__init__.py", line 8, in <module>
    from panel.views import root
  File "/opt/www/panel/panel/views/root.py", line 9, in <module>
    from panel import database;
ImportError: cannot import name database

I spoke with a few people in the #pocoo IRC channel, and from what they described, the issue is that from within views/root.py, Python thinks import panel.database means to import database from panel.py sitting next to it.

This doesn't make sense to me though because PEP 328 outlines (what reads like) this exact problem, and made absolute imports the default in order to fix this. I'm using Python 2.6.6, so this should be the default. Just to be sure though, I added the line from __future__ import absolute_import but this didn't make a difference; the same error importing database.py occurred.

Renaming panel.py fixes this issue, however, I'm extremely curious to know why this doesn't work as it is written, and especially if there's anything I can do to make this work.

You said you added the line from __future__ import absolute_import , but you didn't say to which file you added it. Be sure to add it to root.py.

This section of the python tutorial explains what is happening in your case: http://docs.python.org/tutorial/modules.html#intra-package-references

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