473,241 Members | 1,533 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,241 software developers and data experts.

Strange interaction between exec, dictionary subtypes, and global variables in 2.4

I've been playing with dictionary subtypes for custom environments,
and I encountered a strange interaction between exec, dictionary
subtypes, and global variables. I've attached a test program, but
first I'd like to give some background.

Python uses dictionary objects as symbol tables in it's execution
contexts. Since these objects used to be basic types, which were not
subclassable, some of the interpreter code accessed them using
low-level C functions.

Then dictionary types were made subclassable, and I was pretty
excited, because I wanted to use them to set up custom execution
environments with extended semantics. This didn't work, because when
the dictionary types were made subclassable, the interpreter code
which used them as symbol tables was not changed, so subclassed
dictionaries used in exec statements or eval calls bypassed their
subclass functions, and jumped straight to the underlying C functions.

In python 2.4, this was finally fixed, and you can now use subclassed
dictionaries in exec statements and eval calls.

Except that there is some niggling edge case dealing with variables
which have been marked 'global'. It seems that if a compiled chunk of
python contains a 'global VAR' statement, anywhere, then that VAR, and
only that VAR, will bypass the subclassed functions when it is
accessed.

I'd like to fix this, and send it upstream, and I've worked on
extensive python/C bindings before, but I've not hacked the
interpreter. I took a look around, and I'm not sure where the symtable
lookup is happening.

However, I have some belief that someone on this list _may_ be able to
point me in the right direction.

#!/usr/bin/python2.4

class TypedDictionary(dict):
def __setitem__(self, key, value):
print '__setitem__(%s, %s)' % (key, value)
if self.has_key(key):
t = type(self[key])
try:
value = t(value)
except Exception:
raise TypeError, \
"illegal assignment to '%s': %s cannot be coerced to %s" \
% (key, type(value), t)
dict.__setitem__(self, key, value)

test_script = """
foo = 0
bar = 'xyz'
print 'foo:', repr(foo), '; bar:', repr(bar)

foo = '1'
bar = 42
print 'foo:', repr(foo), '; bar:', repr(bar)
"""

print "Without 'global foo':"
exec test_script in TypedDictionary()

print

print "With 'global foo':"
exec test_script + """
def f():
global foo
pass
""" in TypedDictionary()
This program produces this output:
Without 'global foo':
__setitem__(foo, 0)
__setitem__(bar, xyz)
foo: 0 ; bar: 'xyz'
__setitem__(foo, 1)
__setitem__(bar, 42)
foo: 1 ; bar: '42'

With 'global foo':
__setitem__(bar, xyz)
foo: 0 ; bar: 'xyz'
__setitem__(bar, 42)
foo: '1' ; bar: '42'
__setitem__(f, <function f at 0x40230454>)

Dec 31 '05 #1
1 2671
Crutcher <cr******@gmail.com> wrote:
...
Except that there is some niggling edge case dealing with variables
which have been marked 'global'. It seems that if a compiled chunk of
python contains a 'global VAR' statement, anywhere, then that VAR, and
only that VAR, will bypass the subclassed functions when it is
accessed.


As we covered on another mailing list today, the presence of that
'global VAR' anywhere means that accesses to that variable get compiled
into bytecodes LOAD_GLOBAL, STORE_GLOBAL, instead of the LOAD_NAME,
STORE_NAME produced when no 'global VAR' is around; and looking at
ceval.c, we see that the use of dictionary subclasses is only supported
for f_locals -- f_globals (and f_builtins) are always used as 'exact'
dict instances instead. I consider that a bug, even though there might
be a (hopefully miniscule) slowdown in supporting dict subclasses for
f_globals as well as for f_locals. I know you're now working on a patch
for the issue (and I repeat my recommendation of adding a unit-test for
this issue as part of your patch)... let's see what comes up (the
python-dev mailing list may be more appropriate for this discussion,
btw, since it IS about the development of Python).
Alex
Dec 31 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Jonathan | last post by:
I'm puzzled by Python's behavior when binding local variables which are introduced within exec() or execfile() statements. First, consider this simple Python program: # main.py def f() : x = 1...
5
by: Nick Jacobson | last post by:
This works fine: x = 1 def execfunc(): print x execfunc() So why doesn't this? s = \
3
by: kepes.krisztian | last post by:
Hi ! In Unifying types and classes in Python 2.2 article I see that: >>> print a # show the result
2
by: tedsuzman | last post by:
----- def f(): ret = 2 exec "ret += 10" return ret print f() ----- The above prints '12', as expected. However,
2
by: Gerald Senarclens de Grancy | last post by:
Hi! I kept searching my online and offline python ressources to figure out how to execute some code in the global dictionary. Basically I'm reading a options file that defines some variables. I...
3
by: Attila Szabo | last post by:
Hi, I wrote this sample piece of code: def main(): lambda x: 'ABC%s' % str(x) for k in range(2): exec('print %s' % k) main()
10
by: Antoon Pardon | last post by:
I have the following little piece of code: class Cfg:pass #config = Cfg() def assign(): setattr(config, 'Start' , ) def foo(): config = Cfg()
5
by: TPJ | last post by:
I have the following code: ----------------------------------- def f(): def g(): a = 'a' # marked line 1 exec 'a = "b"' in globals(), locals() print "g: a =", a
4
by: carl.dhalluin | last post by:
Hello I am completely puzzled why the following exec code does not work: mycode = "import math\ndef f(y):\n print math.floor(y)\nf(3.14)" def execute(): exec mycode execute()
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.