Scope of variable inside list comprehensions?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Dec 5 17:35:06 EST 2011


On Mon, 05 Dec 2011 19:57:15 +0100, Jean-Michel Pichavant wrote:

> The proper way to propagate information with exceptions is using the
> exception itself:
> 
> try:
>     songs = [Song(_id) for _id in song_ids]
> except Song.DoesNotExist, exc:
>     print exc


I'm not entirely sure that this is the proper way to propagate the 
exception. I see far to many people catching exceptions to print them, or 
worse, to print a generic, useless message like "an error occurred".

The problem here is that having caught the exception, songs now does not 
exist, and will surely cause another, unexpected, exception in a moment 
or two when the code attempts to use it. Since the error is (apparently) 
unrecoverable, the right way as far as I can see is:

songs = [Song(_id) for _id in song_ids]

allowing any exception to be fatal and the traceback to be printed as 
normal.

If the error is recoverable, you will likely need to do more to recover 
from it than merely print the exception and continue.



-- 
Steven



More information about the Python-list mailing list