assigning variables from list data

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Aug 6 09:49:32 CEST 2010


Chris Hare a écrit :
> I have a database query result (see code below).  In PHP, I would have said
> 
> list(var1,var2,var) = $result

Other already answered on the Python equivalent. But there's an IMHO 
better way, which is to use (if the DB-API connector provides it) a 
DictCursor, that yields dicts instead of tuples.

> 
> import sqlite3 as sqlite
> 
> try:
> 	print "connecting to disk db ..."
> 	conn = sqlite.connect("netcomm.db")
> except:
> 	print "oops"


OT, but do yourself a favor and remove this try/except. Sorry to have to 
say but it's about the most stupidiest error handling scheme you could 
think of. Seriously.

Ask yourself : what will happens if sqlite.connect raises AND you don't 
catch the exception ? Yes, the script will stop right here - which is 
what you want anyway - AND you will have an error message giving you 
informations about what went wrong, and a full traceback. IOW, you'll 
have as much helpful debugging infos as possible at this point.

Now what will happen with your current code ? Instead of an informative 
error message, you have a "oops". Well, really helps. Then your script 
will go on, print "retrieving data", and you can bet your ass it'll 
crash on the next line - "cursor = conn.cursor()", that is - with a very 
less informative error message, and you'll wonder why.

Also, be warned that SysExit and KeyboardInterrupt are also exceptions. 
The one you may NOT want to catch and dismiss.

To make a long story short:

1/ only catch exceptions you can *and* want to handle
2/ never assume anything about what caused the exception
3/ not exception handling is better than a wrong exception handling.

HTH



More information about the Python-list mailing list