社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python 3.10 发布了!看看有啥新特点?

凹凸数据 • 3 年前 • 335 次点击  

人生苦短,快学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可视化 | Matplotlib绘制圆环图的两种方法!


3000字长文,Pandas美化你的Excel表格!


可视化 Python打包 exe,这个神器绝了!


Python GUI | 利用Tkinter制作签名设计软件!


点击这里,阅读更多
Python
文章!
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/121342
 
335 次点击