[Python-ideas] Commas [was Re: except expression]

Steven D'Aprano steve at pearwood.info
Tue Feb 18 22:41:28 CET 2014


On Tue, Feb 18, 2014 at 06:19:28PM +1300, Greg Ewing wrote:
> Alexander Belopolsky wrote:
> >Funny: less than an hour ago, I paused when writing a lambda to return a 
> >tuple.  I conservatively put parentheses around the tuple and did not 
> >bother  to check if they are required.  Now I know that they are.
> 
> It's even more confusing when you consider that
> you can write
> 
>    lambda x, y: x + y, 2
> 
> and the first comma doesn't break up the lambda,
> but the second one does!

It shouldn't be confusing. It would be confusing if the expression was 
broken up in this way:

    (lambda x), (y: x+y), 2

since it is semantically meaningless. The parser here does the right 
thing, parsing an expression in a way that is semantically sound.


> With oddities like this already in the language,
> I don't think we need to worry too much about the
> corner cases.

But the corner cases could include bugs in the parser, at least 
theoretically, as well as bugs in people's code. And that is definitely 
not theoretical. For example, the old form of try...except blocks was a 
terrible bug magnet:

    try:
        stuff()
    except ValueError, error:
        print error.arguments



People would write:

    except ValueError, TypeError:

and the caught ValueError would be bound to the name TypeError, instead 
of catching TypeError.


> People are always free to insert parens
> to make things clearer. E.g. I would probably write
> the above as
> 
>    (lambda (x, y): x + y), 2

Well, you could try to, but it won't work in Python 3. That's a 
SyntaxError.



-- 
Steven


More information about the Python-ideas mailing list