RIIA in Python 2.5 alpha: "with... as"

Duncan Booth duncan.booth at invalid.invalid
Tue Apr 11 10:12:20 EDT 2006


Alexander Myodov wrote:

> Or maybe you have an idea how this can be fixed? The
> simplest way I see is putting all the "controlled" variables into a
> dedicated class... and do that each time for each block of variables I
> need control lifetime. Is there any simpler way?

I wouldn't use the word "fixed", but I suppose if you must you could do 
something like:

>>> import contextlib
>>> @contextlib.contextmanager
def controlled(**kw):
	class Bunch: pass
	obj = Bunch()
	obj.__dict__.update(kw)
	yield obj
	obj.__dict__ = {}

	
>>> with controlled(a=5, b=[1, 2, 3]) as k:
	print k.a, k.b, dir(k)

	
5 [1, 2, 3] ['__doc__', '__module__', 'a', 'b']
>>> print dir(k)
['__doc__', '__module__']

So the lifetime of the variable is still not limited, but the lifetime of 
its attributes is. I still don't see what that buys you though.



More information about the Python-list mailing list