Which style of return is "better" for a method that might return None?
Posted
by Daenyth
on Stack Overflow
See other posts from Stack Overflow
or by Daenyth
Published on 2010-06-15T05:03:26Z
Indexed on
2010/06/15
5:12 UTC
Read the original article
Hit count: 232
I have a method that will either return an object or None
if the lookup fails. Which style of the following is better?
def get_foo(needle):
haystack = object_dict()
if needle not in haystack: return None
return haystack[needle]
or,
def get_foo(needle):
haystack = object_dict()
try:
return haystack[needle]
except KeyError:
# Needle not found
return None
I'm undecided as to which is more more desirable myself. Another choice would be return haystack[needle] if needle in haystack else None
, but I'm not sure that's any better.
© Stack Overflow or respective owner