Using try / except: any stipulations against routine use?
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
On 12/13/2011 04:30 PM, Kirby Urner wrote:
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.
More evidence for the "perfectly reasonable": Iterators are implemented with the StopIteration exception. You can find a few other examples in the language for things like that. I think it's perfectly reasonable myself. -- Corey Richardson
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@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@python.org http://mail.python.org/mailman/listinfo/edu-sig
-- Sarina Canelake MIT EECS
participants (3)
-
Corey Richardson
-
Kirby Urner
-
Sarina Canelake