Skip to content

Use or For Fallback

Sourcery refactoring id: use-or-for-fallback

Description

Often, a value can come from various sources in a priority order. In these cases, the most concise way is to use the or boolean operator.

Before

pattern = provided_pattern
if not pattern:
    pattern = pattern_from_config

After

pattern = provided_pattern or pattern_from_config

Explanation

Thanks to the flexibility of Python's or operator, you can use a single assignment statement, even if a variable can retrieve its value from various sources. This is shorter and easier to read than using multiple assignments with if not conditions.