Home > Back-end >  Changing assert statement to remove "== True" according to flake8 E712 produces error
Changing assert statement to remove "== True" according to flake8 E712 produces error

Time:09-29

I am trying to write a pytest of the form

import numpy as np
import pytest

def test(blah):
    # ...
    assert (np.isclose(computed_value, expected_value, atol = 0.001, rtol = 0) == True), 
    "error message" 

The pytests pass, but once I try to commit to GitLab, I get the following message and the commit fails to go through.

>  flake8...................................................................Failed
- hook id: flake8
- exit code: 1
  E712 comparison to True should be 'if cond is True:' or 'if cond:

Replacing the above assert by

assert if np.isclose(computed_value, expected_value, atol = 0.001, rtol = 0) is True,"Error message"

does not help either.

Further,

assert (np.isclose(computed_value, expected_value, atol = 0.001, rtol = 0) is True), 
        "error message" 

causes my pytest to fail! How can I resolve this?

CodePudding user response:

the original code was not testing what you expect -- == in numpy is a projection (meaning numpy.array([1, 2, 3]) == True => numpy.array([True, False, False])

numpy.isclose is also a projection of sorts, returning an array with values for each comparison -- your original assertion only passed because a numpy array is "truthy" -- not that every value was close within the tolerance

you probably want to use numpy.all to validate that everything was "isclose" --

assert numpy.all(numpy.isclose(...))

CodePudding user response:

E712 comparison to True should be 'if cond is True:' or 'if cond:

This message is misleading in this context, because it shows an example of a condition that is used in an if statement.

It caused you to write

assert if np.isclose( ...

But you are using the condition in an assert statement, not in an if statement.

You should only remove == True and change nothing else. Don't add if after assert.

  • Related