[Edu-sig] Using try / except: any stipulations against routine use?
Sarina Canelake
sarina at MIT.EDU
Tue Dec 13 22:39:52 CET 2011
I enjoy your explanation. I have recently written something very similar to
one of my students.
We teach dictionaries about three weeks before exception handling, though,
so I rarely see this code.
On Tue, Dec 13, 2011 at 4:30 PM, Kirby Urner <kurner at oreillyschool.com>wrote:
> Below is typical feedback to a student.
>
> What do others think regarding my discussion of using try /except
> in routine dict manipulation?
>
> Kirby
>
>
> ===
>
> Yes perfect. Good work.
>
> try:
> res_dict[ext] += 1
> except KeyError:
> res_dict[ext] = 1
>
> This code is not atypical and you'll find some polarization among
> Pythonistas about whether this is good style. Another construct:
>
> res_dict[ext] = res_dict.get(ext, 0) + 1
>
> is the one I favor. I think of a "key not found" event
> in a dict as "routine, to be expected" whereas I think of
> try: / except: as for "crying wolf" (not for everyday
> contingencies). The opposite bias is: why make that
> distinction, try: / except: is a perfectly reasonable
> construct for trapping a new key to a dict.
>
> In any case, good Python.
>
> -Kirby
> _______________________________________________
> Edu-sig mailing list
> Edu-sig at python.org
> http://mail.python.org/mailman/listinfo/edu-sig
>
--
Sarina Canelake
MIT EECS
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20111213/60f51e48/attachment.html>
More information about the Edu-sig
mailing list