I have a boolean field in the mysql db table.
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
Okay, I think that make sense. So change my code to this:
caseNum = session.query(TestCase).filter(TestCase.obsoleted is False).count()
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.
That’s because SQLAlchemy filters are one of the few places where
== False actually makes sense. Everywhere else you should not use it.
# noqa comment to the line and be done with it.
Or you can use
from sqlalchemy.sql.expression import false TestCase.obsoleted == false()
false() returns the right value for your session SQL dialect. There is a matching
SQL Alchemy also has
isnot functions you can use. An example would be
field == Falseis converted to
field = false
field == Trueis converted to
field = true
field == Noneis converted to
field IS NULL
field.is_(False)is converted to
field IS false
field.is_(True)is converted to
field IS true
field.is_(None)is converted to
field IS NULL
is_(not None) will be evaluated to
is_(bool(not None) what gives
field = true so you rather go for
field IS NOT NULL
# noqa in front of statement, it’ll ignore the warning.