Mutable defaults

J. Pic jpic at yourlabs.org
Wed Feb 10 21:54:55 EST 2021


Adding decorators with some inspect sauce could certainly work with the
syntax we already have:

@default(x=lambda: copy([]), y=lambda x: len(x))
def foo(x=None, y=None):

I think this PoC is doable. But the lambda copy is a boring so, two
decorators:

@default.copy(x=[])
@default.call(y=lamba x: len(x))
def foo(x=None, y=None):

Or with a new syntax:

def foo(x:=[], y`=len(x))

Here walrus is used to denote that an assignment of the right side is going
to take place at call, and the backtick to denote that execution of the
right side is going to take place.

Le jeu. 11 févr. 2021 à 03:06, Chris Angelico <rosuav at gmail.com> a écrit :

> On Thu, Feb 11, 2021 at 12:56 PM J. Pic <jpic at yourlabs.org> wrote:
> >
> > I just meant removing the whole "default value mutating" story, not
> removing mutable variables. Really, I was wondering if there was a use case
> where this actually turns to an advantage, in which case it would be a
> designed feature rather than an undesirable side effect, which it seems to
> be.
> >
>
> Right, I know you weren't asking about removing mutables altogether.
> But how would you remove "default value mutating"? Do you disallow any
> mutable values from being argument defaults? Because that's a huge
> category of values that are no longer available.
>
> Mutable defaults most certainly ARE used deliberately, although often
> it's more as a sort of "static variable" rather than actually a
> parameter. But it's common enough as an idiom that it can't be changed
> without breaking a lot of code.
>
> > Now I'm wondering if you have considered copy on write, to save the
> overhead from copying every mutable default at every call when it is not
> necessary.
> >
>
> That's its own level of mess.
>
> The only way to move forward with this is something
> backward-compatible, which probably means an explicit request for late
> binding (or copying, which comes to much the same thing). But it needs
> an elegant syntax. The proposal lives or dies on that syntax, and so
> far, it's always died.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>


More information about the Python-list mailing list