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?
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 yourfoobarwhich behaves identically without explicitly returningNone: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.