mutable default parameter problem [Prothon]

Troy Melhase troy at gci.net
Wed Jun 16 04:10:39 EDT 2004


On Tuesday 15 June 2004 10:53 pm, Andrea Griffini wrote:
> On Tue, 15 Jun 2004 22:01:19 -0800, Troy Melhase <troy at gci.net> wrote:
> >Or even this:
> >
> >shared_cache = {}
> >
> >def F(a, b, cache=shared_cache):
> >    ...
>
> A global you mean ? Why not just saying "global shared_cache"
> at the start of the function ?

The shared_cache dictionary is mutable, making the global statement redundant 
at best.  It could have just as easily been left out of the function argument 
list.

The definition above would also allow clients of the function to pass in a 
cache of their choosing.  (Granting, of course, that this would most likely 
be an obscure use.)

> If you need more power than a global then you probably a
> (callable) class is going to serve you better than a function.

Of course.  I was trying to illustrate using a named module-level dict instead 
of a mutable value that could not be accessed outside of the function body.

> Is really a feature that if someone passes (by mistake) an extra
> parameter to the function the script silently swallows it and
> behaves strangely ? Or you also double-wrap the function, so
> that a(x,y) calls real_a(x,y,cache=[]) ?

How many times have you passed an extra parameter by mistake?  This is Python, 
and one of the mottos is "we're all consenting adults".

> >Of course you can argue that this is bad style, but the counter argument
> > is just as strong:  this is quite pythonic and quite readable.
>
> Pythonic ? In the sense that this is for example more explicit ?
> Are you kidding ?

No, I'm not.  The function specified a muteable argument.  Nothing implicit 
about it.

> That something is used is one thing. That something is elegant
> is another.

Of course.  But using a mutable default function parameter as a cache is 
elegant as far as I'm concerned.


-- 
Troy Melhase, troy at gci.net
--
I have sworn upon the altar of God eternal hostility against every form of 
tyranny over the mind of man. - Thomas Jefferson





More information about the Python-list mailing list