Python3.7 新特性

简介

Python3.7 发布于2018年6月27日,这儿总结一下改版本引入的一些新功能

官方新特性链接 Python3.7 新特性

安装

此处主要介绍在Ubuntu下安装 Python3.7

  1. 添加deadsnakes源
    • sudo add-apt-repository ppa:deadsnakes/ppa
    • sudo apt-get update
  2. 安装 Python3.7
    • sudo apt install python3.7-full
  3. 安装 Python3.7 的pip
    • python3.7 -m ensurepip --upgrade

breakpoint 函数

内置了新的 breakpoint() 函数,作为简单进入Python调试的方式,使用 breakpoint() 函数,相当于设置了断点,遇到 breakpoint() 会自动进入 pdb 调试模式

内置 breakpoint() 会调用 sys.breakpointhook()。 在默认情况下后者会导入 pdb 然后再调用 pdb.set_trace(),但是通过将 sys.breakpointhook() 绑定到你选定的函数,breakpoint() 可以进入任何调试器。 此外,环境变量 PYTHONBREAKPOINT 可被设置为你选定的调试器的可调用对象。 设置 PYTHONBREAKPOINT=0 会完全禁用内置 breakpoint()。

具有纳秒级精度的新时间函数

现代系统的时钟精度可以超过由 time.time() 函数及其变化形式所返回的浮点数的有限精度。 为了避免精度损失,Python3.7 在 time 模块中增加了原有计时器函数的六个新“纳秒版”变化形式

  • time.clock_gettime_ns()
  • time.clock_settime_ns()
  • time.monotonic_ns()
  • time.perf_counter_ns()
  • time.process_time_ns()
  • time.time_ns()

这些新函数会以整数值的形式返回纳秒数。

1
2
3
4
5
6
import time

print(time.time())
print(time.time_ns())
# 1663496284.7790382
# 1663496284779068663

新增 dataclasses

新的 dataclass() 装饰器提供了一种声明数据类的方式。 数据类使用变量标注来描述其属性。 它的构造器和其他魔术方法例如 repr(), eq() 以及 hash() 会自动地生成。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from dataclasses import dataclass

@dataclass
class Point:
x: float
y: float
z: float = 0.0

"""
同一下代码
class Point:
def __init__(self, x: float, y: float, z: float=0.0):
self.x = x
self.y = y
self.z = z
"""

p = Point(1.5, 2.5)
print(p) # produces "Point(x=1.5, y=2.5, z=0.0)"

dict 对象正式保持插入时顺序

dict 对象会保持插入时的顺序这个特性其实在 Python 3.6 中已经非正式的出场了,现在 Python 3.7 中正式宣布成为 Python 语言官方规范的一部分。

dict 对象有了顺序,对于一些方法自然就有了影响,比如 popitem 之前是随机删除,而现在 就是删除最后加入的键值对了,有了确定性。

1
2
3
4
5
a={'a': 1,'b': 2,'c': 3}
print(a.popitem())
# ('c', 3)
print(a)
# {'a': 1, 'b': 2}

但是,按照 dict 的特性,我们在写代码的过程中依然不应该依赖 dict 有序,实际开发中还是应该按照无序处理

新增 getattr() 定制对模块属性的访问

Python 3.7 允许在模块上定义 __getattr__() 并且当以其他方式找不到某个模块属性时将会调用它。 在模块上定义 __dir__() 现在也是允许的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class User(object):
name: str
age: int
sex: int = 1

def __getattr__(self, item):
return f"Can't find {item} attribute"

user = User('stolen', 18, 2)
print(user.name)
print(user.age)
print(user.sex)
print(user.info)
"""
stolen
18
2
Can't find info attribute
"""

其他

  • async 和 await 变为了保留关键字
  • typing 不会向核心 CPython 解释器引入的限制取消了
  • 允许将超过 255 个参数传递给一个函数,而现在一个函数也可以拥有超过 255 个形参