Monday, November 13, 2006

Be Pythonic -- 字正腔圓說 Python

學任一種語言,要說得道地,關鍵是融入語言的風格特色中,體會語言社群的風土,知道他們的慣用法。

既然 Python 寫的 code 有 executable pseudo code 的美稱,想寫出 Pythonic 的 code ,當然要站在一定的高度,讓寫出來的 code 夠 pseudo...

Pythonic 一詞被用來形容合於 Python 慣用法的 code 。Pythonic 的 code 除了讓人們更好理解外,機器執行時,也往往更具效率--語言設計者會絞盡腦汁最佳化語言慣用法的執行效率。這在 Python 這類高階、動態的語言,尤其明顯 :)

幾個 Pythonic 的準則:

  • 讓程式結構盡量扁平(flat)
  • 降低 Loops 的複雜度
    • 少用 counter ,偶爾用一下 iterator
    • 改採 Functional Programming
      • 利用 map, reduce, filter 等 functions
    • 能用 List Comprehensions 更好
  • function 是第一級物件,可以不必定義在 class 裡。
    • 如果只是要為一群公用的 function 分組,應該使用 module
    • 分類複雜時再追加使用 package
    • 需要用到多個 instance 時,才要定義 class
  • 向 getters 及 setters 說「不」
    • 以 keyword parameters 及 default parameters 取代一部分 getters/setters 的需求
    • 或者直接存取 object 的成員變數
    • 必要時,追加使用 property,而不必改到 client code
  • Duck typing 取代不必要的繼承
  • 以 tuple assignment 同時 assign 多個變數
  • 以 tuple assignment 讓 function 傳回多個值
  • Generator Function 達成 Continuation
  • 不要多次叫用 + 或 += 來串接字串
  • eval 來 parsing 字串
  • 只被單一 function 呼叫的 functions ,考慮使用 Closure
  • ……

更詳盡的說明,請參考以下的收集及摘要:

  • Be Pythonic
    • You need counters rarely, and iterators only occasionally
    • You may not need that for loop
    • Tuples are not read-only lists
    • Classes are not for grouping utility functions
    • Say no to getters and setters
    • Functions are objects
  • Python isn't Java without the compile
    • First-class functions
    • Keyword parameters
    • Default parameters
    • Tuples
    • Parallel assignment
    • Efficient multiple return values
    • Continuations
    • User-defined operators
    • Closures
    • Meta-programming
  • Python is Not Java
    • Flat is better than nested
    • Got a switch statement? The Python translation is a hash table, not a bunch of if-then statments.
    • XML is not the answer.
    • Code is easier to write than XML.
    • Getters and setters are evil.
    • Stop Writing So much code

其他相關 links:

2 comments:

York said...

Thinker 寫了一系列關於 Python 的好文。其中,〈Pythonic 的 dynamic programming〉更探討了漂亮的 decorator 用法,值得一讀。

York said...

The Zen of Python 已經有中譯了,值得好好玩味玩味。