Replacing globals in exec by custom class

Jonathan S jonathan.slenders at gmail.com
Wed Dec 8 08:01:04 EST 2010


Hi all,

I wonder if anyone can explain some weird behaviour in Python.
What I'm trying to do is to execute a string of python code through
the 'exec' statement. I pass an instance of my Global class, which
acts like a dict. By overriding the __getitem__ method, the Global
should pretend that a global variable, named 'xx' does exist.

This does work for the outermost scope in the executed code, but
inside the nested function, 'q', the Global instance seems never to be
accessed, 'xx' is not found, while the globals() built-in still
returns the custom Global instance.

According to python's executing model [1], the interpreter is supposed
to look into globals(), if a variable has not been assigned in the
inner scope. What am I missing here?

[1] http://docs.python.org/reference/executionmodel.html


{{{
class Global(dict):
    def __init__(self):
        pass
    def __getitem__(self, key):
        import __builtin__
        if key == 'xx':
            return 'xx'

        if hasattr(__builtin__, key):
            return getattr(__builtin__, key)

        else key in self.__dict__:
            return self.__dict__[key]

    def __setitem__(self, key, value):
        self.__dict__[key] = value

    def __str__(self):
        return ' <globals> ' + unicode(self.__dict__)


code="""
print globals()
print xx  # Does work, prints 'xx'

def q():
    print globals().__getitem__('xx') # Does work, prints 'xx'
    print globals()['xx']  # Does work, prints 'xx'
    print xx # Does not work, cannot find xx
q()
"""
g = Global()

exec(compile(code, 'my code', 'exec'), g, g)
}}}







More information about the Python-list mailing list