python import module from parent package

末鹿安然 提交于 2019-12-29 07:33:28

问题


I have the following directory structure

foo/
    __init__.py
    settings.py
    bar/
        __init__.py
        myfile.py

In myfile.py I have: import settings

I get the following error: ImportError: No module named settings, why? How can I efectively import the settings file from myfile.py


回答1:


From http://docs.python.org/2/tutorial/modules.html#intra-package-references :

from .. import settings

Hope it helps




回答2:


Here is another method that seems more clear:

In foo.__init__.py:

  __all__ = ['settings', ..(all other modules at 'foo' level you want to show)...]

In myfile.py:

# instead of "from .. import..." 
  from foo import settings 
  print settings.theThing


来源:https://stackoverflow.com/questions/14250058/python-import-module-from-parent-package

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