【问题标题】:pylint protection against self-assignment防止自我分配的 pylint 保护
【发布时间】:2019-09-30 10:09:48
【问题描述】:

我有这个测试文件:

"""module docstring"""


class Aclass:
    """class docstring"""

    def __init__(self, attr=None, attr2=None):
        self.attr = attr
        self.attr2 = attr2

    def __repr__(self):
        return 'instance_of the Aclass {self.attr}.'

    def __str__(self):
        return 'The A with: {self.attr}.'


def init_a():
    """function docstring"""
    a_inst = Aclass()
    attr = 1
    attr2 = 2
    a_inst.attr2 = attr2
    # should be: a_inst.attr = attr, but have a typo
    attr = attr

我使用 pylint 检查它,输出显示一切正常。

$ pylint test.py 

--------------------------------------------------------------------
Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00)

基于linting,我希望在软件语言中出现可疑使用的标志,因为我不知道此代码a=1; a=a 何时有用。 我想看到一些警告,例如:未使用的变量或自赋值等。有没有使用 pylint 的方法? (我知道 Pycharm 和 sonarqube)。 sonar rules 的示例。

public void foo() {
    int x = 3;
    x = x;
}

Such assignments are useless, and may indicate a logic error or typo.

关于pylint的详细信息

pylint 2.3.1
astroid 2.2.5
Python 3.6.5 (default, May  5 2019, 22:05:54) 
[GCC 6.3.0 20170516]

UPDATE已添加到版本pylint 2.4

【问题讨论】:

  • 在我看来,您的问题的关键是“是否存在a=a 可能无效的情况?”。我相当确定您可以通过将模块加载器和描述符弄得一团糟来管理这样的事情。我可能需要很长时间才能真正写出有效的东西。一些导致a=a 产生副作用的代码会回答您的问题吗?
  • 不,我的问题是如何运行 pylint 以使用与声纳示例中相同的规则来捕获警告。

标签: python pylint


【解决方案1】:

我查看了 Pylint 规则,但没有找到任何可以帮助您解决此问题的方法。我确实发现您可以编写自己的检查器并使用它制作 pylint :

$ pylint yourpieceofcode.py --load-plugins=checker

checker.py:

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


class SelfAssignChecker(BaseChecker):
    __implements__ = IAstroidChecker

    name = 'self-assign-returns'
    priority = -1
    msgs = {
        'W5555': (
            'Self assignment (%s).',
            'self-assign',
            'useless assignment.'
        ),
    }

    def visit_assign(self, node):
        names = []
        for child in node.get_children():
            if not hasattr(child, 'name'):
                return
            if child.name not in names:
                names.append(child.name)
            else:
                self.add_message("self-assign", node=node, args=child.name)


def register(linter):
    linter.register_checker(SelfAssignChecker(linter))

文档here! :)

在您的文件 test.py 上测试。输出:

$ pylint --load-plugins=checker test.py
************* Module test
test.py:25:0: C0304: Final newline missing (missing-final-newline)
test.py:25:4: W5555: Self assignment (attr). (self-assign)

------------------------------------------------------------------
Your code has been rated at 8.57/10 (previous run: 9.29/10, -0.71)

Pylint 版本:

$ pylint --version
pylint 2.3.1
astroid 2.2.5
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0]

【讨论】:

    猜你喜欢
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 2012-06-28
    • 2015-05-21
    • 1970-01-01
    • 2013-03-24
    • 2018-01-18
    相关资源
    最近更新 更多