File "example.py", line 1 expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4, ^ SyntaxError: '{' was never closed
类似地,还有推导式中如果忘记加圆括号时,之前一言不合直接提示语法错误
>>> {x,y for x,y in zip('abcd', '1234')} File "", line 1 {x,y for x,y in zip('abcd', '1234')} ^ SyntaxError: invalid syntax
而现在会告诉你,是不是忘记加圆括号了。
>>> {x,y for x,y in zip('abcd', '1234')} File "", line 1 {x,y for x,y in zip('abcd', '1234')} ^ SyntaxError: did you forget parentheses around the comprehension target?
嗯,这才人性化。
2、match ... case 终于来了
match ... case 语法是我比较期待的功能,它不是什么多高级的功能,类似于其它语言中的 switch ... case 语法,在多条件判断时比用 if ... elif 代码更简洁。很难想象,这个语法现在才加进来,当然, 一开始Python之父是不愿意加这个语法特性的,好在这个语法最终还是回归了,而且换了个名字。
我在想,干嘛和自己过不去,统一都叫 switch ... case 不好吗?也许这就是Python让人着迷的地方吧。
来看个例子
这是用3.10的 match case 语法
defhttp_error(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 _ 类似于其它语言中的 default ,当其他条件都不符合就执行这行。
用普通的if ... else 语法来写
defhttp_error(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"
3、支持括号的上下文管理器
在之前的老版本中,多个上下文管理器必须放在一行或者用转义符“\”换行
with open("xxx.py", mode="w") as f1, open("yyy.py", mode="w") as f2: pass
# 或者
with open("xxx.py", mode="w") as f1, \ open("yyy.py", mode="w") as f2: pass
在3.10中,我们可以用括号将多个管理器放在多行,这样代码看起来整洁一些。
with ( open("xxx.py", mode="w") as f1, open("yyy.py", mode="w") as f2 ): pass