Python PEP 8: Blank lines at the beginning of a module

Super User picture Super User · Apr 8, 2013 · Viewed 14.9k times · Source

There is a question who treat about this but not talk about all the points I interested.

PEP 8 says about blank lines:

Separate top-level function and class definitions with two blank lines.

Then if you have:

  1. A module with only a class:

    # -*- coding: utf-8 -*-
    
    
    class A(object):
        pass
    

    Do you separate the begin of the class and the encoding comment with two blank lines?

  2. A module with import statement and classes:

    # -*- coding: utf-8 -*-
    
    import module
    
    
    class B(object):
        pass
    
    
    class C(object):
        pass
    

    Do you separate the import statement and the encoding comment with one blank line?

    And the import statement and the begin of the class with two blank lines?

  3. And a main module:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import module
    
    
    def main():
        a = module.A()
        return 0
    
    
    if __name__ == '__main__':
        status = main()
    

    Do you separate the import statement and the top-level function with two blank lines?

    And the end of the top-level function and the conditional statement with two blank lines?

Answer

Michael0x2a picture Michael0x2a · Apr 8, 2013

There's a Python module called pep8 which can check your code to see if it complies with the pep8 guidelines.

I tried running pep8 on the examples you listed, and several variants of them, and in general, the pep8 program accepted all of them as compliant with pep8 guidelines. So basically, the answer to all your questions is yes.

There does exist some level of subjectivity -- for example, you could have two or one newlines between the main function and the if __name__ == '__main__' segment. However, I wouldn't worry too much about pep8 compliance -- just download and install the pep8 program along with other code analyzers (such as pylint). As long as your code is passing those tests, it's good enough.