简体   繁体   English

模块中的Python绝对导入失败

[英]Python absolute import in module fails

I have a project which looks like this: 我有一个看起来像这样的项目:

my_project/
          __init__.py -- empty
          run.py
          datacheck/
                  __init__.py -- empty
                  datacheck.py -- containing class DataCheck(object)
                  config.py -- containing BusinessConfig(object)
                  business.py -- containing class BusinessCheck(DataCheck)

My PYTHONPATH is configured to have /my_project in it. 我的PYTHONPATH配置为包含/ my_project。

In run.py, I have the following code: 在run.py中,我有以下代码:

from datacheck.business import BusinessCheck
business = BusinessCheck()
business.check_data()

In business.py, I have the following imports that fail: 在business.py中,我有以下导入失败:

from datacheck.config import BusinessConfig
from datacheck.datacheck import DataCheck

A relative import like from .config import BusinessConfig works - however I've read in numerous threads that an absolute import is preferred. from .config import BusinessConfig相对导入可以正常工作 - 但是我已经在很多线程中读到绝对导入是首选。

To do a simple test, I also created the following: 为了做一个简单的测试,我还创建了以下内容:

myproject/
          __init__.py -- empty
          run_test.py
          test/
              __init__.py -- empty
              test1.py -- containing class Test1(object)
              test2.py -- containing class Test2(Test1)

run_test.py imports and runs the Test2 class, this didn't fail. run_test.py导入并运行Test2类,这没有失败。

It left me a bit flabbergasted, I don't understand why my absolute imports in datacheck are not working - can anyone explain? 它让我有点大吃一惊,我不明白为什么我在datacheck中的绝对导入不起作用 - 谁能解释一下?

You should prefer absolute imports if your module can be used as __main__ , as explained in the documentation . 如果您的模块可以用作__main__ ,则应该更喜欢绝对导入,如文档中所述。 If not, relative imports are fine. 如果没有,相对进口是好的。

These imports fail, because your package datacheck contains a module datacheck (same name). 这些导入失败,因为您的包datacheck包含模块datacheck (同名)。 When looking up the name, Python implicitly looks inside the package first. 查找名称时,Python首先隐式查看包内部。 There, it finds the module datacheck . 在那里,它找到了模块datacheck This module, however, does not contain anything with the name config , so the import fails. 但是,此模块不包含名称为config任何内容,因此导入失败。

If you want to use absolute imports, move all the stuff from the module datacheck into the __init__.py of the package, or rename it. 如果要使用绝对导入,请将模块datacheck所有内容移动到包的__init__.py中,或重命名它。

I know this is many years later, but for the sake of others searching here, I was able to resolve a similar problem with this bit of code: 我知道这是多年以后,但为了其他人在这里搜索,我能够用这段代码解决类似的问题:

from __future__ import absolute_import

After that, absolute imports worked fine in Python 2.6 and 2.7. 在那之后,绝对导入在Python 2.6和2.7中运行良好。

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

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