use-implicit-booleaness-not-comparison-to-string / C1804#

Message emitted:

"%s" can be simplified to "%s", if it is striclty a string, as an empty string is falsey

Description:

Empty string are considered false in a boolean context. Following this check blindly in weakly typed code base can create hard to debug issues. If the value can be something else that is falsey but not a string (for example ``None``, an empty sequence, or ``0``) the code will not be equivalent.

Caution

This message is disabled by default. To enable it, add use-implicit-booleaness-not-comparison-to-string to the enable option.

Problematic code:

def important_string_manipulation(x: str, y: str) -> None:
    if x == "":  # [use-implicit-booleaness-not-comparison-to-string]
        print("x is an empty string")

    if y != "":  # [use-implicit-booleaness-not-comparison-to-string]
        print("y is not an empty string")

Correct code:

def important_string_manipulation(x: str, y: str) -> None:
    if not x:
        print("x is an empty string")

    if y:
        print("y is not an empty string")

Configuration file:

[main]
enable=use-implicit-booleaness-not-comparison-to-string

Created by the refactoring checker.