Replacing globals in exec by custom class

Terry Reedy tjreedy at udel.edu
Wed Dec 8 15:00:12 EST 2010


On 12/8/2010 8:01 AM, Jonathan S wrote:

> 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]

syntax error

>      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)
> }}}

When asking such questions, paste both the actual code that compiled and 
ran and the actual traceback you got in response.

-- 
Terry Jan Reedy




More information about the Python-list mailing list