Skip to content

if-else-block-instead-of-dict-lookup (SIM116)

Derived from the flake8-simplify linter.

What it does

Checks for three or more consecutive if-statements with direct returns

Why is this bad?

These can be simplified by using a dictionary

Example

def find_phrase(x):
    if x == 1:
        return "Hello"
    elif x == 2:
        return "Goodbye"
    elif x == 3:
        return "Good morning"
    else:
        return "Goodnight"

Use instead:

def find_phrase(x):
    phrases = {1: "Hello", 2: "Goodye", 3: "Good morning"}
    return phrases.get(x, "Goodnight")