MartinThoma / flake8-simplify

❄ A flake8 plugin that helps you to simplify code
MIT License
185 stars 19 forks source link

SIM108: Use the ternary operator if it's reasonable. #12

Closed MartinThoma closed 3 years ago

MartinThoma commented 3 years ago

Explanation

Use the ternary operator if it's reasonable.

Example

# Bad
if a:
    b = c
else:
    b = d

# Good
b = c if a else d
MartinThoma commented 3 years ago
astpretty --no-show-offsets /dev/stdin <<< `cat example.py` 
Module(
    body=[
        If(
            test=Name(id='a', ctx=Load()),
            body=[
                Assign(
                    targets=[Name(id='b', ctx=Store())],
                    value=Name(id='c', ctx=Load()),
                    type_comment=None,
                ),
            ],
            orelse=[
                Assign(
                    targets=[Name(id='b', ctx=Store())],
                    value=Name(id='d', ctx=Load()),
                    type_comment=None,
                ),
            ],
        ),
    ],
    type_ignores=[],
)