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)

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to