Huh? func_defaults, default values in function calls

Tim Hochberg tim.hochberg at ieee.org
Tue Apr 11 10:37:07 EDT 2000


"James "Wez" Weatherall" <jnw22 at cam.ac.uk> wrote in message
news:8cv8ra$hio$1 at pegasus.csx.cam.ac.uk...
> "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!


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.

-tim





More information about the Python-list mailing list