I have a function which connects to a url by httplib
using lxml
. It checks by xpath
for 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?
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.
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').
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With