How to use the pylint.checkers function in pylint

To help you get started, we’ve selected a few pylint examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PyCQA / pylint / tests / unittest_lint.py View on Github external
def test_pylint_visit_method_taken_in_account(linter):
    class CustomChecker(checkers.BaseChecker):
        __implements__ = interfaces.IAstroidChecker
        name = "custom"
        msgs = {"W9999": ("", "custom", "")}

        @check_messages("custom")
        def visit_class(self, _):
            pass

    linter.register_checker(CustomChecker(linter))
    linter.open()
    out = StringIO()
    linter.set_reporter(text.TextReporter(out))
    linter.check("abc")
github svn2github / chromium-depot-tools / third_party / pylint / testutils.py View on Github external
'\n'.join(repr(m) for m in got)))
        self.assertEqual(list(messages), got, msg)

    def walk(self, node):
        """recursive walk on the given node"""
        walker = PyLintASTWalker(linter)
        walker.add_checker(self.checker)
        walker.walk(node)


# Init
test_reporter = TestReporter()
linter = PyLinter()
linter.set_reporter(test_reporter)
linter.config.persistent = 0
checkers.initialize(linter)
linter.global_set_option('required-attributes', ('__revision__',))

if linesep != '\n':
    LINE_RGX = re.compile(linesep)
    def ulines(string):
        return LINE_RGX.sub('\n', string)
else:
    def ulines(string):
        return string

INFO_TEST_RGX = re.compile(r'^func_i\d\d\d\d$')

def exception_str(self, ex): # pylint: disable=unused-argument
    """function used to replace default __str__ method of exception instances"""
    return 'in %s\n:: %s' % (ex.file, ', '.join(ex.args))
github PyCQA / pylint / pylint / extensions / emptystring.py View on Github external
"""Looks for  comparisons to empty string."""

import itertools

import astroid

from pylint import checkers, interfaces
from pylint.checkers import utils


def _is_constant_empty_str(node):
    return isinstance(node, astroid.Const) and node.value == ""


class CompareToEmptyStringChecker(checkers.BaseChecker):
    """Checks for comparisons to empty string.
    Most of the times you should use the fact that empty strings are false.
    An exception to this rule is when an empty string value is allowed in the program
    and has a different meaning than None!
    """

    __implements__ = (interfaces.IAstroidChecker,)

    # configuration section name
    name = "compare-to-empty-string"
    msgs = {
        "C1901": (
            "Avoid comparisons to empty string",
            "compare-to-empty-string",
            "Used when Pylint detects comparison to an empty string constant.",
        )
github BasPH / pylint-airflow / src / pylint_airflow / checkers / xcom.py View on Github external
"""Checks on Airflow XComs."""

import astroid
from pylint import checkers
from pylint import interfaces
from pylint.checkers import utils

from pylint_airflow.__pkginfo__ import BASE_ID


class XComChecker(checkers.BaseChecker):
    """Checks on Airflow XComs."""

    __implements__ = interfaces.IAstroidChecker

    msgs = {
        f"R{BASE_ID}00": (
            "Return value from %s is stored as XCom but not used anywhere",
            "unused-xcom",
            "Return values from a python_callable function or execute() method are "
            "automatically pushed as XCom.",
        )
    }

    @utils.check_messages("unused-xcom")
    def visit_module(self, node: astroid.Module):
        """
github pkgcore / pkgcore / lintplugin / pkgcore_lint.py View on Github external
"""Pylint plugin checking for trailing whitespace."""


import sys

from pylint import interfaces, checkers
from logilab.astng import nodes, raw_building, utils


class PkgcoreChecker(checkers.BaseChecker):

    __implements__ = (interfaces.IRawChecker, interfaces.IASTNGChecker)

    name = 'pkgcore'

    # XXX move some of those over to RewriteDemandload somehow
    # (current monkey patch running the rewriter does not support that)

    msgs = {
        'CPC01': ('line too long',
                  'More complete version of the standard line too long check'),
        'CPC02': ('trailing whitespace', 'trailing whitespace sucks.'),
        'WPC01': ('demandload with arglen != 2 ignored',
                  'A call which is probably a demandload has the wrong number '
                  'of arguments. Either fix the checker to not detect it as '
                  'demandload when it is really not or fix the code to call '
github PyCQA / pylint / pylint / checkers / python3.py View on Github external
parent_scope = parent.func.lookup(parent.func.name)[0]
            if _is_builtin(parent_scope) and parent.func.name in _accepts_iterator:
                return True
        elif isinstance(parent.func, astroid.Getattr):
            if parent.func.attrname == 'join':
                return True
    # If the call is in an unpacking, there's no need to warn,
    # since it can be considered iterating.
    elif (isinstance(parent, astroid.Assign) and
          isinstance(parent.targets[0], (astroid.List, astroid.Tuple))):
        if len(parent.targets[0].elts) > 1:
            return True
    return False


class Python3Checker(checkers.BaseChecker):

    __implements__ = interfaces.IAstroidChecker
    enabled = False
    name = 'python3'

    msgs = {
        # Errors for what will syntactically break in Python 3, warnings for
        # everything else.
        'E1601': ('print statement used',
                  'print-statement',
                  'Used when a print statement is used '
                  '(`print` is a function in Python 3)',
                  {'maxversion': (3, 0)}),
        'E1602': ('Parameter unpacking specified',
                  'parameter-unpacking',
                  'Used when parameter unpacking is specified for a function'
github qutebrowser / qutebrowser / scripts / dev / pylint_checkers / qute_pylint / openencoding.py View on Github external
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser.  If not, see .

"""Make sure open() has an encoding set."""

import astroid
from pylint import interfaces, checkers
from pylint.checkers import utils


class OpenEncodingChecker(checkers.BaseChecker):

    """Checker to check open() has an encoding set."""

    __implements__ = interfaces.IAstroidChecker
    name = 'open-encoding'

    msgs = {
        'W9400': ('open() called without encoding', 'open-without-encoding',
                  None),
    }

    @utils.check_messages('open-without-encoding')
    def visit_call(self, node):
        """Visit a Call node."""
        if hasattr(node, 'func'):
            infer = utils.safe_infer(node.func)
github svn2github / chromium-depot-tools / third_party / pylint / lint.py View on Github external
linter.load_configuration(**self._config)
            linter.set_reporter(reporters.CollectingReporter())

            # Run the checks.
            linter.check(file_or_module)

            msgs = [_get_new_args(m) for m in linter.reporter.messages]
            return (file_or_module, linter.file_state.base_name, linter.current_name,
                    msgs, linter.stats, linter.msg_status)


class PyLinter(configuration.OptionsManagerMixIn,
               utils.MessagesHandlerMixIn,
               utils.ReportsHandlerMixIn,
               checkers.BaseTokenChecker):
    """lint Python modules using external checkers.

    This is the main checker controlling the other ones and the reports
    generation. It is itself both a raw checker and an astroid checker in order
    to:
    * handle message activation / deactivation at the module level
    * handle some basic but necessary stats'data (number of classes, methods...)

    IDE plugins developpers: you may have to call
    `astroid.builder.MANAGER.astroid_cache.clear()` accross run if you want
    to ensure the latest code version is actually checked.
    """

    __implements__ = (interfaces.ITokenChecker, )

    name = 'master'
github brettcannon / caniusepython3 / caniusepython3 / pylint_checker.py View on Github external
# See the License for the specific language governing permissions and
# limitations under the License.
"""Pylint checker to enforce Python 2/3 compatible syntax.

See the documentation for what checkers pylint includes by default
which compliment this file.
"""
from __future__ import absolute_import, print_function

import token
import tokenize

from pylint import checkers, interfaces


class StrictPython3Checker(checkers.BaseChecker):

    __implements__ = interfaces.IAstroidChecker

    name = 'python3'
    msgs = {
        # Errors for what will syntactically break in Python 3, warnings for
        # everything else.
        # Retired:
        #   'W6001': 'filter built-in referenced'
        #   'W6002': 'map built-in referenced'
        #   'W6003': 'range built-in referenced'
        #   'W6004': 'zip built-in referenced'
        'W6005': ('open built-in referenced',
                  'open-builtin',
                  'Used when the open built-in function is referenced '
                  '(semantics different in Python 3; '