mutable default parameter problem [Prothon]

Troy Melhase troy at gci.net
Wed Jun 16 02:01:19 EDT 2004


On Tuesday 15 June 2004 02:07 pm, Mark Hahn wrote:
> As we are addressing the "warts" in Python to be fixed in Prothon, we have
> come upon the
> mutable default parameter problem.  For those unfamiliar with the problem,
> it can be seen in this Prothon code sample where newbies expect the two
> function calls below to both print [ 1 ] :

> We have three proposals in the Prothon mailing list right now to fix this.
> I'd like to bounce these off of the Python list also since this will
> possibly make a big difference in Python code ported over to Prothon and we
> can always use more advice.

Here's an idea:  if it ain't broke, don't fix it.

Seriously, you see a "wart" and a "problem".  I see a pleasant side-effect of 
the documented semantics.  True, new folks are surprised by the behavior, but 
once it's understood, it becomes more powerful.  

How do you intend to account for code like this:

def F(a, b, cache={}):
    try:
        return cache[(a,b)]
    except (IndexError, ):
        value = cache[(a,b)] = do_some_long_calc(a,b)
        return value

Or even this:

shared_cache = {}

def F(a, b, cache=shared_cache):
    ...

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.

Python is a tool, and you decrease the utility of that tool when you limit 
it's idioms.

> How much Python code would these different proposals break?

A lot.  I ran this:

$  find /usr/lib/python2.3/ -name "*.py" -exec grep "def.*=\[\]" {} \; | wc

And see 67 instances just in the standard library.  Multiply that by a factor 
of 1000, 10000 or more to reflect code in the field, and you might start to 
understand the significance of changing the language definition.

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