Huh? func_defaults, default values in function calls

James "Wez" Weatherall jnw22 at cam.ac.uk
Tue Apr 11 09:20:41 EDT 2000


"Roger Baklund" <roger at netconnect.no> wrote in message
news:8cv5qj$35p$1 at zinc.intern.netconnect.no...
[snip of some code]
>
> I don't get it. Why isn't the dictionary reset to {'x':'a'} when i call
> the function the last time?
>
> >>> a.func_defaults
> ('', '', {'x': 'a', 'y': 'c'})
>
> Why is not {} the default for the z parameter?

According to my understanding of the Python docs, defaults are only
evaluated at function definition time, not at function invokation time.

As a result, if you set a mutable object (list, dictionary, etc) as a
default, it'll be set when the function is defined and then if the function
changes it, it'll stay changed for subsequent invokations.  The function
effectively has a "side-effect", of modifying it's own default!

You won't get this behaviour with something like:

def myfun(x, a = 5):
    a = x

though, I don't think, because "5" isn't mutable.

Cheers,

--
James "Wez" Weatherall






More information about the Python-list mailing list