[Python-ideas] Syntax for passing lambdas to functions

Steven D'Aprano steve at pearwood.info
Thu Feb 27 22:14:00 CET 2014


On Thu, Feb 27, 2014 at 06:48:25PM +0000, Joshua Landau wrote:
> On 27 February 2014 18:27, Antony Lee <antony.lee at berkeley.edu> wrote:
> > Now that someone mentioned dispatch tables, another possibility would be to
> > support assignment to tables and monkey-patching directly, with a syntax
> > like
> >
> > def obj.method(*args): ... # __name__ = "method" (the attribute name)
> > def table[key](*args): ... # __name__ = ??? (perhaps "table[key]"?)
> > (and also any other "lvalue".)
>
> I would very much support this. It's actually odd that you *can't* do
> it, considering you *can* do
> 
>     class A: ...
>     a = A()
>     l = [0]
> 
>     for a.x in [1, 2, 3]: ...
>     for l[0] in [1, 2, 3]: ...

I wonder whether that is deliberate feature, or an accident of the way
the syntax works. It does seem to be pretty useless though -- why are
you using an attribute or list as a loop variable? 

As far as setting a method on an instance like that, if you're defining 
methods, 99.9% of the time they ought to be defined on the class, not on 
the instance. For the remaining one time in a thousand, it is nearly 
always sufficient to either embed the assignment inside __init__, or use 
a temporary, external, function:

class Whatever:
    def __init__(self, value):
        def func(arg):
             return arg + value
        self.func = func


Things like this are unusual enough that they don't need -- in fact,
*shouldn't* have -- dedicated syntax to support them. That syntax simply
complicates the interpreter, makes it harder for people to learn the
language, adds more decisions for the programmer to make, and just for a
marginal (if any) benefit.

The list example is slightly better, but not enough to allow it. If you 
could populate the entire list as a single expression, that might be 
interesting:

    functions = [
        def spam(): ..., 
        def eggs(): ...,
        def cheese(): ...,
        ]

but the syntax suggested here doesn't let you do that. You still have a 
separate statement for each item. All it buys you is saving *one line* 
per assignment:

    def spam():
        ...
    functions[0] = spam

or two if you absolutely must then unbind the name spam afterwards

    del spam

(but normally I wouldn't bother).


> However, there are disadvantages:
> 
>     potentially ambiguous grammar
>     (very) small chance of misuse
>     could hurt introspection
> 
> Further, I don't imagine I'd use it frequently. Just enough, though.

I'd like to see some non-contrived use-cases for where you think you 
would actually use this.



-- 
Steven


More information about the Python-ideas mailing list