V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
miniyao
V2EX  ›  Python

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

  •  
  •   miniyao · 2018-10-16 19:45:33 +08:00 via Android · 1781 次点击
    这是一个创建于 2018 天前的主题,其中的信息可能已经有所发展或是发生改变。
    foo = Item.query.filter(...).first()

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

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

    一般我自己不喜欢使用 if foo 这样的表达,毕竟自己敲代码要清楚返回的值是什么(类型),是 None,是 0 还是"",还是[],{}
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1083 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 19:08 · PVG 03:08 · LAX 12:08 · JFK 15:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.