Flake8抱怨过滤子句中的布尔比较“ = =”

在 mysql db 表中有一个布尔字段。

# table model
class TestCase(Base):
__tablename__ = 'test_cases'
...
obsoleted = Column('obsoleted',  Boolean)

要获得所有未过时的测试用例的计数,可以像下面这样简单地完成:

caseNum = session.query(TestCase).filter(TestCase.obsoleted == False).count()
print(caseNum)

这种方法很有效,但是怪物报告了以下警告:

E712: 与 False 的比较应该是“ if cond is False:”或者“ if not 第二:

好吧,我觉得有道理,所以把我的代码改成这样:

caseNum = session.query(TestCase).filter(TestCase.obsoleted is False).count()

或者

caseNum = session.query(TestCase).filter(not TestCase.obsoleted).count()

但是它们都不能工作,结果总是0。 我认为 filter 子句不支持操作符“ is”或“ is not”。有人能告诉我怎么处理这种情况吗。我不想破坏薄片。

35923 次浏览

That's because SQLAlchemy filters are one of the few places where == False actually makes sense. Everywhere else you should not use it.

Add a # noqa comment to the line and be done with it.

Or you can use sqlalchemy.sql.expression.false:

from sqlalchemy.sql.expression import false


TestCase.obsoleted == false()

where false() returns the right value for your session SQL dialect. There is a matching sqlalchemy.expression.true.

SQL Alchemy also has is_ and isnot functions you can use. An example would be

Model.filter(Model.deleted.is_(False))

More on those here

@Jruv Use # noqa in front of statement, it'll ignore the warning.

I have a look what exact query is generated for using SQLAlchemy when == and is_ when the database dialect is Postgresql for boolean field:

  • for == we get:

    1. field == False is converted to field = false
    2. field == True is converted to field = true
    3. field == None is converted to field IS NULL
  • for is_() we get:

    1. field.is_(False) is converted to field IS false
    2. field.is_(True) is converted to field IS true
    3. field.is_(None) is converted to field IS NULL

NOTE: is_(not None) will be evaluated to is_(bool(not None) what gives is_(True) giving field = true so you rather go for isnot(None) producing field IS NOT NULL

Why don't you use .filter_by(field=True) / .filter_by(field=False) ?

caseNum = session.query(TestCase).filter(~TestCase.obsoleted).count()
print(caseNum)

works.try it in your sqlalchemy versions