[Edu-sig] Using try / except: any stipulations against routine use?

Vernon Cole vernondcole at gmail.com
Thu Dec 15 01:24:12 CET 2011


> Isn't this at least as readable, and conceptually simpler?
>
>   if ext in res_dict:
>       res_dict[ext] += 1
>   else:
>       res_dict[ext] = 1
>
> Not arguing against exceptions in general, but in this case?
>
> - Bert -

Yes, it is readable -- but more resource intensive -- since I have to
access the dictionary twice, once to see if the key is there, and
another to adjust or define the value.

If I use try / except, then I will usually only have to access the
dictionary a single time, with a second dip only if the key did not
exist. A clear win for using exceptions.

Incidentally, the .get() one liner also does two dictionary accesses,
rather than one (since it can't use the += operator, the get() and the
update/define are separate operations.)
"Less lines" does not necessarily mean "runs faster."  Dictionary
lookups are a somewhat expensive operations.
--
Vernon


More information about the Edu-sig mailing list