[Edu-sig] Using try / except: any stipulations against routine use?
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?
> Yes perfect. Good work.
> 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.
> Edu-sig mailing list
> Edu-sig at python.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Edu-sig