PY3.R0912

Too many branches

Used when a function or method has too many branches, making it hard to follow.

Noncompliant Code:

Copy
def foo(x):
    if x == 1:
        return 'This is one.'
    else:
        print('This is not one.')
    if x == 2:
        return 'This is two.'
    else:
        print('This is not two.')
    if x == 3:
        return 'This is three.'
    else:
        print('This is not three.')
    if x == 4:
        return 'This is four.'
    else:
        print('This is not four.')
    if x == 5:
        return 'This is five.'
    else:
        print('This is not five.')
    if x == 6:
        return 'This is six.'
    else:
        print('This is not six.')
    if x == 7:
        return 'This is seven.'
    else:
        print('This is not seven.')
    if x == 8:
        return 'This is eight.'
    else:
        print('This is not eight.')

Compliant Code:

Copy
NUMBERS_TO_STRINGS = {
    1: 'one',
    2: 'two',
    3: 'three',
    4: 'four',
    5: 'five',
    6: 'six',
    7: 'seven'
}
def foo(x):
    for key, value in NUMBERS_TO_STRINGS.items():
        if x == key:
            return f'This is {value}.'
        else:
            print(f'This is not {value}.')

The content on this page is adapted from the Pylint User Guide, Copyright ©2003-2022, Logilab, PyCQA and contributors. All rights reserved. https://pylint.pycqa.org/en/latest/index.html#, and is used under the Python Software Foundation License Version 2. Examples, recipes, and other code in the Pylint documentation are additionally licensed under the Zero Clause BSD License.