Mutable defaults

Chris Angelico rosuav at gmail.com
Wed Feb 10 22:00:35 EST 2021


On Thu, Feb 11, 2021 at 1:55 PM J. Pic <jpic at yourlabs.org> wrote:
>
> 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):

This would work, although the copy is unnecessary here. But you're
assuming that it magically figures out whether to pass 'x' or not.
Seems awkward. Also, it doesn't solve the problems of signature
display, so you're not really much better than:

def foo(x=None, y=None):
    if x is None: x = []
    if y is None: y = len(x)

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

Now this is the sort of thing I was talking about: actual syntactic
support. But this syntax looks pretty terrible, and if you propose it
like this, I doubt it'll be accepted. Backtick had a very very
different meaning in Py2, and := is going to be extremely confusing.

This proposal will stand or fall on the syntax. Don't just give
placeholder syntax. Put some thought into figuring out what would
actually be good, and propose *that*. The semantics aren't really even
that hard - it'd be equivalent to an if statement just inside the
function.

ChrisA


More information about the Python-list mailing list