python-3.x 如何添加自定义pylint警告?

kq0g1dla  于 2023-04-22  发布在  Python
关注(0)|答案(2)|浏览(152)

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

enxuqcxy

enxuqcxy1#

您可以在pylintrc中添加print到bad内置:

[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):

    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,
cnwbcb6i

cnwbcb6i2#

我建议编写一个自定义检查器。我以前从未这样做过,但如何做到这一点的文档在这里:https://pylint.pycqa.org/en/latest/how_tos/custom_checkers.html

相关问题