python with contextmanager yield 语法糖
生活随笔
收集整理的這篇文章主要介紹了
python with contextmanager yield 语法糖
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
官方示例
https://docs.python.org/zh-cn/3.8/library/contextlib.html
說實話,沒看出來有多方便。我這寫了兩個功能相同的程序,一個用語法糖,一個用常規(guī)寫法:
語法糖寫法
import contextlibmsg_queue = []@contextlib.contextmanager def msg_manager(msg):if msg:print(msg, "添加到消息隊列")msg_queue.append(msg)try:print("yield...")yield Nonefinally:if msg:print(msg, "彈出消息隊列")msg_queue.pop()with msg_manager("mouse_event"):print("分發(fā)事件")mouse_event 添加到消息隊列
yield…
分發(fā)事件
mouse_event 彈出消息隊列
正常人類的做法
msg_queue = []def msg_append(msg):if msg:print(msg, "添加到消息隊列")msg_queue.append(msg)def msg_pop(msg):if msg:print(msg, "彈出消息隊列")msg_queue.pop() msg_append("mouse_event") print("分發(fā)事件") msg_pop("mouse_event")mouse_event 添加到消息隊列
分發(fā)事件
mouse_event 彈出消息隊列
總結
只要寫出同事看不懂的代碼,就能保住工作了對吧
總結
以上是生活随笔為你收集整理的python with contextmanager yield 语法糖的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cve-bin-tool 证书错误的解决
- 下一篇: 通过句柄找到广告弹窗进程