为什么我可以跳过在log_func中调用yield log_func,即我只需要编写yield,而代码仍然有效。为什么会这样呢?在这种情况下,yield是如何工作的?
import time
from contextlib import contextmanager
@contextmanager
def log_exec(log_func):
s = time.perf_counter()
yield log_func
e = time.perf_counter()
log_func(e - s)
with log_exec(log.debug):
time.sleep(1)发布于 2020-11-13 12:14:03
摘录自文档
此
iterator必须精确地包含一个值,如果有yield语句的as子句,则该值将绑定到with语句中的目标。
您没有使用as子句,因此结果没有改变。但是,如果您尝试将其与空的yield一起使用,您将看到生成的值是None。
with log_exec(debug) as log_foo:
print(log_foo)
time.sleep(1)https://stackoverflow.com/questions/64820090
复制相似问题