str.format(**locals()) 將當前區域變數字典解包為關鍵字參數,讓格式化字串直接引用變數名,避免重複輸入。
結論:現代 Python (3.6+) 應優先使用 f-string;**locals() 技巧適用於:
| 風險 | 說明 | 緩解 |
|---|---|---|
| 區域變數汙染 | locals() 包含所有區域變數,模板可能誤用內部變數 | 傳遞顯式字典 dict(name=name, age=age) 或 {k:v for k,v in locals().items() if k in allowed} |
| 效能 | 建立字典、解包有額外開銷 | 熱路徑改用 f-string 或預編譯 string.Template |
| 安全性 | 使用者提供模板可能存取敏感變數 | 使用 string.Template (安全、不執行代碼) 或沙箱環境 |
string.Template 安全替代方案**locals() 是 Python 2/早期 3 時代的實用技巧。str.format(**context) 或 string.Template。