Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:
        return 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?

like image 948
Aufwind Avatar asked May 14 '11 07:05

Aufwind


People also ask

How do you avoid None output in Python?

Run this code: print(print("Hi")) The output is: Hi None The inner print function sends "Hi" to the console but doesn't return anything, i.e returns None, which the outer function sends to the console. Python It's simple, if your function doens't have any return value then the function will return None.

How do I return nothing instead of None in Python?

If you want to return a null function in Python then use the None keyword in the returns statement. Example Python return null (None). To literally return 'nothing' use pass , which basically returns the value None if put in a function(Functions must return a value, so why not 'nothing').

Why is my Python function returning None?

Functions often print None when we pass the result of calling a function that doesn't return anything to the print() function. All functions that don't explicitly return a value, return None in Python.

Should you explicitly return None in Python?

Like you said, return None is (almost) never needed. But you should consider that the intention of your code is much clearer with an explicit return None . Remember: a piece of code also needs to be readable by human-beings, and being explicit usually helps.


1 Answers

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.

like image 66
Håvard S Avatar answered Oct 05 '22 12:10

Håvard S