Huh? func_defaults, default values in function calls

Mark Hathaway hathawa2 at marshall.edu
Tue Apr 11 21:17:10 EDT 2000


>>> 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.

Definately goofy!

>> 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!

This way you'll never really know what the default is going to be.
Ha ha ha ha. that's pathetic.

> That's exactly right. The idiomatic Python way of doing what Roger wants
> here is:
>
> def a(x='',y='',z=None):
>    if z is None:
>       z = {}
>    if x:
>       z['x'] = x
>    if y:
>       z['y'] = y
>    print str(z)
>
> I think this is the first time I've seen show up with dictionaries, usually
> is shows up with lists.

At least this idiom gets the job done, but it sincerely defeats the
idea of having default values to have to say "z=None".


Mark S. Hathaway
email: hathawa2 at marshall.edu



More information about the Python-list mailing list