Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - safe & elegant way to set a variable from function that may return None

I'm looking for a more elegant way of declaring a variable value where the function may return None and there are chained methods following the function call.

In the example below I am using BeautifulSoup to pass an HTML doc and if the element I am looking for is not found, the initial function call returns None. The chained methods then break the code because .string is not a method of None object.

Which all makes sense, but I'm wondering if there's a cleaner way to write these variable declarations that won't break on a None value.

# I want to do something like this but it throws error if soup.find returns
# none because .string is not a method of None.
title = soup.find("h1", "article-title").string or "none"


# This works but is both ugly and inefficient
title = "none" if soup.find("h1", "article-title") is None else soup.find("h1", "article-title").string

# So instead I'm using this which feels clunky as well
title = soup.find("h1", "article-title")
title = "none" if title is None else title.string

Any better way?

like image 914
patnz Avatar asked Apr 06 '15 20:04

patnz


1 Answers

I like Shashank's answer, but this might work for you as well:

class placeholder:
    string = "none"

title = (soup.find("h1", "article-title") or placeholder).string
like image 94
1.618 Avatar answered Sep 21 '22 13:09

1.618