if / try

Jay Dorsey jay at jaydorsey.com
Thu Oct 2 09:56:45 EDT 2003


vald wrote:
...
>     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?

If you're just trying to get the value or None from an dictionary, you 
could also try this:

 >>> n = {'test':1, 'blah':2}
 >>> repr(n.get('test'))
1
 >>> repr(n.get('asdf'))
'None'

I just got the Python Cookbook and this was in it.  If I'm 
misunderstanding the question I apologize.

Jay

<apologies for the personal reply as well, I meant to send this just to 
the list>






More information about the Python-list mailing list