On Tue, Mar 22, 2016 at 11:31 AM, Ben Bacarisse <ben.use...@bsb.me.uk> wrote:
> However, the explanation ("because Python’s syntactic framework can't
> handle statements nested inside expressions") seemed, at first, to be
> saying you can't because you can't!  But the term "syntactic framework"
> hints that it's not really just an arbitrary choice -- that this is
> something about the way Python is parsed that make this choice
> inevitable.  Is it to do with the way that indentation has a syntactic
> role?
>
> To phrase my question in terms of syntax, why is the : in lambda
> followed by a test (the top-level production for an expression in the
> grammar) but the : in a function definition is followed by a suite?  I
> expected them to be both a suite, but presumably something goes horribly
> wrong if that were done.  Now I'm wondering what.

A "suite" is a series of statements - in common parlance, a block of
code. A "test" is a type of expression (there are a variety of these
kind of things, and they define operator precedence).

Part of the trickiness of permitting statements inside expressions is
that it would get confusing - not that it'd be truly ambiguous and
impossible to parse, but that small errors could result in peculiar
misinterpretations of subsequent code, which means the error messages
would be harder to understand. There are already a few places like
that:

functioncall( # ) # oops, forgot the close parenthesis
name = value
othername = othervalue

You'll get a SyntaxError on the last line, despite it being
functionally identical to the second. And it's just "invalid syntax",
the most completely unhelpful message. (This situation is considered
worthwhile, though. Named arguments and assignment both make way too
much sense to break one of them.) Now imagine if every "lambda" in the
code could result in the same kind of thing; currently, the keyword
"lambda" must be followed by a (possibly empty) argument list and then
an expression, which must either be entirely within one line, or have
parentheses around it. If, instead, "lambda x:" introduced a suite,
you'd have errors coming up much further down.

Having full statement syntax inside an expression isn't always even a
benefit. It's often a major cost to readability - just have a look at
a big pile of JavaScript callback code some time. (Although, to be
fair, function() {...} isn't the only readability problem there.) And
it has a debugging cost that gets significantly higher when you don't
have braces to delimit blocks.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to