Python 你忽略了什么PEP 8准则,你坚持哪些准则?

Python 你忽略了什么PEP 8准则,你坚持哪些准则?,python,pep8,pep,Python,Pep8,Pep,多年来,我写的Python越多,我就越同意大多数准则,尽管出于我自己的原因,我一直故意打破一些准则 我很想知道人们在政治公众人物8(或其他政治公众人物)中坚持什么,为什么坚持,以及人们觉得什么不方便或不充分 就我而言(以及在工作中),我们只偏离了少数几点: 下划线分隔的小写名称,我可以看出它的意义,因为它将始终如一地保持一致,但我们倾向于使用小写字母,即使它偶尔会导致一些不一致(例如部分大写或错误大写的首字母缩写词和后续单词,这通常是出于一时冲动的调用)。主要是因为我们通常使用的API几乎全部

多年来,我写的Python越多,我就越同意大多数准则,尽管出于我自己的原因,我一直故意打破一些准则

我很想知道人们在政治公众人物8(或其他政治公众人物)中坚持什么,为什么坚持,以及人们觉得什么不方便或不充分

就我而言(以及在工作中),我们只偏离了少数几点:

  • 下划线分隔的小写名称,我可以看出它的意义,因为它将始终如一地保持一致,但我们倾向于使用小写字母,即使它偶尔会导致一些不一致(例如部分大写或错误大写的首字母缩写词和后续单词,这通常是出于一时冲动的调用)。主要是因为我们通常使用的API几乎全部都使用camelCase(一些较高,一些较低),而且由于某些原因,我发现它更容易阅读,并且倾向于保留下划线作为分隔标记或指定的混乱/模糊

  • 我仍然无法让自己按照政治公众人物在物体内部规定的方式将物体隔开。new和init我倾向于在类的正下方不留空行,因为我总是想在那里阅读它们,其中包含类名和参数,这些方法有助于类中相同的功能范围(比如init、get和set of the same attrib或set of attrib)我只隔一个空格,我喜欢类之间有三个空格,两个方法之间,我不会在那个对象的映射中聚合。 同样,这纯粹是为了代码的视觉效果和可读性。我发现流控制中非常紧凑的内容,以及方法和对象之间的这种间隔,始终将我的眼睛引导到我希望它在代码停止几个月后重新读取的地方。它对我选择的编辑器的折叠也有很好的响应

  • 我坚持的一些东西是标签而不是空格(特别是当我们使用的一些应用内编辑器实际上没有标签替换功能时,这在原型设计阶段对代码库造成了很大的污染),当我阅读其他内容时,这些东西会让我发疯

  • 诸如导入、什么导入、全局等的顺序。当那些导入量很大的文件混淆或无序时,它确实会让我对这些文件产生反感

  • 语句中的空格,尤其是当人们使用制表符并试图在var名称中不同长度的行之间对齐赋值操作时(似乎没有办法说服这样做的人,一段看起来像excel的代码并不整洁;)

  • 控制块内的间距,特别是当我看到同一个流控制块内明显的随机间距,然后在对象内使用相似数量的间距作为方法时。在我开始阅读这该死的东西之前,我不得不编辑这些东西


因此,这些都是我的,也是我“违反”政治公众人物计划背后的原因(有些是同事们共同的,有些是同事们不赞成的)。我很想知道其他蟒蛇学者在这些方面做了什么和没有做什么。

当我写小脚本时,我通常只使用两个空格

我总是对docstring使用相同的模式:

def function():
    """
    Even if it's a single line.
    """
def foobang(bizbaz, plotz=None):
    """
    Return a foobang

    Optional plotz says to frobnicate the bizbaz first.
    """

    if plotz is not None:
        ...

我总是使用4个空格,我尝试每行最多使用79个字符,有时是不可能的。 在过去,我还使用了“import sys,os”之类的导入。 总的来说,我试着坚持PEP 8

编辑:也可以使用:

def foobar():
    """
    foobar
    """
对于文档

我使用pylint,,它是一个很好的工具,可以帮助您和其他访问代码的开发人员保持代码的干净性和可读性

虽然我没有涵盖你说的所有话题,但它非常有用

您可以有如下报告:

carlos@debian:~/src/fcl/cltools$ pylint numbertoletters.py
No config file found, using default configuration
************* Module numbertoletters
C:  1: Missing docstring
C: 56:es_numero: Missing docstring
C: 56:es_numero: Invalid name "s" (should match [a-z_][a-z0-9_]{2,30}$)
C: 56:es_numero: Invalid name "s" (should match [a-z_][a-z0-9_]{2,30}$)
C: 69:convertnumbertoletters: Empty docstring
C: 90:convertnumbertoletters: Operator not preceded by a space
    numero='%(numero)09d' % {'numero' : int(parte_entera)}
          ^
C: 92:convertnumbertoletters: Comma not followed by a space
    for i in [0,3,6]:
               ^^

W: 69:convertnumbertoletters: Unused argument 'languaje'
C:108:unidades: Empty docstring
C:108:unidades: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)
C:108:unidades: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)
C:112:unidades: Invalid name "u" (should match [a-z_][a-z0-9_]{2,30}$)
C:118:teens: Empty docstring
C:118:teens: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)
C:118:teens: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)
C:122:teens: Invalid name "t" (should match [a-z_][a-z0-9_]{2,30}$)
C:127:tens: Empty docstring
C:127:tens: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)
C:127:tens: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)
C:131:tens: Invalid name "t" (should match [a-z_][a-z0-9_]{2,30}$)
C:137:tercia: Empty docstring
C:141:tercia: Operator not preceded by a space
    numero='%(numero)03d' % {'numero' : int(num)}
          ^
C:143:tercia: Invalid name "a" (should match [a-z_][a-z0-9_]{2,30}$)
C:144:tercia: Invalid name "b" (should match [a-z_][a-z0-9_]{2,30}$)
C:145:tercia: Invalid name "c" (should match [a-z_][a-z0-9_]{2,30}$)
C:163:tercia: Operator not followed by a space
                resultado ='veinti '+unidades(c)
                          ^
C:165:tercia: Operator not followed by a space
        elif b >=3 and b <= 9:
               ^^
C:178:tercia: Operator not followed by a space
                resultado ='ciento '+unidades(c)
                          ^
C:192:tercia: Operator not followed by a space
                resultado ='ciento veinti '+unidades(c)
                          ^
C:204:tercia: Operator not preceded by a space
            prefix='quinientos '
                  ^
C:206:tercia: Operator not preceded by a space
            prefix='setecientos '
                  ^
C:208:tercia: Operator not preceded by a space
            prefix='novecientos '
                  ^
C:210:tercia: Operator not preceded by a space
            prefix=unidades(a)+'cientos '
                  ^
R:137:tercia: Too many return statements (23/6)
R:137:tercia: Too many branches (41/12)
R:137:tercia: Too many statements (73/50)


Report
======
141 statements analysed.

Raw metrics
-----------

+----------+-------+------+---------+-----------+
|type      |number |%     |previous |difference |
+==========+=======+======+=========+===========+
|code      |144    |68.25 |NC       |NC         |
+----------+-------+------+---------+-----------+
|docstring |5      |2.37  |NC       |NC         |
+----------+-------+------+---------+-----------+
|comment   |57     |27.01 |NC       |NC         |
+----------+-------+------+---------+-----------+
|empty     |5      |2.37  |NC       |NC         |
+----------+-------+------+---------+-----------+



Statistics by type
------------------

+---------+-------+-----------+-----------+------------+---------+
|type     |number |old number |difference |%documented |%badname |
+=========+=======+===========+===========+============+=========+
|module   |1      |NC         |NC         |0.00        |0.00     |
+---------+-------+-----------+-----------+------------+---------+
|class    |0      |NC         |NC         |0           |0        |
+---------+-------+-----------+-----------+------------+---------+
|method   |0      |NC         |NC         |0           |0        |
+---------+-------+-----------+-----------+------------+---------+
|function |6      |NC         |NC         |0.00        |0.00     |
+---------+-------+-----------+-----------+------------+---------+



Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |NC       |NC         |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |NC       |NC         |
+-------------------------+------+---------+-----------+



Messages by category
--------------------

+-----------+-------+---------+-----------+
|type       |number |previous |difference |
+===========+=======+=========+===========+
|convention |32     |NC       |NC         |
+-----------+-------+---------+-----------+
|refactor   |3      |NC       |NC         |
+-----------+-------+---------+-----------+
|warning    |1      |NC       |NC         |
+-----------+-------+---------+-----------+
|error      |0      |NC       |NC         |
+-----------+-------+---------+-----------+



Messages
--------

+-----------+------------+
|message id |occurrences |
+===========+============+
|C0103      |14          |
+-----------+------------+
|C0322      |6           |
+-----------+------------+
|C0112      |5           |
+-----------+------------+
|C0323      |4           |
+-----------+------------+
|C0111      |2           |
+-----------+------------+
|W0613      |1           |
+-----------+------------+
|R0915      |1           |
+-----------+------------+
|R0912      |1           |
+-----------+------------+
|R0911      |1           |
+-----------+------------+
|C0324      |1           |
+-----------+------------+



Global evaluation
-----------------
Your code has been rated at 7.45/10

I hope it helps.
carlos@debian:~/src/fcl/cltools$pylint numbertoletters.py
未找到配置文件,使用默认配置
*************模块编号字母
C:1:缺少文档字符串
C:56:序号:缺少文档字符串
C:56:es_编号:无效的名称“s”(应匹配[a-z_uu][a-z0-9_uu]{2,30}$)
C:56:es_编号:无效的名称“s”(应匹配[a-z_uu][a-z0-9_uu]{2,30}$)
C:69:convertnumbertoletters:空文档字符串
C:90:convertnumbertoletters:运算符前面没有空格
数字='%(数字)09d'{'numero':int(parte_entera)}
^
C:92:convertnumbertoletters:逗号后不带空格
对于[0,3,6]中的i:
^^
W:69:convertnumbertoletters:未使用的参数'Languaaje'
C:108:unidades:空文档字符串
C:108:unidades:无效的名称“x”(应匹配[a-z_uz][a-z0-9_uz]{2,30}$)
C:108:unidades:无效的名称“x”(应匹配[a-z_uz][a-z0-9_uz]{2,30}$)
C:112:unidades:无效的名称“u”(应匹配[a-z_uu][a-z0-9_u]{2,30}$)
C:118:10:空文档字符串
C:118:Tevens:名称“x”无效(应与[a-z_u][a-z0-9_u][2,30}$匹配)
C:118:Tevens:名称“x”无效(应与[a-z_u][a-z0-9_u][2,30}$匹配)
C:122:Tevens:无效的名称“t”(应匹配[a-z_u][a-z0-9_u]{2,30}$)
C:127:tens:空docstring
C:127:tens:无效的名称“x”(应匹配[a-z_uz][a-z0-9_uz]{2,30}$)
C:127:tens:无效的名称“x”(应匹配[a-z_uz][a-z0-9_uz]{2,30}$)
C:131:tens:无效名称“t”(应匹配[a-z_u2;][a-z0-9_2;]{2,30}$)
C:137:tercia:空文档字符串
C:141:tercia:运算符前面没有空格
numero='%(numero)03d'{'numero':int(num)}
^
C:143:tercia:无效的名称“a”(应匹配[a-z_u][a-z0-9_u]{2,30}$)
C:144:tercia:无效的名称“b”(应匹配[a-z_u][a-z0-9_u]{2,30}$)
C:145:tercia:无效的名称“C”(应匹配[a-z_u][a-z0-9_u]{2,30}$)
C:163:tercia:运算符后面不跟空格
resultado='Venti'+unidades(c)
^
C:165:tercia:运算符后面不跟空格
如果b>=3且b则“每行79个字符”部分是无意义的。他们自己的示例显示了执行此操作时代码变得多么不可读:

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)
这就像试着阅读一篇这样的新闻文章一样

80柱te
x = 1
y = 2
long_variable = 3
x             = 1
y             = 2
long_variable = 3
x =             1
y =             2
long_variable = 3
- Imports should usually be on separate lines, e.g.:

    Yes: import os
         import sys

    No:  import sys, os
import sys, os, time, gc, inspect, math, doctest
Without PEP8                           With PEP8                
---------------------------------------------------------------- 
y = sqrt(x**2 + y**2)                  y = sqrt(x ** 2 + y ** 2) 
a*x**3 + b*x**2 + c*x + d              a * x ** 3 + b * x ** 2 + c * x + d 
10**(a*x + b)                          10 ** (a * x + b)  
F = V/(sqrt(g*h) + epsilon)            F = V / (sqrt(g * h) + epsilon) 
a*cos(nx/pi) + b*sin(nx/pi)            a * cos(nx / pi) + b * sin(nx / pi) 
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)
i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
search_start = (f - f_1/3) * n/fs
search_stop  = (f + f_1/3) * n/fs
b_lpf, a_lpf = filter(N, 2*pi*fc, 'low',  analog=True)
b_hpf, a_hpf = filter(N, 2*pi*fc, 'high', analog=True)
p[x >  1] =                         np.cosh(order * np.arccosh( x[x >  1]))
p[x < -1] = (1 - 2 * (order % 2)) * np.cosh(order * np.arccosh(-x[x < -1]))
b0 =  (1 + cos(w0))/2
b1 = -(1 + cos(w0))
a = array([[-0.198,  0.248, -1.17 , -0.629,  1.378],
           [-1.315,  0.947, -0.736, -1.388,  0.389],
           [ 0.241, -0.98 ,  0.535,  0.951,  1.143],
           [-0.601,  1.286, -0.947,  0.037, -0.864],
           [ 0.178, -0.289, -1.037, -1.453, -0.369]])
a = array([[-0.198, 0.248, -1.17, -0.629, 1.378],
           [-1.315, 0.947, -0.736, -1.388, 0.389],
           [0.241, -0.98, 0.535, 0.951, 1.143],
           [-0.601, 1.286, -0.947, 0.037, -0.864],
           [0.178, -0.289, -1.037, -1.453, -0.369]])
"""Return a foobang

Optional plotz says to frobnicate the bizbaz first.

"""
def foobang(bizbaz, plotz=None):
    """
    Return a foobang

    Optional plotz says to frobnicate the bizbaz first.
    """

    if plotz is not None:
        ...
"""
Process foo, return bar.
"""

"""
Process foo, return bar.

If processing fails throw ProcessingError.
"""
"""Process foo, return bar."""

"""
Process foo, return bar.

If processing fails throw ProcessingError.

"""
"""Process foo, return bar."""

"""Process foo, return bar.

If processing fails throw ProcessingError.

"""
"""Process foo, return bar."""

"""Process foo, return bar.

If processing fails throw ProcessingError.
"""
"""Process foo, return bar."""

"""
Process foo, return bar.

If processing fails throw ProcessingError.
"""
if cond:
    actions
    ...
if a == 0: b = 0
if a == 0:
     b = 0