Disable pylint message for a given module or directory

后端 未结 2 1831
离开以前
离开以前 2020-12-19 03:32

Is there a way to disable Pylint\'s duplicate-code message just for test files? All of the tests in our project are DAMP so the duplicated code is by design. I

2条回答
  •  渐次进展
    2020-12-19 03:50

    It can be achieved with pylint plugin and some hack.

    Assume we have following directory structure:

     pylint_plugin.py
     app
     ├── __init__.py
     └── mod.py
     test
     ├── __init__.py
     └── mod.py
    

    content of mod.py:

    def f():
        1/0
    

    content of pylint_plugin.py:

    from astroid import MANAGER
    from astroid import scoped_nodes
    
    
    def register(linter):
        pass
    
    
    def transform(mod):
        if 'test.' not in mod.name:
            return
        c = mod.stream().read()
        # change to the message-id you need
        c = b'# pylint: disable=pointless-statement\n' + c
        # pylint will read from `.file_bytes` attribute later when tokenization
        mod.file_bytes = c
    
    
    MANAGER.register_transform(scoped_nodes.Module, transform)
    

    without plugin, pylint will report:

    ************* Module tmp.exp_pylint.app.mod
    W:  2, 4: Statement seems to have no effect (pointless-statement)
    ************* Module tmp.exp_pylint.test.mod
    W:  2, 4: Statement seems to have no effect (pointless-statement)
    

    with plugin loaded:

    PYTHONPATH=. pylint -dC,R --load-plugins pylint_plugin app test
    

    yields:

    ************* Module tmp.exp_pylint.app.mod
    W:  2, 4: Statement seems to have no effect (pointless-statement)
    

    pylint read comments by tokenizing source file, this plugin change file content on the fly, to cheat pylint when tokenization.

    Note that to simplify demonstration, here I constructed a "pointless-statement" warning, disable other types of message is trivial.

提交回复
热议问题