登录
首页精彩阅读绝对福音!Python3.10的这项改进太棒了,治好了我眼睛
绝对福音!Python3.10的这项改进太棒了,治好了我眼睛
2021-06-10
收藏

来源:麦叔编程

作者:麦叔

一、Python 3.10

2021年6月9号,Python官方发布了3.10的新功能介绍。

绝对福音!Python3.10的这项改进太棒了,治好了我眼睛

以往每次有新的版本,我都替Python开发者叫苦:又有新的版本,又要学新的东西,又要修改程序,命苦啊!

但这次看了以后,我禁不住连声叫好:这个太棒了!福音!

二、主要功能改进

先简单说一下3.10的几项核心改进:

1. 在with ... as语法中支持小括号,可以一行创建多个环境管理器。

with (
    CtxManager1() as example1,
    CtxManager2() as example2,
    CtxManager3() as example3,
):

关于环境管理器,后面可以单独发文讨论细节。

2. 更好的错误提示

这就是让我连连叫好的功能,这也是本文后面讨论的重点。

3. 支持match ... case功能,也就是其他编程语言的swith ... case:

    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" 

这个后面可以单独发文讨论细节。

4. 其他功能

还有一些其他小的功能改进:

  • 跟踪调试中提供更准确可靠的行数
  • 几个关于类型(type hint)的改进,比如支持类型的union操作:X | Y表示类型X或者Y
  • asyncio, base64等几十个模块有一些细小的改动
  • 其他的一些细小的语言改动,比如int加了一个新的方法int.bit_count()

这些细节基本不会影响你现有的代码,有兴趣的同学可以点本文的阅读原文,查看完整的英文原文。

三、更好的错误提示

让我拍手叫绝的这个功能就是更好的错误提示

编程学习者,尤其是新手,会碰到各种各样的编程错误,

而这些错误的提示又不友好,甚至有些误导

错误就在我们面前,我们瞪着眼睛却看不见,这种情况我称为眼瞎问题

就算我这样的老司机,也时不时的会碰到瞎眼问题。

3.10对错误提示有了很大的改进,可以说在一定程度上能挽救我们眼瞎问题

这个改进涵盖了:语法错误,缩进错误,属性错误,名称错误等。

我们一个个看,建议先肉眼看一下,错误在哪里,我们来一个找错误游戏。

1. 语法错误

代码1:

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() 

以前的错误提示:

有语法错误。还把错误的行数说错了,这个就很误导了!

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

现在的提示要好多了:

大括号没有关闭。这个就很自白了!

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 

代码2:

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

这段代码是因为z for z in range(10)应该加上括号,提示也还比较正常。

但是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.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
  • 字典少了value
>>> values = {
... x: 1,
... y: 2,
... z: ... }
  File "<stdin>", line 4     z:      ^ SyntaxError: expression expected after dictionary key and ':' >>> values = {x:1y:2, z w:3}
  File "<stdin>", line 1     values = {x:1y:2, z w:3}
                        ^ SyntaxError: ':' expected after dictionary key
  • try少了except或者finally
>>> try ...     x = 2 ... something = 3   File "<stdin>", line 3     something  = 3     ^^^^^^^^^ SyntaxError: expected 'except' or 'finally' block
  • 比较的时候用了=,而不是==。这个太赞了!
>>> if rocket.position = event_horizon:   File "<stdin>", line 1     if rocket.position = event_horizon:                        ^ SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?
  • 在f-string中用了星号*
>>> f"Black holes {*all_black_holes} and revelations"   File "<stdin>", line 1     (*all_black_holes)
     ^ SyntaxError: f-string: cannot use starred expression here

2. 缩进错误

缩进错误是小白常见错误,现在有救啦,提示很友好:

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

3. 属性错误

用错了属性,不光告诉你错误,还给你一些可能的选择,简直有点人工智能的味道了。

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

4. 命名错误

同样的,命名错误也会给出一个可能的选择:

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

四、结束语

这是python 3.10中最让我眼睛一亮的一项功能,相信可以解救很多和我一样有瞎眼问题的同学。

Python 3.10的match..case功能也可以算是一大改进,另外context manager的功能也很重要,如果大家有兴趣,请留言,点赞,后面我再专门发文介绍这两个知识点。

最后建议:搜藏本文,认真学些这些错误提示。应该可以节省你很多找错误的时间。

数据分析咨询请扫描二维码

客服在线
立即咨询