熱線電話:13121318867

登錄
首頁精彩閱讀絕對福音!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的功能也很重要,如果大家有興趣,請留言,點贊,后面我再專門發文介紹這兩個知識點。

最后建議:搜藏本文,認真學些這些錯誤提示。應該可以節省你很多找錯誤的時間。

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢