flake8 complains on boolean comparison “==” in fil

2019-02-16 03:43发布

I have a boolean field in the mysql db table.

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

To get the count of all the non-obsoleted test cases, that can be done simply like this:

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

That works fine, but the flake8 report the following warning:

E712: Comparison to False should be "if cond is False:" or "if not cond:"

Okay, I think that make sense. So change my code to this:

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

or

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

But neither of them can work. The result is always 0. I think the filter clause doesn't support the operator "is" or "is not". Will someone can tell me how to handle this situation. I don't want to disable the flake.

3条回答
The star\"
2楼-- · 2019-02-16 04:26

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.

查看更多
手持菜刀,她持情操
3楼-- · 2019-02-16 04:32

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

查看更多
家丑人穷心不美
4楼-- · 2019-02-16 04:47

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

查看更多
登录 后发表回答