Nested compound statements.
Neil Cerutti
mr.cerutti at gmail.com
Fri Feb 1 14:03:08 EST 2008
The docs say:
A suite can be one or more semicolon-separated simple statements on
the same line as the header, following the header's colon, or it can
be one or more indented statements on subsequent lines. Only the
latter form of suite can contain nested compound statements; the
following is illegal, mostly because it wouldn't be clear to which if
clause a following else clause would belong:
if test1: if test2: print x
What's the rest of the reason? Is it an LL(1) parser limitation?
The error came to my attention through:
with nested(open(args[0], "rb"),
open(args[1], "rb")) as (banner, pfaids):
if outfile_path is None:
report(sys.stdout, reconcile(banner, pfaids))
else: with open(outfile_path, "w") as outfile:
report(outfile, reconcile(banner, pfaids))
Instead I must write:
with nested(open(args[0], "rb"),
open(args[1], "rb")) as (banner, pfaids):
if outfile_path is None:
report(sys.stdout, reconcile(banner, pfaids))
else:
with open(outfile_path, "w") as outfile:
report(outfile, reconcile(banner, pfaids))
There's nothing terribly wrong with it, I guess, but it does look
"hairier" when really it isn't.
Moreover, "invalid syntax" is a bit terse--but probably it's not worth
it to complicate the grammar just for a better error message.
Finally, any ideas for a prettier version of the above snippet?
--
Neil Cerutti <mr.cerutti+python at gmail.com>
More information about the Python-list
mailing list