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. Advertisements

  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. Advertisements

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. Alexander Kozlovsky

    dict!ident as equivalent of dict["ident"]

    Alexander Kozlovsky, May 21, 2006, in forum: Python
    Replies:
    5
    Views:
    599
    Alexander Kozlovsky
    May 22, 2006
  2. Paul Melis

    dict.has_key(x) versus 'x in dict'

    Paul Melis, Dec 6, 2006, in forum: Python
    Replies:
    48
    Views:
    1,624
    Kent Johnson
    Dec 15, 2006
  3. Almad
    Replies:
    8
    Views:
    615
    Terry Reedy
    Dec 14, 2006
  4. Drew
    Replies:
    19
    Views:
    1,619
    Duncan Booth
    Mar 15, 2007
  5. Albert van der Horst

    dict's as dict's key.

    Albert van der Horst, Jan 13, 2010, in forum: Python
    Replies:
    5
    Views:
    474
    Lie Ryan
    Jan 17, 2010
  6. Menghan Zheng
    Replies:
    1
    Views:
    378
    alex23
    Apr 20, 2010
  7. Cameron Simpson
    Replies:
    6
    Views:
    544
    alex23
    Apr 21, 2010
  8. macm
    Replies:
    11
    Views:
    809
    Alexander Gattin
    Nov 11, 2010
Loading...