我正在寻找一种更优雅的方法来声明变量值,其中函数可能返回 None
并且在函数调用之后有链式方法。
在下面的示例中,我使用 BeautifulSoup 传递 HTML 文档,如果未找到我要查找的元素,初始函数调用将返回 None
。链式方法随后会破坏代码,因为 .string
不是 None
对象的方法。
这一切都说得通,但我想知道是否有一种更简洁的方法来编写这些不会在 None
值上中断的变量声明。
# 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
有什么更好的方法吗?
最佳答案
我喜欢 Shashank 的回答,但这也可能对你有用:
class placeholder:
string = "none"
title = (soup.find("h1", "article-title") or placeholder).string
关于Python - 从可能返回 None 的函数中设置变量的安全且优雅的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29478845/