[Python-3000] pre-PEP: Default Argument Expressions

BJörn Lindqvist bjourne at gmail.com
Thu Feb 15 20:08:20 CET 2007


On 2/15/07, Jim Jewett <jimjjewett at gmail.com> wrote:
> On 2/13/07, Chris Rebert <cvrebert at gmail.com> wrote:
> >      There are currently few, if any, known good uses of the current
> >      behavior of mutable default arguments.
>
> Then are there *any* good use cases for the proposed semantics?

Note that the PEP says _currently_, with the change in semantics the
number of use cases increase drastically. See below.

> Here are the use cases that I can remember seeing for mutable
> default arguments.
>
> (1)  Not really (treated as) mutable.  ==> Doesn't care about the
> mutability semantics.
>
>     >>> def f(extra_settings={}) ...
>
> usually doesn't modify or even store extra_settings; it just wants an
> empty (and perhaps iterable) mapping.  (Sometimes, it doesn't even
> need that, and is really just providing type information.)

That is dangerous code. Sooner or later someone will modify the
extra_settings dict. For me, that is the main attraction of the PEP,
it removes that source of bugs (along with the annoying "if blaha is
None:" thingy).

    class Vector:
        def __init__(self, x, y, z):
            self.x = x
            self.y = y
            self.z = z

    class Ray:
        def __init__(self, direction, origin = Vector(0, 0, 0)):
            self.direction = direction
            self.origin = origin

    ray1 = Ray(Vector(0, 0, -1))
    ray2 = Ray(Vector(0, 0, 1))
    ray3 = Ray(Vector(-1, 0, 0), Vector(2, 3, 4))

The above code looks quite nice, but is wrong.

Not that it matters much, Guido has already rejected the PEP. But the
use cases does exist and there is a problem with how default argument
values are evaluated. Hopefully someone can invent a fix even if this
PEP wasn't it.

-- 
mvh Björn


More information about the Python-3000 mailing list