Python PEP8: Blank lines convention

PythonPep8

Python Problem Overview


I am interested in knowing what is the Python convention for newlines between the program parts? For example, consider this:

import os

def func1():

def func2():

What should be the ideal newline separation between:

  1. The import modules and the functions?
  2. The functions themselves?

I have read PEP8, but I wanted to confirm the above two points.

Python Solutions


Solution 1 - Python

  1. Two blank lines between the import statements and other code.
  2. Two blank lines between each function.

Solution 2 - Python

If one will check with 'Blank Lines' section of PEP8 — one will find the following:

> Surround top-level function and class definitions with two blank lines. > > Method definitions inside a class are surrounded by a single blank line. > > Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations). > > Use blank lines in functions, sparingly, to indicate logical sections.

Regarding imports, PEP8 states:

> Imports should usually be on separate lines > > ... > > Imports should be grouped in the following order: > > 1. standard library imports > 2. related third party imports > 3. local application/library specific imports > > You should put a blank line between each group of imports.

So, for your example, PEP8 compliant formatting would be:

import os


def func1():


def func2():

Just to give a more comprehensive illustration:

import re
import glob
import sys

import requests
import scrapy

from flask import Flask
from my_local_module import MyClass


def top_level_function1():
    pass


def top_level_function2():
    pass


class TestClass(object):
    
    def class_method1():
        pass

    def class_method2():
        pass


class TestClass2(object):
    
    def class2_method1():
        pass

    def class2_method2():
        pass

Solution 3 - Python

Perfectly explained by user8554766

Just a simple modification

#Standard system imports
import re
import glob
import sys

#Related third party imports
import requests
import scrapy
from flask import Flask

#Local application/library specific imports
from my_local_module import MyClass1, MyClass

Reference

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser225312View Question on Stackoverflow
Solution 1 - PythonBryan OakleyView Answer on Stackoverflow
Solution 2 - Pythonuser8554766View Answer on Stackoverflow
Solution 3 - Pythonshellbot97View Answer on Stackoverflow