Reputation: 3898
I have a function called crawl
which will return a link to a website. Then I do something like:
found.append(crawl())
(found is a list)
This works fine as long as crawl returns a valid link, but sometimes it does not return anything. So a value of None
gets added to the list.
So my question is that, is it possible to return something from crawl
that will not not add anything to the list?
Upvotes: 2
Views: 2051
Reputation: 2973
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.
Upvotes: 1
Reputation: 28370
What you could do is to pass the list in to the crawl function and if there is anything to add append it otherwise not. Something like:
def crawl(found):
""" Add results to found list """
# do your stuff saving to result
if result is not None:
found.append(result)
# Call this as
crawl(found)
Upvotes: 2
Reputation: 3209
This is not possible directly.
You can test for a None
being returned though, using the following code.
returned_link = crawl()
if returned_link is not None:
found.append(returned_link)
Upvotes: 1
Reputation: 42758
In Python nothing is something: None
. You have to use if-condition:
link = crawl()
if link is not None:
found.append(link)
or let crawl
return a list, which can contain one or zero elements:
found.extend(crawl())
Upvotes: 10