[英]Python - __init__ submodule using parent package
I have a package structure as: 我有一个包结构为:
parent_package/
__init__.py
module/
__init__.py
In the parent __init__.py
I have: 在父级
__init__.py
我有:
from __future__ import division
print(3/2) # 1.5
However, when I tried to reuse the import in its child, division does not take effect. 但是,当我尝试在其子级中重用导入时,划分不会生效。 In module's
__init__.py
: 在模块的
__init__.py
:
from parent_package.__init__ import division
print(3/2) # 1!
You are misunderstanding how the __future__
module works. 您误会了
__future__
模块的工作方式。 __future__
is a special module that is built into the python interpreter and changes how the interpreter parses and/or executes your code. __future__
是一个特殊的模块,内置在python解释器中, __future__
解释器解析和/或执行代码的方式。 In order for a __future__
import to have the desired effect, it must be of the form 为了使
__future__
导入具有所需的效果,它的形式必须是
from __future__ import <feature>
(See PEP 236 for the exact specification.) (有关具体规格,请参见PEP236 。)
However, in addition to the __future__
module that's built into the interpreter, __future__
is also a real module in the standard library ! 然而,除了
__future__
是内置于解释模块, __future__
也是 在标准库中一个真正的模块 ! The import from __future__ import divison
actually does two things: It enables the new division behavior, and it imports the feature specification from the real __future__
module. from __future__ import divison
实际上有两件事:启用新的除法行为, 并从实际的__future__
模块导入特征规范。 This is what you'll see if you take a look at the value of division
after the import: 如果您查看导入后的
division
值,将看到以下内容:
>>> from __future__ import division
>>> division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
When you do from parent_package.__init__ import division
, you're simply importing this variable. from parent_package.__init__ import division
,您只是在导入此变量。 But you're not enabling the new division behavior. 但是您没有启用新的部门行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.