Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yield in contextlib.contextmanager

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)
like image 994
user270199 Avatar asked Dec 10 '25 11:12

user270199


1 Answers

Excerpt from the documentation:

This iterator must yield exactly one value, which will be bound to the targets in the with statement’s as clause, 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)
like image 158
alex_noname Avatar answered Dec 12 '25 01:12

alex_noname



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!