善用 lru_cache 對設定檔進行 cache
python 3 原生提供了一個簡易的 cache decorator 叫 lru_cache,可以把耗時的函數執行結果儲存起來,一段時間就刪掉
舉例來說下面這段 code
@lru_cache()
def say_hi(name: str):
return f'Hello {name}'
的循序圖大概長這樣
sequenceDiagram
code->>say_hi(): say_hi(name='test')
say_hi()->>func: exec
func-->>code: result
code->>say_hi(): say_hi(name='test')
say_hi()-->>code: result
code->>say_hi(): say_hi(name='tom')
say_hi()->>func: exec
func-->>code: result
code->>say_hi(): say_hi(name='tom')
say_hi()-->>code: result
code->>say_hi(): say_hi(name='test')
say_hi()-->>code: result
搭配 magic method 可以對設定的東西做到簡單的 cache 功能
發佈時間
2020-12-16