Subclassed dict as globals

Discussion in 'Python' started by Evan Simpson, Jan 26, 2005.

  1. Evan Simpson

    Evan Simpson Guest

    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
     
    Evan Simpson, Jan 26, 2005
    #1
    1. Advertising

  2. Evan Simpson <> 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
    <>
     
    Lenard Lindstrom, Jan 26, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?U2xpbWVtYW4=?=

    Cannot view subclassed Page in Visual Designer

    =?Utf-8?B?U2xpbWVtYW4=?=, Jul 15, 2005, in forum: ASP .Net
    Replies:
    4
    Views:
    490
    =?Utf-8?B?U2xpbWVtYW4=?=
    Jul 20, 2005
  2. -
    Replies:
    3
    Views:
    465
    Thomas Fritsch
    Jul 24, 2005
  3. Benji
    Replies:
    1
    Views:
    464
    Chris Uppal
    Oct 6, 2005
  4. Replies:
    20
    Views:
    2,234
  5. cppaddict

    Specializing Subclassed Methods

    cppaddict, Jun 3, 2004, in forum: C++
    Replies:
    1
    Views:
    371
    Buster
    Jun 3, 2004
Loading...

Share This Page