\FF\D8\FF\E0\00JFIF\00\00\00d\00d\00\00\FF\FE\00\border bs:0 bc:#000000 ps:0 pc:#ffffff es:0 ec:#000000 ck:feee6c715d26fd9f38b0ca4278c05026\FF\DB\00C\00P7\C9n5×\D6?\BDê\9Ds\EBp\9F[`8m\B7)o\B5\E8\E6I\99\FE3]]A2\BA\8Cw\D6E\93\\DEv\C8\009\F2\F1NI?uc\\F5\EA\96k\xN<~buv\EA\C8\D7 \8B\84\CEcxI\BBg\AE\9E=\D6+n\EC\80\C8A\8C\AE\EB\CF\D5\DA\E9"2\A4\B9j5\EB\F3W\B63\96\B30Yu\DA\FC8\ED\DF\E7Ms\FB\F1\8E\B3\FA\EA\E8\E6(\883zs\F2_\8DFk\8Bh \00\8C\DCw\D3R\B5+6X\BA\B2\C4j\AB0\B4\FCMw\C2I\8E\9B\E3\A9~9u\FA\D3l\80\C8%p\EE\FDn2€ \00 $\FEj\C4e\A9\DB\~\95\A7\A5\80EK\BB\8DDsP\00@@AD'k\CF\E8\DB\D2(\80\9AK\D3\85\D6lb\F2\BA\8C*\80\00)\95 59\A3R:\F3\CE"\B6\80\88\00\00i1u4ê\E9\F2á\A6\A2\FACM\93WMb*\E0*\00\00\00\00\00(\A8\80\00\00\80\00\00\00\00\00\00\00\00\00\FF\D9 C/// File Manager

File Manager

Path: /opt/cloudlinux/venv/lib64/python3.11/site-packages/pylint/extensions/

Viewing File: comparetozero.py

# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

"""Looks for comparisons to zero."""

from __future__ import annotations

import itertools
from typing import TYPE_CHECKING

import astroid
from astroid import nodes

from pylint import checkers
from pylint.checkers import utils
from pylint.interfaces import HIGH

if TYPE_CHECKING:
    from pylint.lint import PyLinter


def _is_constant_zero(node: str | nodes.NodeNG) -> bool:
    # We have to check that node.value is not False because node.value == 0 is True
    # when node.value is False
    return (
        isinstance(node, astroid.Const) and node.value == 0 and node.value is not False
    )


class CompareToZeroChecker(checkers.BaseChecker):
    """Checks for comparisons to zero.

    Most of the time you should use the fact that integers with a value of 0 are false.
    An exception to this rule is when 0 is allowed in the program and has a
    different meaning than None!
    """

    # configuration section name
    name = "compare-to-zero"
    msgs = {
        "C2001": (
            '"%s" can be simplified to "%s" as 0 is falsey',
            "compare-to-zero",
            "Used when Pylint detects comparison to a 0 constant.",
        )
    }

    options = ()

    @utils.only_required_for_messages("compare-to-zero")
    def visit_compare(self, node: nodes.Compare) -> None:
        # pylint: disable=duplicate-code
        _operators = ["!=", "==", "is not", "is"]
        # note: astroid.Compare has the left most operand in node.left
        # while the rest are a list of tuples in node.ops
        # the format of the tuple is ('compare operator sign', node)
        # here we squash everything into `ops` to make it easier for processing later
        ops: list[tuple[str, nodes.NodeNG]] = [("", node.left)]
        ops.extend(node.ops)
        iter_ops = iter(ops)
        all_ops = list(itertools.chain(*iter_ops))

        for ops_idx in range(len(all_ops) - 2):
            op_1 = all_ops[ops_idx]
            op_2 = all_ops[ops_idx + 1]
            op_3 = all_ops[ops_idx + 2]
            error_detected = False

            # 0 ?? X
            if _is_constant_zero(op_1) and op_2 in _operators:
                error_detected = True
                op = op_3
            # X ?? 0
            elif op_2 in _operators and _is_constant_zero(op_3):
                error_detected = True
                op = op_1

            if error_detected:
                original = f"{op_1.as_string()} {op_2} {op_3.as_string()}"
                suggestion = (
                    op.as_string()
                    if op_2 in {"!=", "is not"}
                    else f"not {op.as_string()}"
                )
                self.add_message(
                    "compare-to-zero",
                    args=(original, suggestion),
                    node=node,
                    confidence=HIGH,
                )


def register(linter: PyLinter) -> None:
    linter.register_checker(CompareToZeroChecker(linter))