How to use the pylint.interfaces.IAstroidChecker 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 rhinstaller / anaconda / tests / pylint / intl.py View on Github external
if isinstance(curr.parent, astroid.CallFunc) and getattr(curr.parent.func, "name", "") in translationMethods:
                self.add_message("W9901", node=node)
                break

            curr = curr.parent

    @check_messages("found-_-in-module-class")
    def visit_callfunc(self, node):
        # The first test skips internal functions like getattr.
        if isinstance(node.func, astroid.Name) and node.func.name == "_":
            if isinstance(node.scope(), astroid.Module) or isinstance(node.scope(), astroid.Class):
                self.add_message("W9902", node=node)

# Extend LoggingChecker to check translated logging strings
class IntlLoggingChecker(LoggingChecker):
    __implements__ = (IAstroidChecker,)

    name = 'intl-logging'
    msgs = {'W9903': ("Fake message for translated E/W120* checks",
                      "translated-log",
                      "This message is not emitted itself, but can be used to control the display of \
                       logging format messages extended for translated strings")
           }

    options = ()

    @check_messages('translated-log')
    def visit_callfunc(self, node):
        if len(node.args) >= 1 and isinstance(node.args[0], astroid.CallFunc) and \
                getattr(node.args[0].func, "name", "") in translationMethods:
            for formatstr in _get_message_strings(node.args[0]):
                # Both the node and the args need to be copied so we don't replace args
github rhinstaller / anaconda / tests / pylint / pointless-override.py View on Github external
class D(B,C):
                pass

        In this  case, starting from B, B._attrib = False would be considered
        pointless. However, for D the MRO is B, C, A, and removing the assignment
        B._attrib = False would change the inherited value of D._attrib from
        False to True.

        The analysis is incomplete because it will find some values unequal when
        actually they are equal.

        The analysis is both incomplete and unsound because it expects that
        assignments will always be made by means of the same syntax.
    """

    __implements__ = (IAstroidChecker,)

    name = "pointless class attribute override checker"
    msgs = {
       "W9951":
       (
          "Assignment to class attribute %s overrides identical assignment in ancestor.",
          "pointless-class-attribute-override",
          "Assignment to class attribute  that overrides assignment in ancestor that assigns identical value has no effect."
       ),
       "W9952":
       (
          "definition of %s method overrides identical method definition in ancestor",
          "pointless-method-definition-override",
          "Overriding empty method definition with another empty method definition has no effect."
       )
    }
github ansible / ansible / test / lib / ansible_test / _data / sanity / pylint / plugins / string_format.py View on Github external
"field numbering (e.g. '{}').",
              {'minversion': (2, 6)}),
    'E9390': ("bytes object has no .format attribute",
              "ansible-no-format-on-bytestring",
              "Used when a bytestring was used as a PEP 3101 format string "
              "as Python3 bytestrings do not have a .format attribute",
              {'minversion': (3, 0)}),
}


class AnsibleStringFormatChecker(BaseChecker):
    """Checks string formatting operations to ensure that the format string
    is valid and the arguments match the format string.
    """

    __implements__ = (IAstroidChecker,)
    name = 'string'
    msgs = MSGS

    @check_messages(*(MSGS.keys()))
    def visit_call(self, node):
        func = utils.safe_infer(node.func)
        if (isinstance(func, astroid.BoundMethod)
                and isinstance(func.bound, astroid.Instance)
                and func.bound.name in ('str', 'unicode', 'bytes')):
            if func.name == 'format':
                self._check_new_format(node, func)

    def _check_new_format(self, node, func):
        """ Check the new string formatting """
        if (isinstance(node.func, astroid.Attribute)
                and not isinstance(node.func.expr, astroid.Const)):
github pkgcore / pkgcore / pkgdist / lintplugin / snakeoil_lint.py View on Github external
if hasattr(interfaces, 'IASTNGChecker'):
    print('ERROR: please install >=pylint-1.0', file=sys.stderr)
    exit(1)

try:
    from astroid import nodes, utils, Getattr, CallFunc, rebuilder
except ImportError:
    print('ERROR: could not import astroid; make sure that package is '
          'installed: dev-python/astroid', file=sys.stderr)
    raise


class SnakeoilChecker(checkers.BaseChecker):
    """Custom snakeoil linter checks."""

    __implements__ = (interfaces.IRawChecker, interfaces.IAstroidChecker)

    name = 'snakeoil'

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

    # pylint: disable=too-few-public-methods,multiple-statements
    class _MessageCPC01(object): pass
    class _MessageCPC02(object): pass
    class _MessageWPC01(object): pass
    class _MessageWPC02(object): pass
    class _MessageWPC03(object): pass
    class _MessageWPC04(object): pass
    class _MessageWPC06(object): pass
    class _MessageWPC08(object): pass
    # pylint: enable=too-few-public-methods,multiple-statements
github PyCQA / pylint / pylint / checkers / spelling.py View on Github external
while True:
            if "/" not in self._text:
                return (self._text, 0)
            pre_text, post_text = self._text.split("/", 1)
            if not pre_text or not post_text:
                break
            if not pre_text[-1].isalpha() or not post_text[0].isalpha():
                raise StopIteration()
            self._text = pre_text + " " + post_text
        raise StopIteration()


class SpellingChecker(BaseTokenChecker):
    """Check spelling in comments and docstrings"""

    __implements__ = (ITokenChecker, IAstroidChecker)
    name = "spelling"
    msgs = {
        "C0401": (
            "Wrong spelling of a word '%s' in a comment:\n%s\n"
            "%s\nDid you mean: '%s'?",
            "wrong-spelling-in-comment",
            "Used when a word in comment is not spelled correctly.",
        ),
        "C0402": (
            "Wrong spelling of a word '%s' in a docstring:\n%s\n"
            "%s\nDid you mean: '%s'?",
            "wrong-spelling-in-docstring",
            "Used when a word in docstring is not spelled correctly.",
        ),
        "C0403": (
            "Invalid characters %r in a docstring",
github Shopify / shopify_python / shopify_python / google_styleguide.py View on Github external
class GoogleStyleGuideChecker(checkers.BaseChecker):
    """
    Pylint checker for the Google Python Style Guide.

    See https://google.github.io/styleguide/pyguide.html

    Checks that can't be implemented include:
      - When capturing an exception, use as rather than a comma

    Checks that are already covered by Pylint include:
      - Never use catch-all 'except:' statements, or 'catch Exception' (bare-except, broad-except)
      - Do not use mutable objects as default values in the function or method definition (dangerous-default-value)
      - Do not terminate your lines with semi-colons and
        do not use semi-colons to put two commands on the same line. (unnecessary-semicolon, multiple-statements)
    """
    __implements__ = (interfaces.IAstroidChecker,)

    name = 'google-styleguide-checker'

    msgs = {
        'C6001': ('%(child)s is not a module or cannot be imported',
                  'import-modules-only',
                  'Only import packages or modules and ensure that they are installed.'),
        'C6002': ('%(module)s imported relatively',
                  'import-full-path',
                  'Import modules using their absolute names.'),
        'C6003': ('%(name)s declared at the module level (i.e. global)',
                  'global-variable',
                  'Avoid global variables in favor of class variables.'),
        'C6004': ('Raised two-argument exception',
                  'two-arg-exception',
                  "Use either raise Exception('message') or raise Exception."),
github kiwitcms / Kiwi / kiwi_lint / objects_update.py View on Github external
# Copyright (c) 2018 Alexander Todorov 

# Licensed under the GPL 2.0: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html

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


class ObjectsUpdateChecker(checkers.BaseChecker):
    __implements__ = (interfaces.IAstroidChecker,)

    name = 'objects-update-checker'

    msgs = {'E4461': ("Model.objects.update() doesn't update history! Use Model.save() instead.",
                      'objects-update-used',
                      "")}

    @utils.check_messages('objects-update-used')
    def visit_attribute(self, node):
        """
            Note: this checker will produce false-positives on
            dict.update() or anything else that is named .update().

            These should be white-listed on a line by line basis
            b/c there can be many situations where .update() is used
            after filtering or directly on top of another variable which
github kiwitcms / Kiwi / kiwi_lint / nested_definition.py View on Github external
# Copyright (c) 2019 Alexander Todorov 

# Licensed under the GPL 2.0: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html

import astroid

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


class NestedDefinitionChecker(checkers.BaseChecker):
    __implements__ = (interfaces.IAstroidChecker,)

    name = 'nested-definition-checker'

    msgs = {'E4491': ("Nested class definition found!",
                      'nested-class-found',
                      "Do not define classes inside other classes or functions!"),
            'E4492': ("Nested function definition found!",
                      'nested-function-found',
                      "Do not define functions inside other functions!")}

    @utils.check_messages('nested-function-found')
    def visit_functiondef(self, node):
        if not isinstance(node.parent, (astroid.Module, astroid.ClassDef)):
            self.add_message('nested-function-found', node=node)

    @utils.check_messages('nested-class-found')
github pylava / pylava_pylint / pylama_pylint / pylint / checkers / logging.py View on Github external
method names, False otherwise.
    """
    if not isinstance(callfunc_node, astroid.CallFunc):
        return False
    func = utils.safe_infer(callfunc_node.func)
    return (isinstance(func, astroid.BoundMethod)
            and isinstance(func.bound, astroid.Instance)
            and (func.bound.name in types if types else True)
            and (func.name in methods if methods else True))



class LoggingChecker(checkers.BaseChecker):
    """Checks use of the logging module."""

    __implements__ = interfaces.IAstroidChecker
    name = 'logging'
    msgs = MSGS

    options = (('logging-modules',
                {'default': ('logging',),
                 'type': 'csv',
                 'metavar': '',
                 'help': 'Logging modules to check that the string format '
                         'arguments are in logging function parameter format'}
               ),
              )

    def visit_module(self, node): # pylint: disable=unused-argument
        """Clears any state left in this checker from last module checked."""
        # The code being checked can just as easily "import logging as foo",
        # so it is necessary to process the imports and store in this field
github pylava / pylava_pylint / pylama_pylint / pylint / checkers / classes.py View on Github external
}


class ClassChecker(BaseChecker):
    """checks for :
    * methods without self as first argument
    * overridden methods signature
    * access only to existent members via self
    * attributes not defined in the __init__ method
    * supported interfaces implementation
    * unreachable code
    """

    __implements__ = (IAstroidChecker,)

    # configuration section name
    name = 'classes'
    # messages
    msgs = MSGS
    priority = -2
    # configuration options
    options = (('ignore-iface-methods',
                {'default' : (#zope interface
                    'isImplementedBy', 'deferred', 'extends', 'names',
                    'namesAndDescriptions', 'queryDescriptionFor', 'getBases',
                    'getDescriptionFor', 'getDoc', 'getName', 'getTaggedValue',
                    'getTaggedValueTags', 'isEqualOrExtendedBy', 'setTaggedValue',
                    'isImplementedByInstancesOf',
                    # twisted
                    'adaptWith',