Python中 if query 和 if query is not None 有区别吗?
foo = Item.query.filter(…).first()
if foo,和 if foo is not None 有区别吗?
自己常用 if foo,看到一些代码里有用 if foo is not None,有特别的地方吗?否则 if foo 简单多了
Python中 if query 和 if query is not None 有区别吗?
可读性。
有区别,关键看 query 是什么。
if query 检查的是对象的“真值”。在Python里,None、False、0、空字符串''、空列表[]、空字典{} 等都被视为“假”。所以如果 query 是空字符串 '',if query 会判断为 False。
if query is not None 是严格的身份比较,只检查 query 是不是 None 这个特定的对象。即使 query 是 0、False 或 '',只要它不是 None,这个条件就为 True。
主要区别场景:
- 你想允许“假值”但排除
None:比如函数参数,0或''是有效输入,但None表示未提供。这时用if arg is not None。 - 你只想检查是否提供了任何非假值:比如一个配置项,
None、''、[]都算没设置。这时用if config更简洁。
例子:
def process(data=None):
# 情况1:允许假值,只拒绝None
if data is not None:
print(f"Data is provided: {data}") # 即使data=0或''也会执行
else:
print("Data is None")
# 情况2:只接受真值
if data:
print(f"Data is truthy: {data}") # data=0或''时不会执行
else:
print("Data is falsy or None")
# 测试
process(0) # 输出: Data is provided: 0 \n Data is falsy or None
process('') # 输出: Data is provided: \n Data is falsy or None
process(None) # 输出: Data is None \n Data is falsy or None
process('hello')# 输出: Data is provided: hello \n Data is truthy: hello
简单总结: 用 is not None 来精确排除 None,用 if query 来排除所有假值。
比如 0 和[]和{}都不会通过 if foo
文档里写了: In the context of Boolean operations, and also when expressions are used by
control flow statements, the following values are interpreted as false:
False, None, numeric zero of all types, and empty strings and containers
(including strings, tuples, lists, dictionaries, sets and frozensets). All
other values are interpreted as true. (See the nonzero()
special method for a way to change this.)
python3 里的__bool__
取决于 query 的内容,像我用 numpy 的话肯定是用 if quey is not None。
你可以试试<br>query = numpy.arrange(3)<br>if query: print(1)<br>
会报错
None 是单例模式,永远只有一个 None,所以 is None 可以判断是否返回为空。而 if query 则是判断布尔值是否为 True
看到这个语句,很像 sqlalchemy(flask-sqlalchemy)?
如果是的话,那么实际上 if foo is not None 和 if foo 达到的效果是一样的
但显然第一种表达更为清晰,毕竟 sqlalchemy 返回的要么是个 orm 对象要么是 None
一般我自己不喜欢使用 if foo 这样的表达,毕竟自己敲代码要清楚返回的值是什么(类型),是 None,是 0 还是"",还是[],{}


