Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Subclassed dict as globals

Reply
Thread Tools

Subclassed dict as globals

 
 
Evan Simpson
Guest
Posts: n/a
 
      01-26-2005
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? For that matter, is there a way to do this
(intercept global variable accesses) in Python 2.3?

Cheers,

Evan @ 4-am

 
Reply With Quote
 
 
 
 
Lenard Lindstrom
Guest
Posts: n/a
 
      01-26-2005
Evan Simpson <(E-Mail Removed)> 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
<(E-Mail Removed)>
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
what are the other ways to prevent a class from being subclassed. one way is to declare the class final. srinivas.veeranki@gmail.com Java 20 02-17-2006 12:21 AM
Subclassed ClassLoader problem with array types Benji Java 1 10-06-2005 10:00 AM
Is the URLConnection class capable of being subclassed to createcustom protocol connections? - Java 3 07-24-2005 06:39 PM
Cannot view subclassed Page in Visual Designer =?Utf-8?B?U2xpbWVtYW4=?= ASP .Net 4 07-20-2005 04:03 AM
Specializing Subclassed Methods cppaddict C++ 1 06-03-2004 07:13 AM



Advertisments