Fabio Z Tessitore wrote:
reading Dive Into Python, on Chapter 6 (exception), I've found:
"This code comes from the getpass module, a wrapper module for getting a
password from the user"
****************try:
************************from EasyDialogs import AskPassword
****************except ImportError:
************************getpass = default_getpass
****************else:
************************getpass = AskPassword
Knowing that this code is very simple, my question is about simplicity. I
think it is simpler the following code. I haven't a long experience on
Python, so I'd like to know your opinions about.
>
****************try:
************************from EasyDialogs import AskPassword
************************getpass = AskPassword
****************except ImportError:
************************getpass = default_getpass
I think you are asking the wrong question. The difference between these two
functionally equivalent snippets is in expressiveness rather than
simplicity.
The first can be read as
try:
<operation that may fail>
except <Error I can handle>:
<fix it>
else:
<build on successful operation>
When you move the else suite into the try...except
try:
<operation that may fail>
<build on successful operation#
except <Error I can handle>:
<fix it>
you blur the difference between <operation that may failand <build on
successful operationwhile at the same time introducing the implicit
constraint that the latter does not fail with <Error I can handle>.
Therefore the original code gives the reader a much clearer notion of the
author's intention. This may not be a problem for the simple code at hand
but is definitely a bad habit to get into.
Peter