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

Kirby Urner kurner at oreillyschool.com
Tue Dec 13 22:30:46 CET 2011


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


More information about the Edu-sig mailing list