Python 程式設計 - 中階

使用 Python typing 模組對你的同事好一點

由於 Python 動態型別(執行階段可以任意改變變數的型別)的特性,所以很多時候開發者們都會透過變數的命名讓他人知道該變數的型別,例如:

dicts = [{"key": "value"}, {"key": "values"}]

複數型的 dicts 命名讓其他人在閱讀時能夠大致猜到它可能是個字典(dict)的列表(list)。

但是現代專案不可能經常是如此簡單的結構,有時光從命名仍難以了解是什麼型別的變數,例如:

def get_value(json):
     return parse(json)

當我們看到上述函式中的 json 時,就會疑惑它是什麼? str? dict? 而回傳的值到底長怎樣,有什麼 key 可以使用?也由於這種不確定性,所以在除錯甚至協同開發時都需要實際執行才能夠知道該變數到底是什麼型態,在複雜的大型專案中甚至會成為一種痛苦。

p.s. Javascript 也有相同的痛點,所以才有 TypeScript 問世

這種情況,我們除了用心命名之外,還可以搭配使用 typing 模組來改善!

Last updated on  Sep 24, 2023  in  Python 程式設計 - 中階  by  Amo Chen  ‐ 6 min read

Python daemon thread 解說

閱讀 Python Threading 文件時,關於 Thread Objects 中有提到 Daemon Thread

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left.

單看說明其實還不是特別清楚,可以用個範例實際幫助理解。

Last updated on  Sep 8, 2023  in  Python 程式設計 - 中階  by  Amo Chen  ‐ 2 min read

Python - 製作 JSON serializable 的類別

Python 的 json 模組十分方便,可以把 dict() tuple() list() str() int() 等資料型別轉成 JSON 字串,不過遇到像是 set() 時,就會產生以下錯誤:

>>> import json
>>> json.dumps(set())
...(略)...
TypeError: Object of type 'set' is not JSON serializable

原因在於 json.dumps() 中預設並沒有處理 set() 等型別的序列化( serialization )。

雖然如此, json.dumps() 還是有參數能夠處理這些無法被序列化的類別(class)或型別。

Posted on  Mar 29, 2018  in  Python 程式設計 - 中階  by  Amo Chen  ‐ 2 min read

Python threading event objects 溝通範例教學

The simplest mechanisms for communication between threads: one thread signals an event and other threads wait for it.

Threads(執行緒)之間溝通最簡單的方式,即是透過 Event Objects ,這種方式通常應用在 1 個 thread 發起 1 個 event ,然後其他 threads 會等待發出 event 的 thread ,譬如 1 個發號施令的 thread ,其他 threads 會等待該 thread 發號施令後才開始工作。

Last updated on  Jul 24, 2023  in  Python 程式設計 - 中階  by  Amo Chen  ‐ 2 min read