前情提要 PEP 572是python 3.8 中的一個feature (Assignment Expressions) 而這個Assignment Expressions語法在最近掀起了Python生態的腥風血雨,先說明一下這是什麼改動 首先先貼一下PEP 572當中的介紹 In most contexts where arbitrary Python expressions can be used, a named expression can appear. This is of the form NAME := expr where expr is any valid Python expression other than an unparenthesized tuple, and NAME is an identifier. 以下是範例 if (match := pattern.search(data)) is not None: # Do something with match # A loop that can't be trivially rewritten using 2-arg iter() while chunk := file.read(8192): process(chunk) # Reuse a value that's expensive to compute [y := f(x), y**2, y**3] 而這個用法並沒有限制變數的位置,如下 def foo(answer = p := 42): # INVALID ... def foo(answer=(p := 42)): # Valid, though not great style ... 所以 當然也可以這樣 def foo(answer: p := 42 = 5): # INVALID ... def foo(answer: (p := 42) = 5): # Valid, but probably never useful 開了這個洞給程式碼,一定會有非常恐怖的程式碼出現 如同以下的程式碼,我們已經可以預測未來不久就會有這種寫法誕生在各個proje...