pythonpython-3.xpylintpylintrc

How to add custom pylint warning?


I want to add a warning message to my pylint for all print statements reminding myself I have them in case I print sensitive information. Is this possible? I can only find answers about disabling pylint errors, not enabling new ones.


Solution

  • You can add print to the bad builtin in your 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,
    

    Creating a custom checker like Code-Apprentice suggested should also be relatively easy, something like that:

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

    Then you add it in load-plugin in the pylintrc:

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