global, was Re: None assigment

Rainer Deyke root at
Fri Feb 9 07:00:00 CET 2001

"Aahz Maruch" <aahz at> wrote in message
news:95vst8$1na$1 at
> In article <_BHg6.195181$ge4.67634054 at>,
> Rainer Deyke <root at> wrote:
> >"Aahz Maruch" <aahz at> wrote in message
> >news:95umoi$is5$1 at
> >>
> >> 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
> >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 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

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
Shareware computer games           - 
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor

More information about the Python-list mailing list