Subclassed dict as globals
Lenard Lindstrom
len-1 at telus.net
Wed Jan 26 17:27:02 EST 2005
Evan Simpson <evan at tokenexchange.com> writes:
> 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
> >>>
>
[snip]
> [Is] there a way to do this (intercept global variable accesses)
> in Python 2.3?
>
One can emulate it in a rather limited way in pre 2.4 releases:
>>> cd = compile("print x, y, z", '<string>', 'exec')
>>> glbs = dict(globals())
>>> for id in cd.co_names:
glbs[id] = 'K' + id
>>> exec cd in glbs
Kx Ky Kz
Special names can be used only as constants. It is better suited
for eval() than exec.
Lenard Lindstrom
<len-l at telus.net>
More information about the Python-list
mailing list