首页 文章详情

Python 3.10刚发布,这5点非常值得学习!

小詹学Python | 213 2021-10-17 07:25 0 0 0
UniSMS (合一短信)


正值国庆节期间,Python官网发布了Python3.10.0。

说实话,对于这次的升级,有几个特性,还真是值得和大家讲讲。

1. 更友好的错误提示

Python 3.10以前,它是这样提示的,你可能完全不知道哪里有问题,当代码过多。

print ("Hello"
print ("word")

  File ".\test.py", line 2
    print ("word")
    ^
SyntaxError: invalid syntax

对于Python 3.10,它是这样提示:

File ".\test.py", line 1
    print ("Hello"
          ^
SyntaxError: '(' was never closed

给你明确指示错误,太香了!

2. zip新增可选参数:严格模式

zip新增可选参数strict, 当该选项为True时,传入zip的两个可迭代项长度必须相等,否则将抛出 ValueError。

对于Python 3.10以前,没有该参数,当二者长度不等时,以长度较小的为准。

names = ["a","b","c","d"]
numbers = [1,2,3]
z = zip(names,numbers)
for each in z:
    print(each)

结果如下:对于Python 3.10,设置strict为True。

d:测试.py in <module>
      3 numbers = [1,2,3]
      4 z = zip(names,numbers,strict=True)
----> 5 for each in z:
      6     print(each)

ValueError: zip() argument 2 is shorter than argument 1

3. with可以加括号

官方文档中是这样写的:

with (CtxManager() as example):
    ...

with (
    CtxManager1(),
    CtxManager2()
):
    ...

with (CtxManager1() as example,
      CtxManager2()):
    ...

with (CtxManager1(),
      CtxManager2() as example):
    ...

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

这样你一定看不懂,如果换成下面这种写法呢?

with(
    p1.open(encoding="utf-8") as f1,
    p2.open(encoding="utf-8") as f2
):
    print(f1.read(), f2.read(), sep="\n"

就是你现在可以一次性在with中,操作多个文档了。

4. 结构化模式匹配:match...case...

对,就是其他语言早就支持的的switch-case,Python今天终于提供了支持。

day = 7
match day:
    case 3:
        print("周三")
    case 6 | 7:
        print("周末")
    case _ : 
        print("其它")

5. 新型联合运算符

以 X|Y 的形式引入了新的类型联合运算符。

def square(x: int|float)
    return x ** 2

square(2.5) 
# 结果:6.25

新的运算符,也可用作 isinstance() 和 issubclass() 的第二个参数。

True
isinstance("a"int|str)

# True 
issubclass(str, str|int)

推荐阅读


牛逼!Python常用数据类型的基本操作(长文系列第①篇)

牛逼!Python的判断、循环和各种表达式(长文系列第②篇)

牛逼!Python函数和文件操作(长文系列第③篇)

牛逼!Python错误、异常和模块(长文系列第④篇)


good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter