我是在看cleverhans的源码发现python中的__future__语句的:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
查了一下,主要是解决版本不兼容问题,例如一个python 2.7 的代码迁到 python 3.7, 如果直接换成python 3.7的解释器的话可能会有很多问题,所以可以通过用from future import xxx 来渐进式改进当前版本代码的不兼容问题。
当然另一方面,可能你只是某个代码想要用python最新版本的特性,也可以使用以上声明
让我困惑的几个问题:
1.future 模块是如何定义的,最新版本的python还有future特性吗?
2.python 2.x的解释器是如何适应future特性的
查了一下,回答如下:
future模块中定义了在将来版本中一定会成为标准的一些语法,自从python 2.1 中引入future模块后,这些标准只增不减。因而python3.7自然也有future模块。
可以通过在python文件调用help来查看future模块的具体特性:
help(__future__)
关于解释器如何兼容,官方文档是这样解释的:
当识别到from future import xxx这样的声明后,编译器会生成一些为了适应future特性与原版不同的代码,但同时也可能引起新的不兼容问题:
A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.
以上是一点个人总结,希望对看的朋友有所帮助~