foo = Item.query.filter(...).first()
if foo,和 if foo is not None 有区别吗?
自己常用 if foo,看到一些代码里有用 if foo is not None,有特别的地方吗?否则 if foo 简单多了
if foo,和 if foo is not None 有区别吗?
自己常用 if foo,看到一些代码里有用 if foo is not None,有特别的地方吗?否则 if foo 简单多了
1
Leigg Oct 16, 2018 via iPhone
可读性。
|
2
beny2mor Oct 16, 2018
比如 0 和[]和{}都不会通过 if foo
|
3
menc Oct 16, 2018
|
4
Wincer Oct 16, 2018 via Android
文档里写了: 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.) |
6
dangoron Oct 16, 2018 via Android
取决于 query 的内容,像我用 numpy 的话肯定是用 if quey is not None。
你可以试试 ``` query = numpy.arrange(3) if query: print(1) ``` 会报错 |
7
Qzier Oct 17, 2018 via iPhone
None 是单例模式,永远只有一个 None,所以 is None 可以判断是否返回为空。而 if query 则是判断布尔值是否为 True
|
8
vipppppp Oct 19, 2018 看到这个语句,很像 sqlalchemy(flask-sqlalchemy)?
如果是的话,那么实际上 if foo is not None 和 if foo 达到的效果是一样的 但显然第一种表达更为清晰,毕竟 sqlalchemy 返回的要么是个 orm 对象要么是 None 一般我自己不喜欢使用 if foo 这样的表达,毕竟自己敲代码要清楚返回的值是什么(类型),是 None,是 0 还是"",还是[],{} |