[Tutor] understanding pydoc try

Steven D'Aprano steve at pearwood.info
Thu Aug 30 16:09:19 CEST 2012


On 30/08/12 23:30, 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


That's a description of the Python grammar in some variation of
Backus-Naur Form. In English, it means:

A "try statement" is either a "try1 statement" or a "try2 statement".

Presumably then there will be a definition of try1_stmt and try2_stmt,
also in BNF form, probably in terms of other statements, until
eventually the syntax of try statements is fully defined.

http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form#Example

http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form


> I can write simple statements as shown below, but I want to actually understand what I am doing.
>
>
>
> try:
>     import io
>     print("importing io")
> except ImportError:
>     print("nothing to import")
>     foo = None

This first block attempts to import the "io" module, and then print
"importing io". If the import process fails, an exception is
raised. But since the io module does exist and can be imported,
nothing happens and execution happily goes on to the part *after*
the except clause:


> try:
>     import somefunctionthatdoesnotexist
>     print("importing ...")
> except ImportError:
>     print("nothing to import")
>     foo = None


This time, since "somefunction blah blah" probably doesn't exist, the
import process does fail, and an exception is raised, interrupting
normal execution of the code. Instead of the next line running,
execution of your code halts and Python signals an ImportError.

However, then the "except ImportError" line takes over and catches
the exception. "nothing to import" is printed and foo is set to None.


Does that help?



-- 
Steven


More information about the Tutor mailing list