[Python-ideas] Enhance definition of functions

Paul Moore p.f.moore at gmail.com
Wed Jul 31 11:15:33 CEST 2013


On 31 July 2013 07:47, Andrew Barnert <abarnert at yahoo.com> wrote:

> > It might be lack of imagination on my part, but I have a lot of nested
> functions named "function" or "callback" that are too complex to be a
> lambda, but too simple or specialized to bother making them proper
> functions. The key function for sort is one of the usecases.
> >
> > I'd love to have anonymous functions for that, but haven't seen a
> proposal for those yet that would fit the language.
>
> Would it really help anything? If you're worried about keystrokes you can
> always call them "f" instead of "function". And I don't think anonymous
> functions would be as nice in tracebacks as even genetically-named ones.
>
> I think having to define them out of line is usually a more serious
> problem than having to name them, and if you solve that problem you may get
> the other one for free (although admittedly you may not, as the @in
> proposal shows...).


The only real reason I ever use lambdas (and would sometimes like a
multiline version or similar) is for readability, where I want to pass a
callback to a function and naming it and placing it before the call
over-emphasises its importance. It's hard to make this objective, but to my
eyes

    def k(obj):
        return obj['x'] / obj['y']
    s = list(sorted(l, key=k)

reads marginally worse than

    s = list(sorted(l, key=k)) where:
        def k(obj):
            return obj['x'] / obj['y']

simply because the focus of the block of code (building a sorted list) is
at the start in the latter.

But because the difference is so subtle, it's very hard to get a syntax
that improves things sufficiently to justify new syntax. And it's also not
at all obvious to me that any improvement in readability that can be gained
in simple example code that you can post in an email, will actually still
be present in "real world" code (which, in my experience, is always far
messier than constructed examples :-))

Paul
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130731/7f26baf1/attachment-0001.html>


More information about the Python-ideas mailing list