import java.awt.event.*什么意思_什么是 __future__ 模块 ?

__future__模块在Python中主要用于平滑版本迁移,它允许开发者在旧版本中引入新版本的特性,避免不兼容性。例如,当从Python 2.7迁移到3.x时,可以先通过__future__测试新功能,如print函数的转变。这个模块提供了一种执行文档的方式,记录了何时引入变化并何时成为必需。通过导入__future__并检查其内容,可以了解哪些新特性已引入并进行适配。
摘要由CSDN通过智能技术生成

958545e74fc64724cede621c8fa2851f.png

前言

不知道大家有没有注意到 python 有一个 __future__ 模块,如果大家有人看开源项目兼容 py2 和 py3 的话,它们的源代码中会经常出现这个模块,那么这个模块究竟有什么作用呢?

__future__

关于 __future__ 的作用,官方文档中也有明确提到,让我们看一下:

_future_ is a real module, and serves three purposes: 1. To avoid confusing existing tools that analyze import statements and expect to find the modules they’re importing. 2. To ensure that future statements run under releases prior to 2.1 at least yield runtime exceptions (the import of __future__ will fail, because there was no module of that name prior to 2.1). 3. To document when incompatible changes were introduced, and when they will be — or were — made mandatory. This is a form of executable documentation, and can be inspected programmatically via importing __future__ and examining its contents.

翻译过来大致意思如下:

  1. 为了避免混淆现有工具,分析import语句和期望找到他们要导入的模块。
  2. 确保2.1之前的版本导入 __future__产生运行时异常,因为2.1之前没有这个模块
  3. 记录何时引入了不兼容的更改,以及何时将其强制执行。 这是一种可执行文档,可以通过导入 __future__进行可编程式检查。

看完的感觉是不是这样的?

bda5d3d8d36b9392666aa0146cc6e2cc.png

如果是的话,就对了。别看官方文档上面写的很邪乎,其实总结起来很简单, python 在新版本会引入某些新的功能特性,但是有的时候有些改动是不兼容旧版本的,举个例子说,比如你的项目是用的是 py2.7,现在你需要迁移到 3.x 版本,直接升级到 3.x 肯定是不行的,那怎么办呢?这个时候就需要用到 _future_ 了,我们可以通过 __future 导入新版本某些模块,测试新版本的新功能,等测试成功后再升级到新的版本上.

例子

说完了,我们举个最典型的例子, print, 使用过 py2.7 和 py3.x 的小伙伴肯定都知道,在 3.x 的时候,print 成了一下函数,那么让我们在 py2.7 通过 __future__ 感受一下

1d7c6eb28ef0169ac2bdd5348d417084.png

除了 print,还有其他不少类似的,在官方文档中都有提及到,我这里就简单截个图,有兴趣的可以自己去官网研究一下

25b9e259c82dfe9c60f2a027b4b154b6.png

参考链接

29.10. __future__ - Future statement definitions - Python 3.6.8 documentation​docs.python.org What is __future__ in Python used for and how/when to use it, and how it works​stackoverflow.com
0240d8351b0aa7228fd1a750585e052e.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值