Implementation of the global statement

Mikael Olofsson mikael at isy.liu.se
Thu Nov 28 03:36:46 EST 2002


Me, myself and I wrote about about defining here and executing there:
> >   Is that behaviour intended?
> >   Is it likely to stay that way?

Greg Ewing answered:
> Yes and yes. [snip clarifying stuff]

I also wrote on the same topic:
> >   Is there an obvous way to have f (still defined in A) manipulate
> >   objects in B when executed in B?

Greg said:
> Don't know whether it counts as "obvious", but I
> think there is a way (short of using exec):
> 
>    import new
>    g = new.function(f.func_code, B.__dict__)
> 
> This creates a new function g which has the
> same code as f but a different global namespace.
> 
> (You can't just change f.func_globals directly
> because it's a read-only attribute, unfortunately.)

Thanks Greg, especially for this snippet. It does the job, and it has
the advantage of being readable. And thanks to others who also answered.
Not that I understand everything about Python internals, but I do feel
enlightened by your replies.

Greetings
/Mikael

-----------------------------------------------------------------------
E-Mail:  mikael at isy.liu.se
WWW:     http://www.dtr.isy.liu.se/dtr/staff/mikael               
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339

         /"\
         \ /     ASCII Ribbon Campaign
          X      Against HTML Mail
         / \

This message was sent by Sylpheed.
-----------------------------------------------------------------------
Linköpings kammarkör: www.kammarkoren.com




More information about the Python-list mailing list