if query,和 if query is not None 有区别吗?

2018-10-16 19:45:33 +08:00
 miniyao
foo = Item.query.filter(...).first()

if foo,和 if foo is not None 有区别吗?

自己常用 if foo,看到一些代码里有用 if foo is not None,有特别的地方吗?否则 if foo 简单多了
1786 次点击
所在节点    Python
8 条回复
Leigg
2018-10-16 19:47:11 +08:00
可读性。
beny2mor
2018-10-16 19:47:51 +08:00
比如 0 和[]和{}都不会通过 if foo
menc
2018-10-16 19:48:38 +08:00
Wincer
2018-10-16 19:49:39 +08:00
文档里写了: 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.)
beny2mor
2018-10-16 19:52:11 +08:00
@Wincer python3 里的__bool__
dangoron
2018-10-16 20:01:03 +08:00
取决于 query 的内容,像我用 numpy 的话肯定是用 if quey is not None。
你可以试试
```
query = numpy.arrange(3)
if query: print(1)
```
会报错
Qzier
2018-10-17 22:53:42 +08:00
None 是单例模式,永远只有一个 None,所以 is None 可以判断是否返回为空。而 if query 则是判断布尔值是否为 True
vipppppp
2018-10-19 09:16:03 +08:00
看到这个语句,很像 sqlalchemy(flask-sqlalchemy)?
如果是的话,那么实际上 if foo is not None 和 if foo 达到的效果是一样的
但显然第一种表达更为清晰,毕竟 sqlalchemy 返回的要么是个 orm 对象要么是 None

一般我自己不喜欢使用 if foo 这样的表达,毕竟自己敲代码要清楚返回的值是什么(类型),是 None,是 0 还是"",还是[],{}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/498234

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX