[issue11647] function decorated with a context manager can only be invoked once

Nick Coghlan report at bugs.python.org
Tue Mar 29 12:30:49 CEST 2011


Nick Coghlan <ncoghlan at gmail.com> added the comment:

Part of the problem is that there was a specific reason we didn't go with lazy initialisation of the internal generator: lazy initialisation means there can be an arbitrary delay between creation of the context manager and the creation of the underlying generator that lets you know that you got the arguments wrong.

By creating the generator immediately, any exceptions are thrown at the point where the context manager is created rather than when it is used.

I think the cleanest way to fix this is to still create the generator automatically in __init__, but *also* save the original function and argument details. Then override __call__ to create a fresh instance of _GeneratorContextManager each time, instead of using "with self:" the way ContextDecorator does.

The ContextDecorator documentation should also be updated to point out that it only works with reusable context managers.

For 3.3, the fix could be generalised with ContextDecorator supporting a documented "self._recreate" internal interface that, by default, just returns self, but would be overridden in _GeneratorContextManager to actually create a new instance. The custom __call__ implementation for _GeneratorContextManager could then be removed.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue11647>
_______________________________________


More information about the Python-bugs-list mailing list