jayessay wrote: > "Michele Simionato" <[EMAIL PROTECTED]> writes: > >> jayessay wrote: >>> I was saying that you are mistaken in that pep-0343 could be used to >>> implement dynamically scoped variables. That stands. >> Proof by counter example: >> >> from __future__ import with_statement >> import threading >> >> special = threading.local() >> >> def getvar(name): >> return getattr(special, name) >> >> def setvar(name, value): >> return setattr(special, name, value) >> >> class dynamically_scoped(object): >> def __init__(self, name, value): >> self.name = name >> self.value = value >> def __context__(self): >> return self >> def __enter__(self): >> self.orig_value = getvar(self.name) >> setvar(self.name, self.value) >> def __exit__(self, Exc, msg, tb): >> setvar(self.name, self.orig_value) >> >> if __name__ == '__main__': # test >> setvar("*x*", 1) >> print getvar("*x*") # => 1 >> with dynamically_scoped("*x*", 2): >> print getvar("*x*") # => 2 >> print getvar("*x*") # => 1 >> >> If you are not happy with this implementation, please clarify. > > I can't get this to work at all - syntax errors (presumably you must > have 2.5?, I only have 2.4). But anyway: > > This has not so much to do with WITH as relying on a special "global" > object which you must reference specially, which keeps track (more or > less) of its attribute values, which you use as "faked up" variable > Actually you probably need to hack this a bit more to even get that as > it doesn't appear to stack the values beyond a single level.
Actually there's no problem there. hint : dynamically_scoped is a class that the with statement will instantiate before (any) entry. OTOH, as it is written, I am not convinced it will work in a multithreaded setting : isn't it the case that all threads that will import eg dynamically_scoped/getvar/setvar will act without sync on the /single/ special object of the /single/ thread that initialized the module ? But I'm not sure, it's been ages since I used python threading. > > > /Jon > -- http://mail.python.org/mailman/listinfo/python-list