开发者

Which style of return is "better" for a method that might return None?

开发者 https://www.devze.com 2023-01-03 06:29 出处:网络
I have a method that will ei开发者_高级运维ther return an object or None if the lookup fails. Which style of the following is better?

I have a method that will ei开发者_高级运维ther 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 dict method get is the most concise:

def get_foo(needle):
    haystack = object_dict()
    return haystack.get(needle)

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 :)


if both do exactly the same, choose that one that you like the most and thats more readable - i like the second one, but both are good.

(maybe one if this is faster than the other one - so if preformance is realy important, test it and choose the faster one)


In every language I've used the first version is perferable. Exceptions are basically goto's in disguise with many of the same problems, so I don't use them if I can avoid it.

There is also a possible performance cost. I don't know about Python, but in many other languages there is a heavy cost for creating the exception that you are going to throw away on the next line.

0

精彩评论

暂无评论...
验证码 换一张
取 消