ic_context.py
· 898 B · Python
Bruto
# 引用python內建模組contextlib中的contextmanager
from contextlib import contextmanager
# 將icecream模組簡稱為ic
from icecream import ic # 引用icecream模組
# 設定icecream的輸出選項,包含上下文
ic.configureOutput(includeContext=True)
# 定義ic_disabled函式為一個上下文管理器
@contextmanager
def ic_disabled():
# 將ic.enabled的原始值存入_enabled
_enabled = ic.enabled
# 將ic.enabled設為False,關閉ic()的輸出
ic.enabled = False
# 使用yield來暫時執行代碼區塊內的程式
yield
# 離開代碼區塊後,將ic.enabled恢復原始值
ic.enabled = _enabled
ic(42) # 會輸出: ic| 42: 42
with ic_disabled():
ic("這段程式不會印出") # `ic()` 被停用,不會顯示輸出
ic("這段程式會印出") # `ic()` 被恢復,會輸出: 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函式為一個上下文管理器 |
| 11 | @contextmanager |
| 12 | def ic_disabled(): |
| 13 | # 將ic.enabled的原始值存入_enabled |
| 14 | _enabled = ic.enabled |
| 15 | # 將ic.enabled設為False,關閉ic()的輸出 |
| 16 | ic.enabled = False |
| 17 | # 使用yield來暫時執行代碼區塊內的程式 |
| 18 | yield |
| 19 | # 離開代碼區塊後,將ic.enabled恢復原始值 |
| 20 | ic.enabled = _enabled |
| 21 | |
| 22 | ic(42) # 會輸出: ic| 42: 42 |
| 23 | |
| 24 | with ic_disabled(): |
| 25 | ic("這段程式不會印出") # `ic()` 被停用,不會顯示輸出 |
| 26 | |
| 27 | ic("這段程式會印出") # `ic()` 被恢復,會輸出: ic| "這段程式會印出": 這段程式會印出 |
| 28 |