β

pep 8

jKey Blog 92 阅读

简介

这篇是讲关于 python 代码风格的一些约定,主要用于 python 中标准库的代码风格的约定。关于 pep 8 这份文档网上也有很多翻译,但是为了自己便于记忆,大致的翻译记录一下。所以,对照原文可能是不完整的。

A Foolish Consistency is the Hobgoblin of Little Minds

总之一句话,就是保持代码的一致性。

代码排版

缩进

Yes:

# Aligned with opening delimiter
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# More indentation included to distinguish this from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

No:

# Arguments on first line forbidden when not using vertical alignment
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# Further indentation required as indentation is not distinguishable
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)

Optional:

# Extra indentation is not necessary.
foo = long_function_name(
  var_one, var_two,
  var_three, var_four)

制表符还是空格?

每行最大长度

Some examples:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
            color == 'red' and emphasis == 'strong' or
            highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

空行

编码 (PEP 263)

python 核心代码应该使用 ASCII 或 Latin-1 编码。python 3.0 以上使用 UTF-8,更多请看 PEP 3120

导入

Yes: import os
         import sys

    No:  import sys, os
from subprocess import Popen, PIPE
from myclass import MyClass
    from foo.bar.yourclass import YourClass
如果这样写导致了本地名字冲突,那么就这样写:
import myclass
    import foo.bar.yourclass
并且使用 "myclass.MyClass" 和 "foo.bar.yourclass.YourClass".

表达式和语句中的空格

不能忍受的事

避免在下述情况中使用无关的空格:

Yes: spam(ham[1], {eggs: 2})
    No:  spam( ham[ 1 ], { eggs: 2 } )
Yes: if x == 4: print x, y; x, y = y, x
    No:  if x == 4 : print x , y ; x , y = y , x
Yes: spam(1)
    No:  spam (1)
Yes: dict['key'] = list[index]
    No:  dict ['key'] = list [index]
x = 1
    y = 2
    long_variable = 3
No:
x             = 1
    y             = 2
    long_variable = 3

其他推荐

注释

Block Comments

Inline Comments

Documentation Strings

Version Bookkeeping

Naming Conventions

Descriptive: Naming Styles

Prescriptive: Naming Conventions

Names to Avoid

Package and Module Names

Class Names

Exception Names

Global Variable Names

Function Names

Function and method arguments

Method Names and Instance Variables

Constants

Designing for inheritance

Programming Recommendations

作者:jKey Blog
原文地址:pep 8, 感谢原作者分享。

发表评论