Function to convert fetchone() result from a list to a dictio nary

Alex Martelli aleax at aleax.it
Tue Apr 29 18:34:16 CEST 2003


sismex01 at hebmex.com wrote:

>> From: Alex Martelli [mailto:aleax at aleax.it]
>> Sent: Tuesday, April 29, 2003 4:09 AM
>> 
>> So here's a step-by-step version (using SPACES, not TABS:-)...:
>> 
>> def cfd(cursor):
>>     values = cursor,fetchone()
>>     if values is None:
>>         return None
>>     keys = [d[0] for d in cursor.description]
>>     result_dict = dict(zip(keys, values))
>>     return result_dict
>>
> 
> I don't think there's need to explicitly return None,

No, there isn't.  However, stylistically speaking, I
*HATE* functions that along some execution paths have
explicit "return <expr>" statements and along others
have bare "return" or "just fall off the end" -- in my
code-maintenance experience, such functions are just
too likely to have bugs due to the original developer
having _ignored_ the possibility of alternate execution
paths -- so every time I find myself examining one,
I need to look at it long and hard to make SURE the
coder's intentions are indeed exactly expressed.

MUCH better to have an *explicit* "return None" along
the execution paths that really want to do that, MOST
particularly when that aspects of a function's specs
is so anti-intuitive as here (why None when it seems
SO much more natural to return an empty dict!? -- must
be a very explicit specification mandating it, I guess).

> nor to assign result_dict only to immediately return

Absolutely -- that, as I explained, was a didactical
device, to help a newbie understand better what was
going on.  I do prefer "return dict(..." etc myself.

> it, but then, that's just me ;-)
> 
> 
> def cfd(cursor):
>     values = cursor.fetchone()
>     if values:

Are you sure that the specs of cursor.fetchone() make
it IMPOSSIBLE that it returns e.g. an empty list or
tuple?  If that happens, this function is buggy in the
sense that it doesn't implement the same semantics as
the original one -- the original one would return an
empty dict when cursor.fetchone() returned an empty
sequence, this one would return None instead then.

I consider it horrid style to check "if values:" when
what one REALLY means is "if values is not None:".

>         keys = [d[0] for d in cursor.description]
>         return dict(zip(keys,values))

Sure, this part is OK (and suggested it myself as my
own preferred alternative in a followup).


>> Of course, you can bunch this up more, or less, according to
>> taste -- whatever you find clearest and most readable.  E.g.,
>> the last three lines could be instead:
>> 
>>     return dict(zip([d[0] for d in cursor.description],values))
>> 
>> if you're into one-liners!-)
> 
> Ach! But Perly stuff is so unmaintainable... ;-)

Yes, excessive terseness can damage maintenability.  But so
can the lack of explicitness, particularly about None!-)


Alex





More information about the Python-list mailing list