e-mail address change (was Re: [Tutor] python's default argumentvalue handling in functions - weird syntax? problem grappling withthe concept)

Alan Gauld alan.gauld at freenet.co.uk
Thu Feb 10 09:14:04 CET 2005


> >def f(a,L=[]):
> >    if L==[5]:
> >        print 'L==[5] caught'
> >        print L
> >        print 'resetting L...'
> >        L=[]
> >    L.append(a)
> >    return L
> >
> >
> >###
> >
> Now I'm dizzy... I can't understand why there are two "L"!
> L is a local variable of the function, right?

L is a parameter if the function with a default value.
That means its a special type of local variable that
has a life outside the function. But while inside the
function it acts just like a local variable.

> anything else) Then if I reassign L to something, why doesn't it
keep
> that change till next run?

Because local variables die and their contents are garbage
collected at the end of the function. L goes back to its
external life which points at the original default L.

> so it should keep the reassignation, no?

No, the whole point of this thread is that Python, as
the documentation said, only evaluates the default
value once, at function definition time, you *cannot*
change it. After each function invocation all local
changes are lost and it reverts to the ioriginal value.

Alan G.



More information about the Tutor mailing list