4之间的包导入差异

4之间的包导入差异

本文介绍了Python 2.7和3.4之间的包导入差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于此目录层次结构:

.
├── hello
│   ├── __init__.py
│   └── world
│       └── __init__.py
└── test.py

和Python源文件:

And the Python source files:

if __name__ == '__main__':
    import hello



hello / __ init __。py:



hello/__init__.py:

import world



hello / world / __ init __。py:



hello/world/__init__.py:

print("yes you win")

使用Python 3.4运行test.py会抛出 ImportError 说找不到模块 world ,但是使用Python 2.7一切都很好。

Running test.py with Python 3.4 throws ImportError saying that module world is not found, but with Python 2.7 everything is fine.

我知道在搜索导入的模块时会引用 sys.path ,因此添加目录 hello sys.path 消除错误。

I know that sys.path is referenced when searching for the imported modules, so adding the directory hello to sys.path eliminates the error.

但是在Python 2.7,在导入 world 之前,目录 hello 也不在 sys.path 中。是什么导致这种差异?是否在Python 2.7中应用了递归搜索策略?

But in Python 2.7, before importing world, the directory hello is not in sys.path either. What causes this difference? Is there any recursive searching policy applied in Python 2.7?

推荐答案

Python 3使用绝对导入(参见,@ user2357112指出)。缺点是Python 3从每个 sys.path 条目的根目录进行搜索,而不是首先查询模块的目录,就像它是<$ c中的前置条目一样$ c> sys.path 。

Python 3 uses absolute imports (see PEP 328 as @user2357112 points out). The short of it is that Python 3 searches from the root of each sys.path entry, rather than first consulting the module's directory as if it were a prepended entry in sys.path.

要获得您想要的行为,您可以:

To get the behavior you want you can either:


  • 明确使用相对导入:来自。 hello 包中的import world

  • 使用绝对导入: import hello .world

  • Use relative imports explicitly: from . import world in the hello package
  • Use an absolute import: import hello.world

这篇关于Python 2.7和3.4之间的包导入差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 10:51