[Python-ideas] YAML (yet-another-multiline-lambda)

Steven D'Aprano steve at pearwood.info
Tue Oct 22 14:39:03 CEST 2013


On Tue, Oct 22, 2013 at 03:10:29AM -0700, Antony Lee wrote:

> Specifically, I suggest that the "def" (and possibly the "class")
> keyword(s) may be used in an expression context, if immediately surrounded
> by parentheses.  

I don't think there is any need to allow class in an expression, since 
we already have type().

> The indentation of the body of the function is given by
> the indentation of the first line after the def.

I presume that means you can't do this:

value = [1, 2, 3, (def spam(arg): do_this()
                        do_that()
                        ), 4, 5, 6]

I think I would be okay with that, since you can't do that with the def 
statement either:

py> def spam(): do_this()
...     do_that()
  File "<stdin>", line 2
    do_that()
    ^
IndentationError: unexpected indent


I suppose, like the statement version, a single-line function body could 
be inline:

value = [1, 2, 3, (def spam(arg): do_this()), 4, 5, 6]

which would then make lambda redundant.

In each of your examples, you have the body indented further to the 
right than the def. Is that mandatory, or would you allow something like 
this?

value = [1, 2, 3, (def spam(arg):
    do_this()
    do_that()
    if condition():
        do_something_else()
    ),
    4, 5, 6,
    ]

That is, relative to the def itself, the body is outdented.


I can't see any reason to justify prohibiting the above in the language, 
although I'd probably frown upon it in style-guides. I think that should 
be written as:

value = [1, 2, 3, 
         (def spam(arg):
              do_this()
              do_that()
              if condition():
                  do_something_else()
              ),
         4, 5, 6,
         ]

sort of thing. But I don't think that having the first indent be to the 
left of the def should be prohibited. However, that can lead to some 
pretty ugly, and misleading, constructions:

def spam(arg, func=(def ham(a,
                            x, 
                            y, 
                            z):
    fe(a)
    fi(x)
    fo(y)
    fum(z)
    ),
        ):
    ...


I'm not sure if there is a question buried in this, or just an 
observation. I hardly ever miss having multi-line lambdas, and I fear 
that they will make code harder to read and understand.


-- 
Steven


More information about the Python-ideas mailing list