Python 3.10正式版发布

1,187 阅读3分钟

Python在几天前发布了正式版3.10,虽然你不一定会马上应用到生产环境,不过还是建议有条件的可以升级体验以下,没条件直接看我这篇文章就可以了,我列了几个开发者可能比较感兴趣的特性,看看哪个是你最期待的特性。

1、更友好的错误提示

expected = {91182192273283293364374,
            38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6,
some_other_code = foo()

比如这段代码如果你不小心漏掉一个右花括号,运行代码时,在之前的版本中直接提示语法错误:

File "example.py", line 3
    some_other_code = foo()
                    ^
SyntaxError: invalid syntax

不仔细检查代码你还真的没法一眼看出来到底哪里语法错误。而在python3.10中,提示变得非常友好而且具体, 直接告诉你 "{"没有关闭,这样定位错误就很快了。

File "example.py", line 1
    expected = {91182192273283293364374,
               ^
SyntaxError: '{' was never closed

类似地,还有推导式中如果忘记加圆括号时,之前一言不合直接提示语法错误

>>> {x,y for x,y in zip('abcd''1234')}
  File "<stdin>", line 1
    {x,y for x,y in zip('abcd''1234')}
         ^
SyntaxError: invalid syntax

而现在会告诉你,是不是忘记加圆括号了。

>>> {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?

嗯,这才人性化。

2、match ... case  终于来了

match ... case 语法是我比较期待的功能,它不是什么多高级的功能,类似于其它语言中的 switch ... case 语法,在多条件判断时比用 if ... elif 代码更简洁。很难想象,这个语法现在才加进来,当然, 一开始Python之父是不愿意加这个语法特性的,好在这个语法最终还是回归了,而且换了个名字。

我在想,干嘛和自己过不去,统一都叫 switch ... case 不好吗?也许这就是Python让人着迷的地方吧。

来看个例子

这是用3.10的 match case 语法

def http_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 语法来写

def http_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

4、新的类型联合操作符

在之前版本中,对于函数参数如果希望类型支持多种,例如同时支持int和float,需要用Union:

from typing import Union


def foo(number: Unionintfloat]) -> Union[intfloat]:
    return number ** 2

现在有个新的语法糖“|”,叫联合操作符,可以让代码更简洁

def square(number: int | float) -> int | float:
    return number ** 2

该操作符在函数 isinstance()和 issubclass() 也可以支持

# python3.10
>>> isinstance(1int | str)
True

# python3.7
>>> isinstance(1, (int,float))
True

最后

当开发者问到Python是否还会有Python4.0的时候,Python之父直言不要对 Python 4.0 抱有希望。假如真的哪天发布了Python4.0,也不会重走2.x过度到3.0的老路。同时,我们也别指望Python的GIL能够去掉,不是没尝试过,而是去掉GIL之后更慢了。如果你的项目对性能非常敏感,不妨试试pypy,python的一个分支。

本文同步发表博客:foofish.net

欢迎关注公众号

https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/216a486abacf4924b743a65f804af491~tplv-k3u1fbpfcp-zoom-1.image