I thought I'd 'got' globals but...
Bruno Desthuilliers
onurb at xiludom.gro
Thu Jul 6 06:58:35 EDT 2006
meridian wrote:
> 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):
This is a FAQ, cf:
http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects
Briefly : default args are eval'd only once at load/import time.
> Any ideas how I can make the 'Lisa' assignment permanent forever in 2nd
> doIt? Thanks
def doIt(name=None):
global gname
if name is None:
name = gname
else:
gname = name
> (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)
Modifying globals from within a function is usually a very bad idea.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list