看看Python 官网的文档 whatsnew,Python 3.10 已然距离我们越来越近了,然我们看看 Python 3.10 相较于 Python 3.9 有哪些改变吧

新特性

通过括号来组织多个上下文管理器

**的福音,以前在面对有多个上下文管理器时,我们只能采取多层嵌套的方式,像这样:

with open("read.txt", "r") as rfile:
with open("write.txt", "w") as wfile:
wfile.write(rfile.read())

会不会变成这样,[捂脸][捂脸][捂脸]

那在 Python3.10 中,我们可以这样写了:

with (
open("read.txt", "r") as rfile,
open("write.txt", "w") as wfile
):
wfile.write(rfile.read())

更加友好的错误信息

语法错误

  1. 对于代码中未闭合括号或引号造成的语法错误,解释器可以提供具体出错的开头位置

比如下面这段错误代码(是因为大括号没有闭合):

# filename: syntax_error_1.py
expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6,
some_other_code = foo()

Python 3.9 版本运行的报错信息,很难定位到错误原因:

> C:\Users\zioyi\.pyenv\pyenv-win\versions\3.9.6\python.exe syntax_error_1.py
File "C:\Users\zioyi\python_code\syntax_error_1.py", line 3
some_other_code = foo()
^
SyntaxError: invalid syntax

再来看看 Python 3.10 的报错信息,就显得贴心很多了:

> C:\Users\zioyi\.pyenv\pyenv-win\versions\3.10.0b4\python.exe syntax_error_1.py
File "C:\Users\zioyi\python_code\syntax_error_1.py", line 1
expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
^
SyntaxError: '{' was never closed
  1. 对于语法错误,解释器将高亮显示构成语法错误代码的完整错误范围

先看一下 Python 3.9:

>>> foo(x, z for z in range(10), t, w)
File "<stdin>", line 1
foo(x, z for z in range(10), t, w)
^
SyntaxError: Generator expression must be parenthesized

再看一下 Python 3.10:

>>> foo(x, z for z in range(10), t, w)
File "<stdin>", line 1
foo(x, z for z in range(10), t, w)
^^^^^^^^^^^^^^^^^^^^
SyntaxError: Generator expression must be parenthesized

原来,^^^^^^^^^^^这就是高亮

3. 错误信息变得更加智能,不再只是无情的才裁判,只会返回SyntaxError: invalid syntax,更像是一位循循善诱的老师

来看看当我们写错时,老师(Pyhton 3.10) 是怎么引导我们的

>>> # 条件语句忘记加冒号
>>> if rocket.position > event_horizon
File "<stdin>", line 1
if rocket.position > event_horizon
^
SyntaxError: expected ':' >>> # 解包元组时没写括号
>>> {x,y for x,y in zip('abcd', '1234')}
File "<stdin>", line 1
{x,y for x,y in zip('abcd', '1234')}
^
SyntaxError: did you forget parentheses around the comprehension target? >>> # 构造字典时,两个元素之间没加逗号
>>> items = {
... x: 1,
... y: 2
... z: 3,
File "<stdin>", line 3
y: 2
^
SyntaxError: invalid syntax. Perhaps you forgot a comma? >>> # 准备补货多个异常,却少写了括号
>>> try:
... build_dyson_sphere()
... except NotEnoughScienceError, NotEnoughResourcesError:
File "<stdin>", line 3
except NotEnoughScienceError, NotEnoughResourcesError:
^
SyntaxError: multiple exception types must be parenthesized

缩进错误 IndentationErrors

现在缩进错误会有更多关于期望缩进的块类型的上下文信息,包括语句的位置:

>>> def foo():
... if lel:
... x = 2
File "<stdin>", line 3
x = 2
^
IndentationError: expected an indented block after 'if' statement in line 2

属性错误 AttributeErrors

当出现熟悉错误时,PyErr_Display函数会猜你喜欢,打印出你可能要的属性:

>>> collections.namedtoplo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'collections' has no attribute 'namedtoplo'. Did you mean: namedtuple?

命名错误 NameErrors

和属性错误一样,当出现命名错误时,PyErr_Display函数会猜你喜欢,打印出你可能要的变量名:

>>> schwarzschild_black_hole = None
>>> schwarschild_black_hole
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'schwarschild_black_hole' is not defined. Did you mean: schwarzschild_black_hole?

PyErr_Display真是一个懂事的函数

switch-casematch-case终于来了

别人(Java、Golang、C)有的,你(Pyhton)也会有的,而且只会更好!

响应全网呼声,Python 版switch-case,即match-case也终于来了,这个特性也是 Python 3.10 中最受瞩目的特性

语法

Python 版的switch-case,你要按照这个格式去写:

match subject:
case <pattern_1>:
<action_1>
case <pattern_2>:
<action_2>
case <pattern_3>:
<action_3>
case _:
<action_wildcard>

简单匹配

在没有match-case之前,我们是这样写的:

def http_error_if_else(status):
if status == 400:
return "Bad request"
elif status == 404:
return "Not found"
elif status == 418:
return "I'm a teapot"
else:
return "Something's wrong with the internet"
# 或者这样
def http_error_dict(status):
http_status_to_error = {
400: "Bad request",
404: "Not found",
418: "I'm a teapot"
}
return http_status_to_error.get(status, "Something's wrong with the internet")

虽然可以解决问题,但我们知道if-else在性能上和易读性上都没有switch-case好用

再看看 Python 3.10 里,我们就可以这样写了:

def http_error_match_case(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"

这就变得简单了许多

你还可以在case后面用使用|来串联多个,像这样:

case 401 | 403 | 404:
return "Not allowed"

如果不在case语句中使用_兜底,则可能不存在匹配项。如果不存在匹配项,则行为为空操作。例如,如果状态500被传递,则会发生空操作。

同时匹配变量和常量

在进行匹配时,会按照case后的patternsubject尝试进行转换,来绑定pattern中的变量,.在这个例子中,一个数据点可以解包到它的 x 坐标和 y 坐标:

# point is an (x, y) tuple
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a point")

Python 3.10 is coming!的更多相关文章

  1. 八月暑期福利,10本Python热门书籍免费送!

    八月第一周,网易云社区联合博文视点为大家带来Python专场送书福利,10本关于Python的书籍内容涉及Python入门.绝技.开发.数据分析.深度学习.量化投资等.以下为书籍简介,送书福利请见文末 ...

  2. Python 3.10 正式发布,新增模式匹配,同事用了直呼真香!

    关注微信公众号:K哥爬虫,QQ交流群:808574309,持续分享爬虫进阶.JS/安卓逆向等技术干货! 前几天,也就是 10 月 4 日,Python 发布了 3.10.0 版本,什么?3.9 之后居 ...

  3. Python 3.10 版本采纳了首个 PEP,中文翻译即将推出

    现在距离 Python 3.9.0 的最终版本还有 3 个月,官方公布的时间线是: 3.9.0 beta 4: Monday, 2020-06-29 3.9.0 beta 5: Monday, 202 ...

  4. Python 3.10 明年发布,看看都有哪些新特性?

    我们目前生活在Python 3.8的稳定时代,上周发布了Python的最新稳定版本3.8.4.Python 3.9已经处于其开发的beta阶段,并且2020年7月3日预发布了beta版本(3.9.0b ...

  5. Python 3.10 中新的功能和变化

    随着最后一个alpha版发布,Python 3.10 的功能更改全面敲定! 现在,正是体验Python 3.10 新功能的理想时间!正如标题所言,本文将给大家分享Python 3.10中所有重要的功能 ...

  6. 利用Conda尝鲜Python 3.10

    1 简介 就在几天前,Python3.10的第一个正式版本3.10.0发布,之前我们只是从其各个测试版本中捕风捉影地知晓了一些可能加入的新特性,而在正式版本中,我们得以一睹其正式加入的诸多新特性. 本 ...

  7. Python多个版本安装!

    Python可以同时安装多个版本,目前我安装的是3.6和3.5,在Eclipse中使用3.6:在Visual Studio中使用3.5.如何让哪个版本的Python成为系统默认的解释器呢?通过调整不同 ...

  8. 6个顶级Python NLP库的比较!

    6个顶级Python NLP库的比较! http://blog.itpub.net/31509949/viewspace-2212320/ 自然语言处理(NLP)如今越来越流行,在深度学习开发的背景下 ...

  9. [TPYBoard - Micropython之会python就能做硬件 开篇]会python就能做硬件!

    转载请注明:@小五义http://www.cnblogs.com/xiaowuyiQQ群:64770604 会python就能做硬件! 在写这套教程之前,首先感觉山东萝卜电子科技有限公司(turnip ...

随机推荐

  1. 微信小程序云开发-数据库-删除数据

    一.js文件使用.remove()删除单条数据 在js文件中写updategood函数,在函数中使用.doc()指定要删除的数据id,调用.remove()方法删除数据. 二.wxml文件添加[删除] ...

  2. R在ubuntu16.04上环境搭建

    1.R安装 sudo apt-get update sudo apt-get remove vim-common sudo apt-get install vimapt-cache show r-ba ...

  3. mongo-express 远程代码执行漏洞(CVE-2019-10758)

    影响版本 mongo-express 0.53.0 POST /checkValid HTTP/1.1 Host: 192.168.49.2:8081 Accept-Encoding: gzip, d ...

  4. 🔥 LeetCode 热题 HOT 100(71-80)

    253. 会议室 II(NO) 279. 完全平方数 class Solution { public int numSquares(int n) { // dp[i] : 组成和为 i 的最少完全平方 ...

  5. 题解 P6688 可重集

    己所欲者,杀而夺之,亦同天赐 解题思路 一定不要用自动溢出的 Hash!!!!!!! 我真的是调吐了... 思路非常简单明了 : 需要我们创新一下 Hash. 首先我们的 Hash 要满足无序性.. ...

  6. UI_UE在线就业班(2)(Adobe Illustrator软件学习)

    Adobe Illustrator软件的使用     认识AIUI_UE在线就业班(2) .   ▼ AI是Adobe Illustrator的英文缩写,是Adobe公司旗下推出的一款基于矢量图形制作 ...

  7. rsa加密初探

    RSA加密算法初探 RSA加密算法是早期的非对称加密,公钥和私钥分离,公开公钥,通过确保私钥的安全来保证加密内容的安全.由麻省理工学院的罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi ...

  8. i春秋-Phone number(union注入+hex转码)

    记一道union注入语句转十六进制的注入题. 这个网站的基本功能就是可以找出跟你用户名相同的注册的人数. 注册登录给了两个显位. 点击check可以显示出有多少人和你用户名相同. 同时在这个页面的源代 ...

  9. 内置函数 strlen

    1 //内置函数 strlen 2 //计算字符串的实际长度,不含字符串结束标准\0 3 4 #include<stdio.h> 5 #include<stdlib.h> 6 ...

  10. 树莓派SG90舵机接法

    我的舵机的三条线是红的.黑色.棕色,接法如下: 棕 : GND 红 : VCC 黄: 信号线 如图所示: 图片来源 如上图所示,写代码时注意舵机的BCM编码是18,而不是物理引脚的编码12.