[Tutor] understanding pydoc try

Dave Angel d at davea.name
Thu Aug 30 16:05:27 CEST 2012


On 08/30/2012 09:30 AM, John Maclean wrote:
> What does the first line from `pydoc try` actually mean? This does not
> look like the syntax that one is supposed to use.
>
> try_stmt  ::= try1_stmt | try2_stmt
>
You're looking at the first of three BNF statements.  BNF (Backus Naur
Form, or something like that) is a way of describing a grammar.  i'll
quote the whole thing here, and try to explain it.

The following is from Python 3.2's pydoc:

   try_stmt  ::= try1_stmt | try2_stmt
   try1_stmt ::= "try" ":" suite
                 ("except" [expression ["as" target]] ":" suite)+
                 ["else" ":" suite]
                 ["finally" ":" suite]
   try2_stmt ::= "try" ":" suite
                 "finally" ":" suite

The first statement says that a try_stmt is one or the other of two
formats.  This simply says there are two syntaxes you can use, depending
on what try features you want.

The second lists the (most common, i expect) syntax.  It has a literal
try token, followed by a literal colon token, followed by a suite of
statements (that's defined elsewhere, but would include simple
statements, if statements, and so on.  It wouldn't include def or class,
presumably).

Then there are one or more except clauses.  Note the trailing + which
means this element may be repeated, but must be present at least once.

Then there is an optional else clause.

Then an optional finally clause.

These must be present in the specific order stated above.  And you can't
(for example) have an else without an except, because except is one or
more times.

The second syntax does not include the except nor else clauses.

Is that clearer?

-- 

DaveA



More information about the Tutor mailing list