I have a context manager for an object that can be used similar to the open
context manager, e.g.
with MyContextManager as cm:
cm.do_something()
I know that a simple context manager can be made into a decorator if using contextlib.ContextDecorator
to create it. Is it also possible to access the object yielded from the context manager if using a decorator? E.g. given the context manager above, something like:
@cmdecorator
def my_function(self, cm):
cm.do_something
I couldn't get that to work. Either I'm missing something trivial (hope so), or this is just not possible... It is only syntactic sugar in the end, but I'm interested if it is possible.
No. This is explicitly mentioned in the documentation.
Note that there is one additional limitation when using context managers as function decorators: there’s no way to access the return value of
__enter__()
. If that value is needed, then it is still necessary to use an explicitwith
statement.
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