Which style of return is "better" for a method that might return None?
- by Daenyth
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.