Implementation of the global statement
Terry Reedy
tjreedy at udel.edu
Wed Nov 27 14:39:48 EST 2002
tem.py:
y=0
def f():
global y
y+=1
"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. Now to my questions:
> Why is that so?
Lets augment tem.py with
import math
def g:
return [f(), math.sin(.033)]
Now your question becomes: why does g look for f and math in tem.py.
Fairly obvious. Otherwise, doc for g would need to say: 'to run g,
you must define f() and import math.' Remember, func only has *1*
global context.
> Is that behaviour intended?
yes
> Is it likely to stay that way?
yes
> Is there an obvous way to have f (still defined in A) manipulate
> objects in B when executed in B?
A way:
>>> import tem
>>> y=0
>>> f=tem.f
>>> tem.f(); y, tem.y
(0, 1)
>>> f(); y, tem.y
(0, 2)
>>> exec tem.f.func_code in globals(); y, tem.y
(1, 2)
eval(tem.f()) or eval(f()) does not change behavior because globals
only affects lookup of tem or f.
Terry J. Reedy
More information about the Python-list
mailing list