Why can I skip calling log_func in yield log_func, i.e. I can just write yield and the code still works. Why is that? How does yield work in this case?
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)
Excerpt from the documentation:
This
iteratormustyieldexactly one value, which will be bound to the targets in thewithstatement’sasclause, if any.
You are not using as clause, therefore the outcome is unchanged. But if you try to use it with an empty yield, you will see that the yielded value is None.
with log_exec(debug) as log_foo:
print(log_foo)
time.sleep(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With