if / try

Stephen Horne $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk
Thu Oct 2 22:15:24 EDT 2003


On Thu, 2 Oct 2003 15:29:50 +0200, vald <vald at valis.amber.eu.org>
wrote:

>
>I wonder if there is any difference in using
>if/else and try/except when checking some
>return values in functions. For example:
>
>    def getValue(self):
>        try:
>            return self.values["SOME_VALUE"]
>        except KeyError:
>            return None
>
>    def getValue2(self):
>        if self.values.has_key("SOME_VALUE"):
>            return self.values["SOME_VALUE"]
>        else:
>            return None
>
>Is there any preformance gain when using one of
>those methods? Which one should be widely used
>in applications in such kind of methods that just
>check whether something is valid and return value 
>or None?

What I would expect (I don't know for sure) is that for most
applications the 'if' version would be faster.

If the key is almost always present, however, the 'try' version may be
faster.

The reasoning relates to purpose - exceptions are intended to handle
exceptional events. I would expect the language designers to implement
it so that overheads in the no-exception case were minimised, whereas
an 'if' should be handled in a much more balanced way with neither the
True nor False case being prioritised.

In this special case, though, you are probably better off using the
'get' method of the dictionary...

  dict.get (key, default)  - return default if key not in dictionary
  dict.get (key)           - return None if key not in dictionary


-- 
Steve Horne

steve at ninereeds dot fsnet dot co dot uk




More information about the Python-list mailing list