Python PEP8:空行约定

Python PEP8: Blank lines convention

我想知道程序部分之间换行符的Python约定是什么? 例如,考虑一下:

1
2
3
4
5
import os

def func1():

def func2():

以下两者之间理想的换行分隔应该是什么:

  • import模块和
    功能?
  • 功能本身?
  • 我已经阅读了PEP8,但是我想确认以上两点。


  • import语句和其他代码之间的两个空白行。
  • 每个功能之间有两个空白行。

  • 如果可以查看PEP8的"空白行"部分,则可以找到以下内容:

    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.

    关于进口,PEP8声明:

    Imports should usually be on separate lines

    ...

    Imports should be grouped in the following order:

  • standard library imports
  • related third party imports
  • local application/library specific imports
  • You should put a blank line between each group of imports.

    因此,对于您的示例,符合PEP8的格式为:

    1
    2
    3
    4
    5
    6
    7
    import os


    def func1():


    def func2():

    为了给出更全面的说明:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    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