Skip to content

needless-bool (SIM103)

Derived from the flake8-simplify linter.

Fix is sometimes available.

What it does

Checks for if statements that can be replaced with bool.

Why is this bad?

if statements that return True for a truthy condition and False for a falsy condition can be replaced with boolean casts.

Example

Given:

def foo(x: int) -> bool:
    if x > 0:
        return True
    else:
        return False

Use instead:

def foo(x: int) -> bool:
    return x > 0

Or, given:

def foo(x: int) -> bool:
    if x > 0:
        return True
    return False

Use instead:

def foo(x: int) -> bool:
    return x > 0

Fix safety

This fix is marked as unsafe because it may change the program’s behavior if the condition does not return a proper Boolean. While the fix will try to wrap non-boolean values in a call to bool, custom implementations of comparison functions like __eq__ can avoid the bool call and still lead to altered behavior.

References