Subclassed dict as globals

Fredrik Lundh fredrik at
Wed Jan 26 12:48:28 EST 2005

Evan Simpson wrote:

> In Python 2.4 the following works:
> >>> class G(dict):
> ...   def __getitem__(self, k):
> ...     return 'K' + k
> ...
> >>> g = G()
> >>> exec 'print x, y, z' in g
> Kx Ky Kz
> >>>
> ...while in Python 2.3 it fails with NameError: name 'x' is not defined. Is this an "accidental 
> feature", or can I count on this working in future versions of Python?

it's an official addition, and it's at least to safe for it to be in all future
versions of CPython 2.X.

    The eval(expr, globals, locals) and execfile(filename, globals,
    locals) functions and the exec statement now accept any mapping type for
    the locals parameter. Previously this had to be a regular Python dictionary.
    (Contributed by Raymond Hettinger.)

I don't think he added this purely by accident, but it might have been a side
effect of some other optimization. ;-)

> For that matter, is there a way to do this  (intercept global variable accesses)
> in Python 2.3?

not that I'm aware of...


More information about the Python-list mailing list