timmy zrewidował ten Gist 10 months ago. Przejdź do rewizji
Brak zmian
timmy zrewidował ten Gist 10 months ago. Przejdź do rewizji
1 file changed, 27 insertions
ic_context.py(stworzono plik)
| @@ -0,0 +1,27 @@ | |||
| 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| "這段程式會印出": 這段程式會印出 | |
Nowsze
Starsze