Import a module with a name similar to the grandparent package

In Python 2.6.6, I have a module named just like its grandfather. My project structure (a web application using Flask) looks something 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 the panel . I also have a module called panel.views.panel . If from within / __ 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 import jobs work. For example, panel.users.models tries to import database.py, and this trace 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 several people in the IRC # pocoo channel and from what they described, the problem is that from inside views / root.py Python thinks that import panel.database means importing the database from the .py panel, sitting next to it.

This makes no sense to me because PEP 328 describes (what it reads) this exact problem and made absolute default imports to fix it. I am using Python 2.6.6, so this should be the default value. However, to be sure, I added the line from __future__ import absolute_import , but this did not affect; An error occurred while importing database.py data.

Renaming panel.py fixes this problem, however, I am very curious to know why this does not work as it is written, and especially if I can do something to make this work.

+4
source share
1 answer

You said you added the line from __future__ import absolute_import , but you did not say which file you added it to. Remember to add it to root.py.

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

+2
source

Source: https://habr.com/ru/post/1434943/


All Articles