Of cause your code runs well. But if you remove the "global foo" in main(), it will fail. And it will succeed again if you call exec(t1) directly. I think this behavior is strange. Even I pass a shadow copy of globals and locals to exec, it still fails. So perhaps there is a basic difference between exec(t1,dg,dl) and exec(t1,globals(),locals()). What do you think about it? Thanks.
On Jan 21, 2:14 am, Steven D'Aprano <steve +comp.lang.pyt...@pearwood.info> wrote: > On Thu, 20 Jan 2011 20:52:15 -0800, longqian9...@gmail.com wrote: > > In pyhton 3.1, I found the following code will succeed with argument 1 > > to 4 and fail with argument 5 to 9. It is really strange to me. I > > suspect it may be a buy in exec() function. Does anyone have some idea > > about it? Thanks. > > What makes you think it's a bug? Is there anything in the documentation > of exec that suggests to you that some other behaviour should occur? What > version of Python are you using? > > Without knowing what behaviour you expect and what behaviour you see, how > are we supposed to know if you've found a bug or not? > > I suggest you fire up the interactive interpreter and try this: > > t1 = """ > class foo: > def fun(): > print('foo') > > def main(): > global foo > foo.fun() > > main() > """ > > dg = {} > dl = {} > > exec(t1, dg, dl) > > then inspect the values of dg and dl and see if it helps. If not, write > back with what you expect to happen, and what you see instead. > > -- > Steven -- http://mail.python.org/mailman/listinfo/python-list