Pycodestyle: False positive E712 (comparison to False) when comparing with arrays

Created on 23 Oct 2015  路  7Comments  路  Source: PyCQA/pycodestyle

For an array of boolean values valid, if I want to find the False elements I might use something like:

badInds = numpy.where(valid == False)

This shows the error E712 - comparison to False should be 'if cond is False:' or 'if not cond:' which will break this statement.

Most helpful comment

For reference with sqlalchemy you can use is_ and isnot (perhaps similar in numpy?):

-            .filter(Group.addon == False)\
-            .filter(Group.product_id != None).all()  # noqa: E712
+            .filter(Group.addon.is_(False))\
+            .filter(Group.product_id.isnot(None)).all()

Source: https://stackoverflow.com/q/18998010/175584

All 7 comments

Strictly speaking there's no easy way for us to detect all of the cases where we might want to make an exception to E712. (Other cases involve ORMs, e.g., SQLAlchemy, SQLObject, etc.)

This line can be written as:
badInds = numpy.where(valid is False)
or
badInds = numpy.where(not bool(valid))
or just
badInds = numpy.where(not valid)

@tonkoandrew No. Not a single one of those works...

In [154]: a = np.random.randint(0, 2, 10).astype(bool)
In [155]: a
Out[155]: array([ True, False, False,  True,  True, False,  True, False,  True,  True], dtype=bool)
In [156]: np.where(a is False)
Out[156]: (array([], dtype=int64),)

the is comparison does _not_ work element-wise.

np.where(a.__eq__(False))

@tonkoandrew that's also a non-starter. There's no doubt that people should be allowed to use == in a case like this. It's something that works perfectly well, the problem is figuring out how to accommodate that.

Flake8 3.0 will allow for # noqa: E712 on these lines, but before that is completed, there might be another way of solving this (sans rewriting the code to something far less elegant).

For reference with sqlalchemy you can use is_ and isnot (perhaps similar in numpy?):

-            .filter(Group.addon == False)\
-            .filter(Group.product_id != None).all()  # noqa: E712
+            .filter(Group.addon.is_(False))\
+            .filter(Group.product_id.isnot(None)).all()

Source: https://stackoverflow.com/q/18998010/175584

So Flake8 3.0 has been out for something longer than a year and allows for folks to do # noqa: E712 on those lines. There's no good way to fix this in pycodestyle directly at this point. So, I'm closing this.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

asottile picture asottile  路  8Comments

ZeeD26 picture ZeeD26  路  5Comments

rharish101 picture rharish101  路  3Comments

Behoston picture Behoston  路  6Comments

fgotzens picture fgotzens  路  7Comments