Python - 从可能返回 None 的函数中设置变量的安全且优雅的方法

标签 python python-2.7

我正在寻找一种更优雅的方法来声明变量值,其中函数可能返回 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/

相关文章:

python - 获取任意长度的列表元素的所有可能 (2^N) 组合

python - 使用 Regex + BeautifulSoup 抓取 XML 并存储到 Pandas

python - 在字符串中搜索并获取Python中匹配前后的2个词

java.lang.ClassNotFoundException : org. openx.data.jsonserde.JsonSerDe 错误

python - 尝试写入文件,但收到错误消息,指出写入需要文件对象而不是字符串

python - 如何显示django类别名称而不是Category对象(一)

python - 使用 Python 编写图像

python - 在文件输入循环中如何将标准输出重定向到控制台

python - 使用Python套接字的RFID(低级命令)

Python PEP8 约定