Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context manager as a decorator with access to the yielded object

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.

like image 583
MrBean Bremen Avatar asked Sep 16 '25 18:09

MrBean Bremen


1 Answers

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 explicit with statement.

like image 77
chepner Avatar answered Sep 19 '25 07:09

chepner