a = b = 1 just syntactic sugar?

Ed Avis ed at membled.com
Mon Jun 9 15:00:09 EDT 2003


"Terry Reedy" <tjreedy at udel.edu> writes:

>>That would be an incompatible change. Currently
>>x = lambda:2
>>print x()
>>prints "2". Under your change, this would be the same as
>>def anon():
>>  2
>>x = anon
>>print x()

[one of three ways to resolve this]

>3) adding the return-deleted template as an alternative, with the
>compiler choosing the 'correct' version.  As things stand, this is
>problematical (ambiguous) because, as Martin noted in another post,
>expressions are (a subset of) expression-lists are
>expression_statements are (a subset of) simple_statements.  I believe
>disambiguation would require new grammar productions for
>multiple_expression_list and non_expression_simple_statement and
>corresponding revision of expression_list and simple_statement.

Yes, it might.  Or it might be possible to set some flag for 'please
save the return value of an expression used as an expression_stmt,
rather than throwing it away', and set this flag while executing the
body of a lambda function, returning the value given.  Then no need
for a further grammar change.  But I need to look at the code.

>(Whether the result would still be LL(1) remains to be tested.)

I do not know whether the change to allow simple_stmt inside lambda
would keep the grammar LL(1).  However, a simple splitting of the
existing simple_stmt production into two different cases would not
change the strings produced by the grammar or its LL(1)-ness.

>Choice 3) would complexify the meaning (translation) of lambda to
>depend on the nature of the body.

Yes, because although you could write

    f = lambda x: x + 1

and get a return value from f(), you would get different results from

    def f(x):
      x + 1

So the surprise of 'hmm, putting x[0] = 5 in my lambda function body
doesn't seem to work' has been replaced by the surprise of 'hey, why
isn't a value being returned from my function, it worked fine as a
lambda'.  I think this is probably a smaller inconsistency in the
language but it is a matter of opinion.

(FWIW, maybe it would be a good idea for an error to be raised if you
try to get the return value of a function that did not have a return
statement, rather than getting the default None as at present.  If you
write 'x = f()' then this shows an expectation that f is a function
returning a value, not a mere procedure which finishes execution with
no return statement.)

-- 
Ed Avis <ed at membled.com>




More information about the Python-list mailing list