[Python-ideas] Syntax: 'return: ...' expressions

Andrew Barnert abarnert at yahoo.com
Wed Jan 7 08:11:32 CET 2015

On Jan 6, 2015, at 21:08, Yawar Amin <yawar.amin at gmail.com> wrote:

> Actually I can offer counter-examples to that:
>  def p(x): print x
>  class A: p("Hello!")
>  class B: 1
>  # Etc.

No, there are no counter-examples there. A top-level program is a sequence of statements. Both def and class are compound statements, meaning the colon is followed by either a simple statement list or an indented block of statements. An expression statement is a kind of simple statement containing nothing but an expression.

> But I think I see what's happening here: statements are the top dogs in
> Python, and when Python wants a statement but only has an expression, it
> 'promotes' the expression into a statement by evaluating it, throwing
> away its value, and pretending nothing happened (i.e., that there was a
> 'pass' statement there). Thus defining a class can have the nonsensical
> effect of calling a function.
> But there's currently no way of going in the other direction, i.e.
> demoting a statement to an expression. Which is what I was trying to do.

That's the key. A function is a way to wrap a sequence of statements (the function body) so it can be used in an expression (a function call). Because JavaScript lets you define functions (with full statement syntax) in expressions, that gives you a way to "demote" an expression inline, while Python can only do so out-of-line. At the core, this is what all of the multiline lambda attempts and similar proposals are trying to accomplish.

More information about the Python-ideas mailing list