Search code examples
pythonpylint

Can pylint check for a static comment / copyright notice at the top of all documents?


Can pylint be configured to check for a specific static text such as a copyright notice at the top of every file?

E.g. validate that the following two lines begin every file:

# Copyright Spacely Sprockets, 2018-2062
#

Solution

  • You could write your own checker:

    from pylint.checkers import BaseRawFileChecker
    
    class CopyrightChecker(BaseRawFileChecker):
        """ Check the first line for copyright notice
        """
    
        name = 'custom_copy'
        msgs = {'W9902': ('Include copyright in file',
                          'file-no-copyright',
                          ('Your file has no copyright')),
                }
        options = ()
    
        def process_module(self, node):
            """process a module
            the module's content is accessible via node.stream() function
            """
            with node.stream() as stream:
                for (lineno, line) in enumerate(stream):
                    if lineno == 1:
                        # Check for copyright notice
                        # if it fails add an error message
                        self.add_message('file-no-copyright',
                                         line=lineno)
    
    
        def register(linter):
            """required method to auto register this checker"""
            linter.register_checker(CopyrightChecker(linter))
    

    See more about custom checkers in the pylint documentation. Also this excellent post about the subject.

    UPDATE Thanks to @Diego in the comments for noticing that this was outdated, now we can just inherit from BaseRawFileChecker.