proposed syntax for multiline anony-functions (hopefully?)

Chris Angelico rosuav at gmail.com
Thu Aug 21 04:18:14 EDT 2014


Ah, here we go again! It's multi-line lambda season. Comes around as
regularly as duck-typing season, rabbit seasoning, baseball season,
and other Looney Tunes references. :)

On Thu, Aug 21, 2014 at 5:55 PM,  <icefapper at gmail.com> wrote:
> doFunc(def():
>    print( "anon" )
>    return "gvr")

What I'm seeing here is that "def():" introduces a suite which becomes
a function definition that's part of the current expression. That's
reasonable, but I don't like the close parens on the same line; even
if this syntax is allowed, I'd frown on it in style guides,
recommending the close parens go on the next line:

doFunc(def():
    print( "anon" )
    return "gvr"
)

But either way, the question you need to answer is: How is this better
than the regular syntax for named functions?

def tmp():
    print( "anon" )
    return "gvr"
doFunc(tmp)

The one use-case that I can think of is large expressions like dict
displays, but I'd like to see a serious example that actually needs
this. Here's a toy example:

tag_handler = {
    "span": lambda content: content,
    "div": lambda content: "\n"+content+"\n",
    "p": lambda content: "\n"+content+"\n",
    "br": lambda content: "\n",
}

If you wanted to expand one of those to have statements in it, you'd
have to take it out-of-line and break the flow. But this is totally
contrived and not real-world; before this sort of feature gets into
the language, there really needs to be a concrete use-case. Since
there's nothing that actually cannot be done with an out-of-line
function, the criterion has to be "doing this out-of-line is extremely
ugly or error-prone", which is a fairly high bar to reach. You'll need
something where anyone will immediately say "Oh, that way is horribly
hard to read, but the new way makes it beautifully clean!".

Python is much more statement-oriented than some languages. In Pike, I
can have a function that's syntactically a single gigantic expression,
because it (occasionally!!) makes sense to do it that way; Python
doesn't really give that option. So while Pike has good justification
for an anonymous function syntax with full statement support, Python
doesn't really call for it as much. That's why Python's survived this
long with its lambda functions being so severely restricted :)

ChrisA



More information about the Python-list mailing list