在Python3中,不幸的决定是删除相对导入的功能。我目前正在现代化大量使用此功能的大量Python2代码。
因此,现在,我的代码具有以下效果:
import other_function
import another_class_file
...
foo = other_function.calculate_foo() + other_function.constant
bar = another_class_file.Bar(foo)
Run Code Online (Sandbox Code Playgroud)
据我所知,在Python3中执行此操作的“正确”方法是:
from other_function import foo as calculate_foo
from other_function import constant
from another_class_file import Bar
....
foo = calculate_foo() + constant
bar = Bar(foo)
Run Code Online (Sandbox Code Playgroud)
但是,这种方式非常肮脏:不是总知道确切的函数或类的来源,而是全都放在了顶层,而了解某物的来源的唯一方法是查看导入语句的列表。顶端。总的来说,代码变得更加模棱两可。显式胜于隐式。
有什么办法可以实现相同的表示法,类似于from other_function import foo as other_function.calculate_foo?我不想手动将这些名称命名为匈牙利风格。
相对导入在Python 3中仍然存在。即使已将其删除,您的第二个代码段也无法解决该问题。您似乎已经对真正的相对进口感到困惑。
相对导入是指程序包中的代码(例如,程序包的pkg.mod子模块pkg中)在不需要重复该pkg部分的情况下,导入同一程序包的其他内容。在Python 2上,如果pkg.mod要导入pkg.mod2,它可以做到
import mod2
Run Code Online (Sandbox Code Playgroud)
这是一个隐式相对导入。这些存在很多歧义性问题,因此引入了显式的相对导入语法:
from . import mod2
Run Code Online (Sandbox Code Playgroud)
在Python 3上,已禁用隐式相对导入语法,而支持显式语法。在Python 2上,隐式相对导入语法仍然存在,但是强烈建议使用显式语法,并且可以使用禁用隐式语法from __future__ import absolute_import。
看起来您的代码似乎没有使用包或任何形式的相对导入。您应该能够继续使用以前使用的相同导入语法。
如果other_function和another_class_file是包中的同级子模块,则必需的语法更改为
from . import other_function
from . import another_class_file
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
207 次 |
| 最近记录: |