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

Python实用宝典

共 1939字,需浏览 4分钟

 · 2021-10-18

人生苦短,快学Python!

正值国庆节期间,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实用宝典 (pythondict.com)
不只是一个宝典
欢迎关注公众号:Python实用宝典

浏览 31
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报