简体   繁体   English

Python:导入导入模块的模块

[英]Python: importing a module that imports a module

So in a file foo I am importing modules: 所以在文件foo中,我正在导入模块:

import lib.helper_functions
import lib.config

And in helper_functions.py, I have: 在helper_functions.py中,我有:

import config

When I run the main function of foo I get an ImportError 当我运行foo的main函数时,我得到一个ImportError

EDIT: Here is the structure of the files I have 编辑:这是我的文件的结构

foo.py
lib/
    config.py
    helper_functions.py

The error results from importing config in helper_functions 在helper_functions中导入配置会导致错误

Traceback (most recent call last):
  File "C:\Python33\foo.py", line 1, in <module>
    import lib.helper_functions
  File "C:\Python33\lib\helper_functions.py", line 1, in <module>
    import config
ImportError: No module named 'config'

So: when I run foo.py the interpreter is complaining about the import statements of helper_functions. 所以:当我运行foo.py时,解释器抱怨helper_functions的import语句。 Yet when I run the main of helper_functions, no such error appears. 但是,当我运行helper_functions的主程序时,没有出现此类错误。

You need to import config using an absolute import. 您需要使用绝对导入来导入config Either use: 可以使用:

from lib import config

or use: 或使用:

from . import config

Python 3 only supports absolute imports; Python 3仅支持绝对导入; the statement import config only imports a top level module config . 语句import config仅导入顶级模块config

In python each module has its own namespace. 在python中,每个模块都有自己的命名空间。 When you import another module you are actually only importing its name. 导入另一个模块时,实际上只导入其名称。

The name "config" exists in the module helper_functions because you imported it there. 名称“config”存在于模块helper_functions中,因为您在那里导入了它。 Importing helper_functions in foo brings only the name "helper_function" into foo's namespace, nothing else. 在foo中导入helper_functions只会将名称“helper_function”带入foo的命名空间,没有别的。

You could actually refer to the "config" name in foo.py with your current imports by doing something like: 您实际上可以通过执行以下操作来引用当前导入的foo.py中的“config”名称:

lib.helper_functions.config

But in python is always better to be explicit rather than implicit. 但是在python中总是最好显式而不是隐式。 So importing config in in foo.py would be the best way to proceed. 因此,在foo.py中导入config是最好的方法。

#file foo.py
import lib.helper_functions
import config

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM