[Python-ideas] Default arguments in Python - the return - running out of ideas but...

Carl Johnson cmjohnson.mailinglist at gmail.com
Fri May 15 09:30:18 CEST 2009


Bruce Leban wrote:

> I'll use an @dynamic decorator-like syntax to illustrate. These would be
> valid:
>
> def foo(a, b = @dynamic lambda: []):
> def foo(a, b = @dynamic lambda: list()):
> def foo(a, b = @dynamic list):
> def foo(a, b = @dynamic random.random):
>
> and this would not:
>
> def foo(a, b = @dynamic [])
> def foo(a, b = @dynamic 5)
>
> because @dynamic says that the thing that follows is called to generate a
> dynamic default parameter value and you can't call [] or 5.

Hmm, very interesting, but in your example what is "dynamic" doing?
Are you proposing it as a keyword to signal "here comes a dynamic
default"? Do we really need it? Why not something like this:

def five_appender(x=@list):
    x.append(5)
    return x

>>> five_appender()
[5]
>>> five_appender()
[5]

The idea is that @ is a magic sigil meaning, "call this if no argument
is passed in." So, as per your prior example @[] or @5 would be result
in a runtime error, since they're not callable. If for some reason you
want a fresh 5 (I can't think of why, since it's immutable, but
whatever), you would need to use a lambda:

def n_appender(n=@lambda: 5, x=@list):
    x.append(n)
    return x

Do y'all think this is enough inline with how @ is already used to
make sense? Or is it too different from the existing use of @?

-- Carl Johnson



More information about the Python-ideas mailing list