from future import absolute_import
from future import division
from future import print_function
from future import unicode_literals
print_function
https://blog.youkuaiyun.com/xiaotao_1/article/details/79460365
Python future 模块
引入 __future__
模块的原因
__future__
模块为了让代码向后兼容。特性在最新版本的 Python 中已经成为语法的一部分,在旧版本的 Python 中你需要使用 future
语句。
__future__
是一个真正的模块,这主要有 3 个原因:
- 避免混淆已有的分析 import 语句并查找 import 的模块的工具。
- 确保 future 语句 在 2.1 之前的版本运行时至少能抛出 runtime 异常(import future 会失败,因为 2.1 版本之前没有这个模块)。
- 当引入不兼容的修改时,可以记录其引入的时间以及强制使用的时间。这是一种可执行的文档,并且可以通过 import future 来做程序性的检查。
每一条 _Feature 语句的格式
每一条语句都是以下格式:
FeatureName = _Feature(OptionalRelease, MandatoryRelease, CompilerFlag)
OptionalRelease 来记录特性首次发布时的 Python 版本。MandatoryRelease 来记录这个特性是何时成为语言的一部分的,从该版本往后,使用该特性将不需要 future
语句,不过很多人还是会加上对应的 import
。并且都与 sys.version_info
格式一致,是一个 5 个元素的元组:
(
PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int
PY_MINOR_VERSION, # the 1; an int
PY_MICRO_VERSION, # the 0; an int
PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string
PY_RELEASE_SERIAL # the 3; an int
)
通常 OptionalRelease 要比 MandatoryRelease 小,例如:
with_statement = _Feature((2, 5, 0, "alpha", 1),
(2, 6, 0, "alpha", 0),
CO_FUTURE_WITH_STATEMENT)
表示 with_statement
特性,在 Python 2.5.0 时 第一次被发布,在 Python 2.6.0 时 成为语言的语法。意味着,使用 with
语句,如果你在 Python 2.5.0 需要 from __future__ import with_statement
,如果你在 Python 2.6.0 那么直接使用 with
语句。
MandatoryRelease 也可能是 None
, 表示这个特性已经被撤销。
_Feature
类的实例有两个对应的方法,getOptionalRelease()
和 getMandatoryRelease()
。
CompilerFlag 是一个标记,对于动态编译的代码,需要将这个标记作为第四个参数传入内建函数 compile()
中以开启对应的特性。这个标记存储在 _Feature
类实例的 compiler_flag
属性中。这些值必须与 在 Include/compile.h
中的定义的 CO_xxx
标志匹配.
如何使用 __future__
future
语句的形式为 from __future__ import FeatureName
,使用该语句让当前版本的 Python 支持 该特性。
future
语句必须在靠近模块开头的位置出现。
future
语句所启用的所有历史特性仍然为 Python 3 所认可。 其中包括 absolute_import
, division
, generators
, generator_stop
, unicode_literals
, print_function
, nested_scopes
和 with_statement
。
它们都已成为冗余项,因为它们总是为已启用状态,保留它们只是为了向后兼容。
__future__
有哪些特性
all_feature_names
是一个列表,显示 __future__
模块支持特性的名称。
__future__
中不会删除特性的描述。从 Python 2.1 中首次加入以来,通过这种方式引入了以下特性:
特性 | 可选版本 | 强制加入版本 | 效果 |
---|---|---|---|
nested_scopes | 2.1.0b1 | 2.2 | PEP 227: Statically Nested Scopes |
generators | 2.2.0a1 | 2.3 | PEP 255: Simple Generators |
division | 2.2.0a2 | 3.0 | PEP 238: Changing the Division Operator |
absolute_import | 2.5.0a1 | 3.0 | PEP 328: Imports: Multi-Line and Absolute/Relative |
with_statement | 2.5.0a1 | 2.6 | PEP 343: The “with” Statement |
print_function | 2.6.0a2 | 3.0 | PEP 3105: Make print a function |
unicode_literals | 2.6.0a2 | 3.0 | PEP 3112: Bytes literals in Python 3000 |
generator_stop | 3.5.0b1 | 3.7 | PEP 479: StopIteration handling inside generators |
annotations | 3.7.0b1 | 3.10 | PEP 563: Postponed evaluation of annotations |
https://blog.youkuaiyun.com/weixin_36670529/article/details/86238610
https://www.cnblogs.com/dylancao/p/11904524.html
https://www.jb51.net/article/178900.htm