A critic of Guido's blog on Python's lambda

Michele Simionato michele.simionato at gmail.com
Thu May 11 08:54:09 CEST 2006

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.

      Michele Simionato

More information about the Python-list mailing list