2007/5/8, [EMAIL PROTECTED] <[EMAIL PROTECTED]>: > I'm working my way through the book "beginning python" and I came across an > exercise that suggests using Exception trapping to see if a value is in a > dictionary: > > fridge={"apple":"A shiny red apple","pear":"a nice ripe > pear","grapes":"seadless grapes"} > food_sought="apple" > fridge_list=fridge.keys(); > try: > print "The fridge contains %s" %fridge[food_sought] > except (KeyError): > print "The fridge does not contain %s"%food_sought > > I'm fairly certain the book is in error in calling this a "short-cut" since > the has_key method is much less verbose to use,
Is it? if fridge.has_key(food_sought): foo else: bar doesn't look much less verbose than: try: foo except (KeyError): bar > but it brings up a question about exceptions in general: > > In Java using exceptions in the way shown above is a classic anti-pattern > since Exceptions should only be used for..well exceptional conditions. > > Is the same true of Python? Or is ok to use Exception handling like the book > suggests? Exceptions are in general much more freely used in Python than in most other languages, it's called the "EAFP" (It's easier to ask forgiveness than to get permission) style, instead of the "LBYL" (look before you leap) style most other languages use. -- Andre Engels, [EMAIL PROTECTED] ICQ: 6260644 -- Skype: a_engels _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor