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

meridian stephen.dover at onetel.co.uk
Thu Jul 6 06:50:16 EDT 2006


I thought I had 'got' globals but this one seems strange.
I want my example function 'doIt' to use and optionally modify a module
variable 'gname', so I declare 'global gname' in the function, but when
modified it doesn't stay modified.

gname = 'Sue'
def doIt(name = gname):
    global gname
    gname = name
    print 'doIt name', name, 'gname', gname

print 'start gname', gname
doIt()
doIt(name='Lisa')
doIt()
print 'finish gname', gname

gives...
 start gname Sue
 doIt name Sue gname Sue
 doIt name Lisa gname Lisa
 doIt name Sue gname Sue
 finish gname Sue

The variable gname has reverted back to value 'Sue'

Curiously though, without the third doIt() call, it works...
print 'start gname', gname
doIt()
doIt(name='Lisa')
#doIt()
print 'finish gname', gname

gives...
 start gname Sue
 doIt name Sue gname Sue
 doIt name Lisa gname Lisa
 finish gname Lisa

The variable gname has been modified to 'Lisa'

Any ideas how I can make the 'Lisa' assignment permanent forever in 2nd
doIt?   Thanks

(Note. Contrived example substitutes for a web-type app, where, if the
page is called without arguments then it displays the global defaults.
If the page is called with form arguments then it should be able to
change the global defaults)




More information about the Python-list mailing list