如何添加自定义pylint警告?

How to add custom pylint warning?

我想为所有打印语句向我的 pylint 添加一条警告消息,提醒自己我有它们以防打印敏感信息。这可能吗?我只能找到有关禁用 pylint 错误的答案,而不是启用新错误。

我建议编写自定义检查器。我自己以前从来没有这样做过,但是关于如何做的文档在这里:https://pylint.pycqa.org/en/latest/how_tos/custom_checkers.html

您可以将 print 添加到 pylintrc:

中的坏内置函数
[DEPRECATED_BUILTINS]

# List of builtins function names that should not be used, separated by a comma
bad-functions=print

load-plugins=
    pylint.extensions.bad_builtin,

创建像 Code-Apprentice 这样的自定义检查器应该也相对容易,像这样:


from typing import TYPE_CHECKING

from astroid import nodes

from pylint.checkers import BaseChecker
from pylint.checkers.utils import check_messages
from pylint.interfaces import IAstroidChecker

if TYPE_CHECKING:
    from pylint.lint import PyLinter

class PrintUsedChecker(BaseChecker):

    __implements__ = (IAstroidChecker,)
    name = "no_print_allowed"
    msgs = {
        "W5001": (
            "Used builtin function %s",
            "print-used",
            "a warning message reminding myself I have them in case I "
            "print sensitive information",
        )
    }

    @check_messages("print-used")
    def visit_call(self, node: nodes.Call) -> None:
        if isinstance(node.func, nodes.Name):
            if node.func.name == "print":
                self.add_message("print-used", node=node)


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

然后你在pylintrc中的load-plugin中添加:

load-plugins=
    your.code.namespace.print_used,