Replace if-else with ternary operation where appropriate

Python pattern

Replaces an assignment to the same variable done across an if-else with a ternary operator when both are equivalent.


Apply with the Grit CLI
grit apply ternary_op

Replace assign across if-else with ternary operator

BEFORE
if condition:
    x = 1
else:
    x = 2

if condition:
    x = 1.0
else:
    x = 2.0

if condition:
    x = "abcd"
else:
    x = "efgh"

if condition:
    y = 10
    x = do_something(y)
else:
    x = "efgh"
AFTER
x = 1 if condition else 2

x = 1.0 if condition else 2.0

x = "abcd" if condition else "efgh"

if condition:
    y = 10
    x = do_something(y)
else:
    x = "efgh"