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?
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
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