global, was Re: None assigment

Michael Hudson mwh21 at cam.ac.uk
Fri Feb 9 09:18:32 CET 2001


"Rainer Deyke" <root at rainerdeyke.com> writes:

> 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.

Which version are you using?  They all print 4 for me, and all but
foo() do modify the value of `b'.  foo() doesn't because what follows
an

if 0:

isn't compiled.

Cheers,
M.

-- 
  Premature optimization is the root of all evil in programming.  
                                                       -- C.A.R. Hoare



More information about the Python-list mailing list