[Python-ideas] Syntax: 'return: ...' expressions
MRAB
python at mrabarnett.plus.com
Wed Jan 7 04:41:24 CET 2015
On 2015-01-07 02:08, Yawar Amin wrote:
> On 2015-01-06 03:25, Andrew Barnert wrote:
>> [...]
>> I think you're missing another important point here: statements and
>> expressions are different things. Blocks are made up of statements,
>> not expressions, ...
>
> Actually I can offer counter-examples to that:
>
> def p(x): print x
> class A: p("Hello!")
> class B: 1
> # Etc.
>
> 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.
> I _still_ think at least something like the following would work (in
> terms of Python's grammar[1]):
>
> expr_expr: 'expr' ':' small_stmt (';' small_stmt)* [';' expr]
>
> So e.g.:
>
> x = expr: import os; os.system("date")
>
[snip]
In BCPL, the body of a routine can be only a single statement, but that
statement can be a block:
LET foo() BE
$(
....
$)
Similarly, the body of a function can be only an expression, but that
expression can include VALOF. VALOF is followed by a block, and the
value of VALOF is given by the expression after RESULTIS:
LET foo() = VALOF
$(
...
RESULTIS ...
...
$)
Of course, in Python, the block would be indented, so it's not entirely
suitable, but you could imagine this:
x = valof:
import os
resultis os.system("date")
I think you're better off using a function instead!
More information about the Python-ideas
mailing list