On 10/21/2011 08:22 PM, Jan Kaliszewski wrote:
An improved (and at the same time simplified) implementation (being also a recipe for Python 2.x, though this list is about ideas for Py3.x):
class CleanupManager(object): def __init__(self, initial_callbacks=()): self.cleanup_callbacks = list(initial_callbacks) def register(self, callback, *args, **kwargs): self.cleanup_callbacks.append((callback, args, kwargs)) def __enter__(self): return self def __exit__(self, exc_type, exc, tb): self._next_callback() def _next_callback(self): if self.cleanup_callbacks: callback, args, kwargs = self.cleanup_callbacks.pop() try: callback(*args, **kwargs) finally: # all cleanup callbacks to be used # Py3.x: all errors to be reported self._next_callback()
I hope it implements well what you explained... I'm not sure if it is worth to be added to the standard library (in the case of your primary example I'd rather prefer that try-finally nested structure) -- though in some cases it may become really useful:
It implements almost exactly what I need. I will use it in a slightly modified form so that exceptions in the cleanup handlers are logged and discarded, so that they original exception is preserved (can't switch to Python 3 before pycryptopp becomes Py3 compatible).
Who decides if it's going into stdlib? I'm of course in favor, but I feel that my opinion may not count that much and, in addition to that, be highly biased :-).