Python __future__ 模块 - future 语句定义

Glossary
https://docs.python.org/3.10/glossary.html

术语对照表
https://docs.python.org/zh-cn/3.10/glossary.html

__future__ 是一个真正的模块。

Python 提供了 __future__ 模块,把下一个新版本的特性导入到当前版本,我们就可以在当前版本中测试一些新版本的特性。

Python 为了确保你能顺利过渡到新版本,特别提供了 __future__ 模块,让你在旧的版本中试验新版本的一些特性。

# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

__future__

A future statement, from __future__ import <feature>, directs the compiler to compile the current module using syntax or semantics that will become standard in a future release of Python. The __future__ module documents the possible values of feature. By importing this module and evaluating its variables, you can see when a new feature was first added to the language and when it will (or did) become the default:
future 语句,from __future__ import <feature> 指示编译器使用将在未来的 Python 发布版中成为标准的语法和语义来编译当前模块。__future__ 模块文档记录了可能的 feature 取值。通过导入此模块并对其变量求值,你可以看到每项新特性在何时被首次加入到该语言中以及它将 (或已) 在何时成为默认:

>>> import __future__
>>> __future__.division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)

1. from __future__ import division

引入精确除法,在 Python 2 中除法 / 属于阶段除,加上该语句后可将 / 改成精确除法。3 / 4 在 Python 2 中的结果为 0,引入精确除法后 3 / 4 = 0.75,此时若需要阶段除可使用 //

在 Python 2 中,如果是整数相除,结果仍是整数,余数会被扔掉,这种除法叫地板除。要做精确除法,必须把其中一个数变成浮点数。

在 Python 3 中,所有的除法都是精确除法,地板除用 // 表示。

如果想在 Python 2 的代码中直接使用 Python 3 的除法,可以通过 __future__ 模块的 division 实现。

2. from __future__ import absolute_import

模块绝对路径引用。

当自己在当前目录开发的模块名与系统模块名发生冲突时,Python 会首先使用自己开发的模块 (首先在当前目录搜索)。若要使用系统自带的模块,需在代码开头加上上面的引用语句,将模块引用方式转化为绝对路径引用。

main.py 模块中加入了绝对路径引用后,当要引用的 string 模块为系统模块时可以直接使用 import string,若此时要引用自己编写的 string.py 模块时,则需使用绝对路径引用 from pkg import string

3. from __future__ import print_function

使用该语句后,print 不再支持 print "abc" 的方式,仅支持 print("abc")

在这里插入图片描述

mandatory ['mændət(ə)rɪ]:adj. 强制的,托管的,命令的 n. 受托者 (等于 mandatary)

References

[1] Yongqiang Cheng, https://yongqiang.blog.csdn.net/

  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yongqiang Cheng

梦想不是浮躁,而是沉淀和积累。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值