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

Eugene Toder eltoder at gmail.com
Tue Jan 6 20:35:54 CET 2015

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, and
statements don't have values. This is the reason, for example, for
having the ?: operator, and for having statement expressions in GNU C
[1]. This separation is common in C-like languages. Some C-like
languages that have REPL invent a rule for statement values similar to
Python's REPL.

> 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.

[1] https://gcc.gnu.org/onlinedocs/gcc-3.1/gcc/Statement-Exprs.html

More information about the Python-ideas mailing list