[Tutor] Newbie Question on Exceptions...

Bob Gailer bgailer at alum.rpi.edu
Tue May 8 21:05:01 CEST 2007


dsh0105 at comcast.net wrote:
> 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
Perhaps the version of Python, when the book was written, did not have 
has_key?
Less verbose? Let's see - if I do a straightforward translation I get:

if fridge.has_key(food_sought):
    print "The fridge contains %s" %fridge[food_sought]
else:
    print "The fridge does not contain %s"%food_sought

That's 2 less words!

But consider (same word count but even easier to read):

if food_sought in fridge:

> 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.  
>   
Ah the dreaded "should". Who says? But then in Java exception handling 
is more complex, and avoiding it seems a good idea.
> Is the same true of Python? Or is ok to use Exception handling like the book suggests?
>   
Since there is no one on the Python side saying "should" (AFAIK) I can 
only opine: use whatever gets the job done, is readable and maintainable.

Many things can be tested for with ease. But consider when you use 
raw_input to get a string, and you want to accept it only if it will 
convert to float. The only easy way I know is to use the float() 
function inside a try:. If you wanted to test it without try: you'd have 
to write a regular expression for floating point syntax and use re. Not 
as easy or readable.

-- 
Bob Gailer
510-978-4454



More information about the Tutor mailing list