flake8 complains on boolean comparison “==” in filter clause

Posted on

Question :

flake8 complains on boolean comparison “==” in filter clause

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()

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.

Asked By: Jruv


Answer #1:

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.

Answered By: Martijn Pieters

Answer #2:

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


More on those here

Answered By: avoliva

Answer #3:

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

Answered By: andilabs

Answer #4:

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

Answered By: user3016020

Leave a Reply

Your email address will not be published. Required fields are marked *