python 中 __future__ 模块的使用

或许在看代码时会注意到 __future__ 模块的使用

1from __future__ import print_function

那么,__future__ 模块是做什么的?通俗地理解,就是在 python 旧版本中引入新版本的部分语法特征。在导入 __future__ 模块中的某一特征之后,它就可以在后续代码中使用了。

因为 python 是不保证向旧版本兼容的,所以旧版本的代码很可能在新版本会用不了。在准备将旧版本代码移植到新版本时,就可以先在旧版本代码中导入 __future__ 模块进行测试。

__future__ 模块在python 2.1 及其之后的版本中可用,其中,__future__ 模块引入了下面这些特性

特性 强制加入版本 效果
nested_scopes 2.2 PEP 227: Statically Nested Scopes
generators 2.3 PEP 255: Simple Generators
division 3.0 PEP 238: Changing the Division Operator
absolute_import 3.0 PEP 328: Imports: Multi-Line and Absolute/Relative
with_statement 2.6 PEP 343: The “with” Statement
print_function 3.0 PEP 3105: Make print a function
unicode_literals 3.0 PEP 3112: Bytes literals in Python 3000
generator_stop 3.7 PEP 479: StopIteration handling inside generators
annotations 4.0 PEP 563: Postponed evaluation of annotations

下面对其中四个举例说明

  • 精确除法
 1Python 2.7.15rc1 (default, Nov 12 201814:31:15
2[GCC 7.3.0] on linux2
3Type "help""copyright""credits" or "license" for more information.
41/3
50
610/3
73
8from __future__ import division  # 引入新特征
91/3
100.3333333333333333
1110/3
123.3333333333333335
  • with 语句
 1file_handle = open('file_path''mode')
2file_handle.read()
3file_handle.close()
4
5# from __future__ import with_statement # 引入新特征之后
6with open('file_path''mode'as file_handle:
7    file_handle.read()
8
9# 使用 with 语句,一些文件和进程的善后工作就可以不用那么操心,with 的用法也不止这些
10
  • print 语句
 1Python 2.7.15rc1 (default, Nov 12 201814:31:15
2[GCC 7.3.0] on linux2
3Type "help""copyright""credits" or "license" for more information.
4print 'hello'  # 打印输出不需要括号
5hello
6import sys
7print >> sys.stderr, 'output to the standard error stream'  # 输出到标准错误流
8output to the standard error stream
9# 引入新特征之后
10from __future__ import print_function
11print ('hello')  # 需要括号
12hello
13print ('output to the standard error stream', file=sys.stderr)  #输出到标准错误流
14output to the standard error stream
  • 字符串
 1Python 2.7.15rc1 (default, Nov 12 201814:31:15
2[GCC 7.3.0] on linux2
3Type "help""copyright""credits" or "license" for more information.
4type('hello')  # 字符串为 str 类型
5<type 'str'>
6type(b'hello')
7<type 'str'>
8type(u'hello')
9<type 'unicode'>
10# 引入新特征之后
11from __future__ import unicode_literals
12type('hello')  # 字符串为 unicode 类型
13<type 'unicode'>
14type(b'hello')
15<type 'str'>
16type(u'hello')
17<type 'unicode'>

官方文档:https://docs.python.org/zh-cn/3/library/__future__.html

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注