I thought I'd 'got' globals but...

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Jul 9 08:12:27 EDT 2006


Luis M. González a écrit :
> Bruno Desthuilliers wrote:
> 
>>def doIt(name=None):
>>  global gname
>>  if name is None:
>>    name = gname
>>  else:
>>    gname = name
>>
> 
> 
> Sorry for this very basic question, but I don't understand why I should
> add the global into the function body before using it.

You have to do it if you intend to rebind the name in the function's 
body (else this would create the name in the local namespace).

> This function works even if I don't add the global.
> Just to try this out, I wrote this variant:
> 
> gname = 'Luis'
> 
> def doIt2(name=None):
> 	if name is None:
> 		name = gname
> 	return name


Please read more carefully the OP's code:
"""
gname = 'Sue'
def doIt(name = gname):
     global gname
     gname = name
     print 'doIt name', name, 'gname', gname
"""

As you can see, it rebinds gname.

> print doIt2()  --> returns Luis.
> 
> So, what's the point of writing the function this way instead?
> 
> def doIt2(name=None):
>         global gname
> 	if name is None:
> 		name = gname
> 	return name

In this case, you don't need the global statement (but keeping it makes 
clear you're using a global name, which is not a bad thing in itself...)

Now if it's about LOCs count, here's a shorter equivalent:
doIt3 = lambda name : (name, gname)[name is None]



More information about the Python-list mailing list