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:
with CleanupMagager() as cm: ... cm.register(foo) ... if cond: cm.register(bar) else: cm.register(spam) for x in y: cm.register(baz, x)
I've opened a wishlist bug for this at http://bugs.python.org/issue13585.
-- »Time flies like an arrow, fruit flies like a Banana.«
PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C