timmy / 使用 contextmanager 建立自訂上下文管理器
0 вподобань
0 форк(-ів)
3 файл(-ів)
Остання активність 9 months ago
contextlib.contextmanager 可用於建立自訂的 with 語句上下文管理器,適用於 資源管理(如檔案、資料庫連線、鎖定機制),確保進入與退出時執行適當的操作。
| 1 | from contextlib import contextmanager |
| 2 | |
| 3 | @contextmanager |
| 4 | def custom_context(name): |
| 5 | print(f"進入上下文: {name}") |
| 6 | try: |
| 7 | yield name # 提供資源 |
| 8 | finally: |
| 9 | print(f"退出上下文: {name}") |
timmy / 使用 icecream 進行偵錯並透過上下文管理控制輸出
0 вподобань
0 форк(-ів)
1 файл(-ів)
Остання активність 10 months ago
這段 Python 程式碼 使用 contextlib.contextmanager 來建立一個 自訂的上下文管理器 (ic_disabled()),用於 暫時停用 icecream (ic) 的輸出,並在 離開上下文後復原原始狀態。
| 1 | # 引用python內建模組contextlib中的contextmanager |
| 2 | from contextlib import contextmanager |
| 3 | |
| 4 | # 將icecream模組簡稱為ic |
| 5 | from icecream import ic # 引用icecream模組 |
| 6 | |
| 7 | # 設定icecream的輸出選項,包含上下文 |
| 8 | ic.configureOutput(includeContext=True) |
| 9 | |
| 10 | # 定義ic_disabled函式為一個上下文管理器 |
Новіше
Пізніше