Skip to content

too-many-branches (PLR0912)#

Derived from the Pylint linter.

What it does#

Checks for functions or methods with too many branches.

By default, this rule allows up to 12 branches. This can be configured using the lint.pylint.max-branches option.

Why is this bad?#

Functions or methods with many branches are harder to understand and maintain than functions or methods with fewer branches.

Example#

def capital(country):
    if country == "Australia":
        return "Canberra"
    elif country == "Brazil":
        return "Brasilia"
    elif country == "Canada":
        return "Ottawa"
    elif country == "England":
        return "London"
    elif country == "France":
        return "Paris"
    elif country == "Germany":
        return "Berlin"
    elif country == "Poland":
        return "Warsaw"
    elif country == "Romania":
        return "Bucharest"
    elif country == "Spain":
        return "Madrid"
    elif country == "Thailand":
        return "Bangkok"
    elif country == "Turkey":
        return "Ankara"
    elif country == "United States":
        return "Washington"
    else:
        return "Unknown"  # 13th branch

Use instead:

def capital(country):
    capitals = {
        "Australia": "Canberra",
        "Brazil": "Brasilia",
        "Canada": "Ottawa",
        "England": "London",
        "France": "Paris",
        "Germany": "Berlin",
        "Poland": "Warsaw",
        "Romania": "Bucharest",
        "Spain": "Madrid",
        "Thailand": "Bangkok",
        "Turkey": "Ankara",
        "United States": "Washington",
    }
    city = capitals.get(country, "Unknown")
    return city

Options#