开发者

`return None` in python not recommended. How to bypass?

开发者 https://www.devze.com 2023-03-06 08:21 出处:网络
I have a function which connects to a url by httplib using lxml. It checks by xpathfor a certain pattern and if the check is positive it returns a string. But if the check was negative it returns noth

I have a function which connects to a url by httplib using lxml. It checks by xpathfor a certain pattern and if the check is positive it returns a string. But if the check was negative it returns nothing.

Now the situation is, that my function returns None. I call the function, check if its return value is not None and continue in the code.

An example:

def foobar(arg):
    # connect to page by httplib
    # check for arg in a certain pattern by lxml
    if check:
        r开发者_StackOverflow社区eturn result
    else:
        return None

result = foobar(arg)
if result:
    # do stuff
else:
    # do other stuff

Recently I read, that this is a no go. How do I avoid such situations?


There is nothing wrong with returning None.

In most cases, you don't need to explicitly return None. Python will do it for you. This is an altered version of your foobar which behaves identically without explicitly returning None:

def foobar(arg):
  if check:
    return result
# If not check, then None will be returned

Still, even if Python implicitly returns None, there is a value in being explicit; Your code becomes easier to read and understand. This is a constant trade-off for which there is no general answer.


It depends on why it's a "no go"; I haven't heard that. If it's just bad form, omit the "return None" (the else statement) altogether, and it will return None by default. If it's considered bad to return None, return 0 or '' (empty string) or False instead, depending on the type expected by the caller.


There are many styles of dealing with this, including using exceptions or just returning whatever you get, including a blank string. This is fine too:

def foobar(arg):
    ...
    if check:
        return result

result = foobar(arg)
if result is not None:
    # do stuff
else:
    # do other stuff


I think returning None is a "no go" from a usability standpoint rather than style. As briefly mentioned in this answer, consider raising an exception instead. For example:

def foobar(arg):
    # connect to page by httplib
    # check for arg in a certain pattern by lxml
    if not check:
        raise ValueError("arg did not match pattern in lxml")         
    return result

try:
    result = foobar(arg)
except ValueError:
    result = None

if result is not None:
    # do stuff
else:
    # do other stuff

The advantage of this approach is that it makes it explicit when there is not a match. Other people using your function won't need to know that None is the return value they should expect when there isn't a match and they can handle the exception as they see fit.

0

精彩评论

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