22

I have some code that causes Pylint to complain:

The if statement can be replaced with 'var = bool(test)' (simplifiable-if-statement)`

The code (with obfuscated variable names) is below.

A = True
B = 1
C = [1]
D = False
E = False

if A and B in C:
    D = True
else:
    E = True

print(D, E)

How can this be simplified so that Pylint does not throw any errors?

I don't quite understand how bool() can be used for this. I know it converts any value to a Boolean value, but I don't know how it can be applied here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gary
  • 3,891
  • 8
  • 38
  • 60

3 Answers3

21

That logic can be expressed as:

D = A and B in C
E = not D
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • Ah yes, that is quite clean. – Gary Mar 29 '18 at 02:33
  • I would argue that this creates the opportunity to introduce a bug when changing how `D`'s value is computed because that would implicitly change how `E`'s value is computed. – ndmeiri Mar 29 '18 at 02:36
7

Try this:

D = bool(A and B in C)
E = not bool(A and B in C)
ndmeiri
  • 4,979
  • 12
  • 37
  • 45
  • Thanks, I figured it would be something along those lines. I suppose a slight tweak would be to store the conditional in a variable, and then `D = cond; E = not cond`? – Gary Mar 29 '18 at 02:32
3

I was initially a bit confused by the accepted answer and then realized my problem was not with the accepted answer itself (which is fully correct indeed) but with the specificity of the question. I needed a more generic / simple use case and so I will try to provide one, hoping it will be of help for someone.

The simplifiable-if-statement Pylint refactor basically happens when we use an if-else statement to assign a value to a boolean variable, which could have otherwise been assigned directly, without using the if-else statement at all.

A generic example could be:

if <condition>:
  variable = True
else:
  variable = False

which can (and should) be simplified as:

variable = <condition>

where <condition> is a boolean expression.

A concrete example:

if a > 5:
  b = True
else:
  b = False

should be rewritten as

b = a > 5

Getting back to the original question, in this case the condition is A and B in C and, as pointed out by other contributors, the redundant snippet:

D = False
E = False
if A and B in C:
    D = True
else:
    E = True

should be simplified as

D = A and B in C
E = not D
Sal Borrelli
  • 2,201
  • 19
  • 19