Scope confusion...

Justin Shaw wyojustin at hotmail.com
Mon Jan 20 20:33:09 EST 2003


"Kevin at Cazabon.com" <kevin at cazabon.com> wrote in message
news:YX0X9.642361$GR5.433453 at rwcrnsc51.ops.asp.att.net...
> I had a perplexing problem that turned out to be a scope issue, but I
still
> can't for the life of me figure out WHY it's behaving like this.  Consider
> this minimal example, and the resulting output:
>
> ##################
> def a(list = []):
>     list.append("test")
>     return list
>
> def b():
>     for i in range(20):
>         print a()
>
> if __name__ == "__main__":
>     b()
> ##################
>
What am I missing?  (I'm using ActivePython 2.2.1 build 222)
>
> Kevin.
>

The default argument is evaluated when the module is loaded.  This one list
gets appended each time you call a().  If this is not the desired behavior
the usual approach is to have the default argument be None.

##################
def a(l = None): # the name list is probably best left to describe the list
type
    if l is None:
        l = []
    l.append("test")
    return l

def b():
    for i in range(20):
        print a()

if __name__ == "__main__":
    b()
###################






More information about the Python-list mailing list