if / try

V

vald

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?

Regards,
Kamil
 
S

Stephen Horne

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top