I would like to second the improved explanation of contextlib.contextmanager, and additionally point out another problem:
A very important piece of information is missing from the documentation: how to return data from the contextmanager-wrapped function.
I had to go look up the source code, which had a wonderful explanation in the comments: https://gist.github.com/enuomi/1385336#file-contextlib-py-L56
In particular, note that
@contextmanager
def some_generator(<arguments>):
yield <return_data>
can be used to return <return_data> to the caller, via
with some_generator(<arguments>) as <return_data>:
print(return_data)
This information is wholly and completely missing from the contextlib.contextmanager documentation. |