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.
For this particular example, it looks like the
dictmethodgetis the most concise:In general, in Python, people tend to prefer try/except than checking something first – see the EAFP entry in the glossary. Note that many “test for membership” functions use exceptions behind the scenes.
I won’t start a flamewar on the relative merits of multiple returns or the alternatives 🙂