python import module from parent package

2020-02-12 02:39发布

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

2条回答
小情绪 Triste *
2楼-- · 2020-02-12 03:01

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
查看更多
登录 后发表回答