If a function returns it has to return an object, even if that object is None
. However, there is another answer being overlooked, and that is to raise an exception rather than returning None
.
As other people point out, one approach is to check if the returned object is None
before appending it to the list:
link = crawl()
if link is not None:
found.append(link)
The other approach is to define some exception, perhaps WebsiteNotFoundError
, and have crawl
execute raise WebsiteNotFoundError
instead of return None
. Then you can write:
try:
found.append(crawl())
except WebsiteNotFoundError:
pass # or take appropriate action
The advantage of the exception handling approach is that it is generally faster than checking for None
if returning None
is a relatively rare occurrence compared to returning a valid link. Depending on the use, it may be more readable in the sense that the code naturally explains what is going wrong with the function.