Absolute Import Not Working, But Relative Import Does

家住魔仙堡 提交于 2019-12-07 11:41:33

问题


Here is my app structure:

foodo/
    setup.py
    foodo/
        __init__.py
        foodo.py
        models.py

foodo/foodo/foodo.py imports classes from the models.py module:

from foodo.models import User

which throws an ImportError:

ImportError: No module named models

However, it does work if I use a relative import:

from models import User

And it also works if I put in an pdb breakpoint before the import and continue.

I should be able to use both absolute and relative imports right?


回答1:


You have a local module foodoo inside the foodoo package. Imports in Python 2 always first look for names in the current package before looking for a top-level name.

Either rename the foodoo module inside the foodoo package (eliminating the possibility that a local foodoo is found first) or use:

from __future__ import absolute_import

at the top of your modules in your package to enable Python-3 style imports where the top-level modules are the only modules searched unless you prefix the name with . to make a name relative. See PEP 328 -- Imports: Multi-Line and Absolute/Relative for more details.



来源:https://stackoverflow.com/questions/39068391/absolute-import-not-working-but-relative-import-does

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!