Closed
Description
Bug description
# pylint: disable=missing-module-docstring,invalid-name
a = True
b = False
c = True
x = (a and b) or c
print(x) # x == True
print(b if a else c) # ternary suggested == False
Configuration
No response
Command used
pylint test.py
Pylint output
************* Module test
test.py:6:0: R1706: Consider using ternary (b if a else c) (consider-using-ternary)
Expected behavior
Success.
Pylint version
pylint 2.11.1
astroid 2.8.0
Python 3.9.7 (default, Aug 30 2021, 00:00:00)
[GCC 11.2.1 20210728 (Red Hat 11.2.1-1)]
OS / Environment
Fedora 34
Additional dependencies
No response
Activity
areveny commentedon Oct 28, 2021
This is a continuation of #1559 and #2058 which concern the message
consider-using-ternary
and the behavior on statements likea and b or c
whereb
might beFalse
.#1559 made the check emit
simplify-boolean-expression
ifb
is falsey, suggesting simplifying toc
.#2058 tries to infer the value of
b
if it is an expression. However, I think the logic is a bit faulty.If
truth_value
is any variable, thentruth_boolean_value.bool_value()
isUninferable
. This means we always suggestconsider-using-ternary
unlesstruth_value
is a falsey literal. The integration test on this ticket only tests the case wheretruth_value
is truthy, and even then it doesn't suggestconsider-using-ternary
becausetruth_boolean_value
isTrue
, but because it isUninferable
.My fix is to change
truth_boolean_value = truth_value.bool_value()
totruth_boolean_value = inferred_truth_value.bool_value()
. I think this was the original intention. This will try to infer the boolean value ofb
, and sees that it isFalse
, and suggestssimplify-boolean-expression
instead.consider-using-ternary
when condition is inferable as False #5227