Skip to content

Assign if expression

Sourcery refactoring id: assign-if-exp

Description:

Replaces conditional assignment to a variable with an if expression

Before:

if condition:
    x = 1
else:
    x = 2

After:

x = 1 if condition else 2

Explanation:

Python's conditional expression syntax is its version of the ternary operator. Using this syntax is definitely more concise, but it is one of the more controversial refactorings (along with list comprehensions). Some coders dislike these expressions and find them slightly harder to parse than writing them out fully.

Our view is that this is a definite improvement where the conditional expression is: - short and fits on one line - is not complex (no nested expressions or long chains of booleans)

Once the change is made there's only one statement where x is defined as opposed to having to read two statements plus the if-else lines. Similarly to the comprehension example, when we're scanning the code we usually won't need to know the details of how x gets assigned, and can just see that it's being assigned and move on.

Back to top