global, was Re: None assigment
Rainer Deyke
root at rainerdeyke.com
Fri Feb 9 01:00:00 EST 2001
"Aahz Maruch" <aahz at panix.com> wrote in message
news:95vst8$1na$1 at panix2.panix.com...
> In article <_BHg6.195181$ge4.67634054 at news2.rdc2.tx.home.com>,
> Rainer Deyke <root at rainerdeyke.com> wrote:
> >"Aahz Maruch" <aahz at panix.com> wrote in message
> >news:95umoi$is5$1 at panix2.panix.com...
> >>
> >> What you're missing is the issue of Python scopes. Try this:
> >>
> >> b=2
> >> def foo():
> >> b=4
> >> print b
> >> del b
> >> global b
> >> print b
> >> foo()
> >
> >And what *you*'re missing is that whether a variable is local or global
is
> >determined at compile time (in the absensce of 'exec' or 'from ... import
> >*'). The above does not work.
>
> It doesn't, eh? Did you try running it? (After a few blunders of my
> own, I rarely post code to c.l.py without testing it -- just to make
> sure.) Note that this is not the same as the issue with None, but it's
> still a scoping issue.
Strangely enough, it does work. I'm really confused now. My understanding
had been that 'global' is not a normal statement executed at run-time, but
something which modifies the meaning of a name for the whole function. It
seems I was right about the former but wrong about the latter. Consider the
following:
b = 6
def foo():
b = 4
if 0:
global b
print b
def bar():
b = 4
if 1:
global b
print b
def baz(n):
b = 4
if n:
global b
print b
foo() # Prints '4'.
bar() # Prints '6'.
baz(0) # Prints '6', not '4'!
baz(1) # Print '6'.
(None of them modified the global variable 'b'.)
>From this I conclude that the behavior of 'global' is totally unpredictable
except when it is placed above all non-'global' statements in a function.
--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games - http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor
More information about the Python-list
mailing list