Implementation of the global statement

Hung Jung Lu hungjunglu at yahoo.com
Wed Nov 27 17:35:33 EST 2002


Mikael Olofsson <mikael at isy.liu.se> wrote in message news:<mailman.1038409397.2506.python-list at python.org>...
> I have a few related questions. Assume that we have defined f as above
> in one global namespace, A say, and assume that f (re)binds y. Then we
> place f in another global namespace, B say. What happens when we execute
> f in B is that y in A is rebound. I would have guessed that a variable y
> in B would have been created or rebound. 

I think it'll be more clear if you can provide concrete code examples.
Words tend to lend to different interpretations in different ears. :)

# file A.py:
y = 1
def f():
    global y
    y = 2

# file B.py:
from A import f
y = 3
f()
print y
import A
print A.y
if f.func_globals == A.__dict__: print 'true'
exec f.func_code in globals()
print y

The result is:
3
2
true
2

>   Why is that so? 
>   Is that behaviour intended?
>   Is it likely to stay that way?

(a) Notice that f() was created in A, and at the moment of its
creation, it stores the binding to the global namespace A. (You can
check the f.func_globals) So, when you execute the code of f() without
specifying a new globals dictionary, it uses its default bound
globals: A.__dict__.

(b) I guess so.

(c) I guess so. When a function is created, some information is stored
in the function object. (Check dir(f) to see its attributes.) A
function is more than just its code. Things like the function-globals
dictionary, the default values, etc. are kind of bound to the whole
Python philosophy and enjoy a long track record. That is, I don't
think they are likely to change.

>   Is there an obvous way to have f (still defined in A) manipulate
>   objects in B when executed in B?

Yes. As in the code example above. Your sentence "... executed in
B..." reflects the good choice of name for the Python statement "exec
... in ..." :)

regards,

Hung Jung



More information about the Python-list mailing list