python3.8,3.9,3.10,3.11特性比较

最近计划将python2迁移到python3,由于本人学习时用的3.7版本,所以仅作大于3.7版本的比较。

3.8

文档地址:python3.8

新增赋值表达式:=(海象运算符)

作用:避免重复调用,使代码更加简洁。PS:别当GO写,它不支持声明并赋值变量

import re

# 3.8
if match := re.search(r"python", "I love python! \r\n And python love me! \r\n", re.I | re.M | re.DOTALL):
    print(match.group())

# 3.7
match = re.search(r"python", "I love python! \r\n And python love me! \r\n", re.I | re.M | re.DOTALL)
if match:
    print(match.group())

仅限位置形参

作用:

  1. 新增了一个函数形参语法 / 用来指明某些函数形参必须使用仅限位置而非关键字参数的形式。
  2. /区分了前后用什么传参方式
# *号代表e,f必须用键值
# /号代表a,b必须用位置
def f(a, b, /, c, d, *, e, f):
    print(a, b, c, d, e, f)

# 合法调用
f(10, 20, 30, d=40, e=50, f=60)
# 不合法调用
f(10, b=20, c=30, d=40, e=50, f=60)   # b不能是关键词参数
f(10, 20, 30, 40, 50, f=60)           # e必须是关键字参数

3.7的老人感觉:这两个符号加上会降低代码可读性

f-字符串支持 = 用于自动记录表达式和调试文档

作用:f’{expr=}’ 的 f-字符串将扩展表示为表达式文本

author = "Generalzy"

print(f'{author=}')
# author='Generalzy'

dict 和 dictview 可以使用 reversed() 按插入顺序反向迭代

作用:python3.7开始后,python的dict就有序了,现在支持反转字典顺序

dic = {"name": "generalzy", "gender": 1, "age": "2000"}
for key, val in dic.items():
    print(key, val)
# name generalzy
# gender 1
# age 2000

print(reversed(dic))
# <dict_reversekeyiterator object at 0x00000257213E71D0>

for key in reversed(dic):
    print(key)
# age
# gender
# name

asyncio.run()更加稳定

作用:asyncio.run() 已经从暂定状态晋级为稳定 API。 此函数可被用于执行一个 coroutine 并返回结果,同时自动管理事件循环

import asyncio

async def main():
    await asyncio.sleep(0)
    return 42

asyncio.run(main())

因此 asyncio.run() 应该作为运行 asyncio 程序的首选方式。

csv.DictReader返回值改变

作用:csv.DictReader 现在将返回 dict 而不是 collections.OrderedDict,此工具现在会更快速且消耗更少内存同时仍然保留字段顺序。

multiprocessing增加进程间共享内存的方法

作用:添加了新的 multiprocessing.shared_memory 模块。

3.9

文档:python3.9

字典合并 (|)与更新运算符(|=)

作用:它们为现有的 dict.update 和 {**d1, **d2} 字典合并方法提供了补充。

>>> x = {"key1": "value1 from x", "key2": "value2 from x"}
>>> y = {"key2": "value2 from y", "key3": "value3 from y"}
>>> x | y
{'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}
>>> y | x
{'key2': 'value2 from x', 'key3': 'value3 from y', 'key1': 'value1 from x'}

增加了 str.removeprefix(prefix) 和 str.removesuffix(suffix) 用于方便地从字符串移除不需要的前缀或后缀。

作用:用于方便地从字符串移除不需要的前缀或后缀。

标准多项集中的类型标注泛型

作用:

  1. 可以使用内置多项集类型例如 list 和 dict 作为通用类型而不必从 typing 导入对应的大写形式类型名 (例如 List 和 Dict)。
  2. 标注类型更加方便了。
def greet_all(names: list[str]) -> None:
    for name in names:
        print("Hello", name)

新的解析器

Python 3.9 使用于基于 PEG 的新解析器替代 LL(1)。 新解析器的性能与旧解析器大致相当,但 PEG 在设计新语言特性时的形式化比 LL(1) 更灵活。

file 属性将是一个绝对路径,而不是相对路径。

作用:__file__在任何情况下都将是一个绝对路径

新增时区zoneinfo模块

zoneinfo 模块为标准库引入了 IANA 时区数据库。 它添加了 zoneinfo.ZoneInfo,这是一个基于系统时区数据的实体 datetime.tzinfo 实现。

>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime, timedelta

>>> # Daylight saving time
>>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
>>> print(dt)
2020-10-31 12:00:00-07:00
>>> dt.tzname()
'PDT'

>>> # Standard time
>>> dt += timedelta(days=7)
>>> print(dt)
2020-11-07 12:00:00-08:00
>>> print(dt.tzname())
PST

random新增方法生成随机字节串

增加了新的 random.Random.randbytes 方法:生成随机字节串。

3.10

文档:python3.10

带圆括号的上下文管理器

作用:允许将过长的上下文管理器集能够以与之前 import 语句类似的方式格式化为多行的形式。

with (
    CtxManager1() as example1,
    CtxManager2() as example2,
    CtxManager3() as example3,
):
    ...

更清楚的错误消息

结构化模式匹配match…case…语句

作用:类似其他语言的:switch…case…

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case 419 | 420 | 421:
        	return "我加的"
        case _:
            return "Something's wrong with the internet"

# 模式和类
class Point:
    x: int
    y: int

def location(point):
    match point:
        case Point(x=0, y=0):
            print("Origin is the point's location.")
        case Point(x=0, y=y):
            print(f"Y={y} and the point is on the y-axis.")
        case Point(x=x, y=0):
            print(f"X={x} and the point is on the x-axis.")
        case Point():
            print("The point is located somewhere else on the plane.")
        case _:
            print("Not a point")
            
# 嵌套模式:模式可以任意地嵌套。
match points:
    case []:
        print("No points in the list.")
    case [Point(0, 0)]:
        print("The origin is the only point in the list.")
    case [Point(x, y)]:
        print(f"A single point {x}, {y} is in the list.")
    case [Point(0, y1), Point(0, y2)]:
        print(f"Two points on the Y axis at {y1}, {y2} are in the list.")
    case _:
        print("Something else is found in the list.")

# 约束项:可以向一个模式添加 if 子句,称为“约束项”。 如果约束项为假值,则 match 将继续尝试下一个 case 语句块。 
match point:
    case Point(x, y) if x == y:
        print(f"The point is located on the diagonal Y=X at {x}.")
    case Point(x, y):
        print(f"Point is not on the diagonal.")

类比一下GO的:

type P struct {
	x,y int
}
func main() {
	// invalid case []int{...} in switch (can only compare slice a to nil)
	//a:=[]int{1,2}
	//switch nil{
	//case []int{1,2}:
	//	fmt.Println(a)
	//}
	
	p:=P{1,2}
	switch p {
	case P{1,2}:
		fmt.Println(p)
		// {1 2}
	}
}

新的类型联合运算符X | Y

作用:简洁标注

def square(number: int | float) -> int | float:
    return number ** 2

int 类型新增了一个方法 int.bit_count()

作用:返回给定整数的二进制展开中值为一的位数,或称“比特计量”。

现在 dict.keys(), dict.values() 和 dict.items() 所返回的视图都有一个 mapping 属性

作用:给出包装了原始字典的 types.MappingProxyType 对象。

zip() 函数有一个可选的 strict 旗标

作用:要求所有可迭代对象的长度都相等,否则异常

3.11

文档:python3.11

比上一个版本快60%

Self type

作用:标注增加self类型

class MyLock:
    def __enter__(self) -> Self:
        self.lock()
        return self

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年5月5日
下一篇 2023年5月5日

相关推荐