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

Andrew Barnert abarnert at yahoo.com
Wed Jan 7 05:43:49 CET 2015

LOn Jan 6, 2015, at 14:35, Eugene Toder <eltoder at gmail.com> wrote:

> On Tue, Jan 6, 2015 at 3:25 AM, Andrew Barnert
> <abarnert at yahoo.com.dmarc.invalid> wrote:
>> I think you're missing another important point here: statements and expressions are different things. Blocks are made up of statements, not expressions, and statements don't have values. This is different from many other languages like C, Ruby, or JavaScript, where as many things as possible are expressions (and therefore have values), so a block is (oversimplifying a bit) just a sequence of expressions separated by semicolons and stuck inside braces, and therefore it has a last value.
> Statements and expressions are separate in C and Javascript,

Well, obviously; otherwise "as many things as possible are expressions" would be pointless.

In C, unlike Python (and, more to the point, unlike many of C's predecessors), assignment, augmented assignment, and increment are expressions. Different languages have since taken that farther: Ruby makes most flow control into expressions, JavaScript makes function definitions into expressions (which means you can wrap any statement in an expression by defining and calling a function around it), CoffeeScript makes everything but return, continue, and break into expressions.

>> One type of statement, the expression statement, is just an expression on a line by itself (or between semicolons), so you _could_ invent a rule pretty easily that expression statements have the value of their expression, and all other statements have a value of None, and a block has the value of its last statement. This is basically the same rule used by the interactive REPL for displaying the repr of what you've typed and setting the _ variable, so it wouldn't be a huge stretch to add the same rule to the language itself--but it would still be a new rule, and a significant change to the internals of the interpreter, even though it would only be useful in this new context.
> I don't think one needs to invent this rule in the context of this
> idea. All that is needed is to end the "return expression" (or
> whatever you want to call it) with an expression rather than a
> statement (i.e. return_expr ::= "keyword" statement* expression). The
> value of this last expression is the value of the whole thing.

That's equivalent to arguing that function bodies don't need return, break, or continue, because you can theoretically write anything to fall off the end. 

I'm assuming that the OP wanted something that works intuitively similar to other languages, the REPL, etc.--e.g., if the last statement executed is in the true block of an if/else, it doesn't matter that it's not textually the last statement.

More information about the Python-ideas mailing list