一图看懂 pycodestyle 模块:一个检查Python代码是否符合PEP8风格约定的工具,资料整理+笔记(大全)

本文由 大侠(AhcaoZhu)原创,转载请声明。
链接: https://blog.csdn.net/Ahcao2008

Alt

一图看懂 pycodestyle 模块:一个检查Python代码是否符合PEP8风格约定的工具,资料整理+笔记(大全)

🧊摘要

  • 全文介绍python的 pycodestyle 模块(一个检查Python代码是否符合PEP8风格约定的工具)、函数、类及类的方法和属性。
  • 它通过代码抓取并经AI智能翻译和人工校对。
  • 是一部不可多得的权威字典类工具书。它是系列集的一部分。后续陆续发布、敬请关注。【原创:AhcaoZhu大侠】

🧊模块图

pycodestyle-module

pycodestyle
	◆bisect
	◆configparser
	◆inspect
	◆io
	◆keyword
	◆os
	◆re
	◆sys
	◆time
	◆tokenize
	◆warnings

🧊类关系图

pycodestyle-class

◆object
	pycodestyle.BaseReport
		pycodestyle.FileReport
		pycodestyle.StandardReport
			pycodestyle.DiffReport
	pycodestyle.Checker
	pycodestyle.StyleGuide

🧊模块全展开

☘️【pycodestyle】

pycodestyle, fullname=pycodestyle, file=pycodestyle.py

根据PEP 8,检查Python源代码格式。
要了解用法和选项列表,请尝试以下操作:
    $ python pycodestyle.py -h
这个程序及其回归测试套件在这里:[参见](https://github.com/pycqa/pycodestyle)
错误和警告组:
    E errors
    W warnings
    100 indentation
    200 whitespace
    300 blank lines
    400 imports
    500 line length
    600 deprecation
    700 statements
    900 syntax error

🔵统计

序号类别数量
1int4
4str10
5tuple1
6list2
8dict4
9module11
10class7
11function53
13residual31
14system9
15private9
16all123

🔵常量

🌿int

1 MAX_LINE_LENGTH 79
2 MAX_DOC_LENGTH 72
3 INDENT_SIZE 4
4 PyCF_ONLY_AST 1024

🌿str

5 DEFAULT_EXCLUDE .svn,CVS,.bzr,.hg,.git,pycache,.tox
6 DEFAULT_IGNORE E121,E123,E126,E226,E24,E704,W503,W504
7 USER_CONFIG C:\Users\ahcao.pycodestyle
8 TESTSUITE_PATH …\lib\site-packages\testsuite

🌿tuple

9 PROJECT_CONFIG (‘setup.cfg’, ‘tox.ini’)

🌿list

10 ASSIGNMENT_EXPRESSION_OP []
11 BENCHMARK_KEYS [‘directories’, ‘files’, ‘logical lines’, ‘physical lines’]

🌿dict

12 BLANK_LINES_CONFIG {‘top_level’: 2, ‘method’: 1}
13 REPORT_FORMAT {‘default’: ‘%(path)s:%(row)d:%(col)d: %(code)s %(text)s’, ‘pylint’: ‘%(path)s:%(row)d: [%(code)s] %(text)s’}
14 _checks {‘physical_line’: {<function tabs_or_spaces at 0x0000020A3540D9D8>: ([‘E101’], [‘physical_line’, ‘indent_char’]), <funct…

🔵模块

🌿15 bisect

bisect, fullname=bisect, file=bisect.py

🌿16 configparser

configparser, fullname=configparser, file=configparser.py

🌿17 inspect

inspect, fullname=inspect, file=inspect.py

🌿18 io

io, fullname=io, file=io.py

🌿19 keyword

keyword, fullname=keyword, file=keyword.py

🌿20 os

os, fullname=os, file=os.py

🌿21 re

re, fullname=re, file=re.py

🌿22 sys

sys, fullname=sys, file=

🌿23 time

time, fullname=time, file=

🌿24 tokenize

tokenize, fullname=tokenize, file=tokenize.py

🌿25 warnings

warnings, fullname=warnings, file=warnings.py

🔵函数

🌿26 fnmatch(name, pat)

fnmatch(name, pat), module=fnmatch, line:19 at fnmatch.py

测试FILENAME是否与PATTERN匹配。
    模式是Unix shell风格:
    *       匹配一切
    ?       匹配任何单个字符
    [seq]   匹配seq中的任何字符
    [!seq]  匹配任何不在seq中的字符
    FILENAME中的初始周期没有特殊的含义。
    如果操作系统需要,FILENAME和PATTERN首先都是大小写规范化的。
    如果你不想这样,使用fnmatchcase(FILENAME, PATTERN)。

🌿27 lru_cache(maxsize=128, typed=False)

lru_cache(maxsize=128, typed=False), module=functools, line:458 at functools.py

最近最少使用的缓存装饰器。
    如果“*maxsize*”设置为“None”,则不启用LRU特性,缓存可以不受约束地增长。
    如果*typed*为True,不同类型的参数将被单独缓存。
    例如,f(3.0)和f(3)将被视为具有不同结果的不同调用。
    缓存函数的参数必须是可哈希的。使用 f.cache_info() 查看命名tuple的缓存统计信息(hits, misses, maxsize, currsize)。
    使用f.cache_Clear()清除缓存和统计信息。
    使用 f.__wrapped__ 访问底层函数。[参见:](http://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU))

🌿28 _get_parameters(function)

_get_parameters(function), module=pycodestyle, line:156 at site-packages\pycodestyle.py

🌿29 register_check(check, codes=None)

register_check(check, codes=None), module=pycodestyle, line:163 at site-packages\pycodestyle.py

注册一个新的检查对象。

🌿30 tabs_or_spaces(physical_line, indent_char)

tabs_or_spaces(physical_line, indent_char), module=pycodestyle, line:186 at site-packages\pycodestyle.py

不要混合制表符和空格。
Python最流行的缩进方式是只使用空格。
第二种最流行的方式是只使用标签。
混合使用制表符和空格缩进的代码应该转换为只使用空格。
当使用-t选项调用Python命令行解释器时,它会对非法混合制表符和空格的代码发出警告。
当使用-tt时,这些警告变成错误。这些选项是强烈推荐的!
    Okay: if a == 0:\n    a = 1\n    b = 1
    E101: if a == 0:\n        a = 1\n\tb = 1

🌿31 tabs_obsolete(physical_line)

tabs_obsolete(physical_line), module=pycodestyle, line:207 at site-packages\pycodestyle.py

在新项目中,强烈建议只使用空格而不是制表符。
    Okay: 如果为真:\n返回
    W191: 如果为真:\n\t 返回

🌿32 trailing_whitespace(physical_line)

trailing_whitespace(physical_line), module=pycodestyle, line:219 at site-packages\pycodestyle.py

尾随空格是多余的。
    返回的警告会根据行本身是否为空而有所不同,以便对那些想要缩进空行的人进行更容易的过滤。
    Okay: spam(1)\n#
    W291: spam(1) \n#
    W293: class Foo(object):\n    \n    bang = 12

🌿33 trailing_blank_lines(physical_line, lines, line_number, total_lines)

trailing_blank_lines(physical_line, lines, line_number, total_lines), module=pycodestyle, line:241 at site-packages\pycodestyle.py

尾随空行是多余的。
    Okay: spam(1)
    W391: spam(1)\n
    然而,最后一行应该以新行结束(警告W292)。

🌿34 maximum_line_length(physical_line, max_line_length, multiline, line_number, noqa)

maximum_line_length(physical_line, max_line_length, multiline, line_number, noqa), module=pycodestyle, line:258 at site-packages\pycodestyle.py

将所有行限制为最多79个字符。
仍然有许多设备被限制在80个字符行;另外,将Windows限制在80个字符使得多个Windows并行使用成为可能。
这些设备上的默认包装看起来很丑。
因此,请将所有行限制为最多79个字符。
对于长文本块(文档字符串或注释),建议将长度限制为72个字符。报告错误E501。

🌿35 _is_one_liner(logical_line, indent_level, lines, line_number)

_is_one_liner(logical_line, indent_level, lines, line_number), module=pycodestyle, line:296 at site-packages\pycodestyle.py

🌿36 blank_lines(logical_line, blank_lines, indent_level, line_number, blank_before, previous_logical, previous_unindented_logical_line, previous_indent_level, lines)

blank_lines(logical_line, blank_lines, indent_level, line_number, blank_before, previous_logical, previous_unindented_logical_line, previous_indent_level, lines), module=pycodestyle, line:331 at site-packages\pycodestyle.py

用两个空行分隔顶级函数和类定义。
    类内的方法定义由单个空行分隔。可
    以使用额外的空行(少量地)来分隔相关函数组。
    在一堆相关的一行程序(例如一组虚拟实现)之间可以省略空行。
    在函数中尽量使用空行来表示逻辑部分。
    Okay: def a():\n    pass\n\n\ndef b():\n    pass
    Okay: def a():\n    pass\n\n\nasync def b():\n    pass
    Okay: def a():\n    pass\n\n\n# Foo\n# Bar\n\ndef b():\n    pass
    Okay: default = 1\nfoo = 1
    Okay: classify = 1\nfoo = 1

    E301: class Foo:\n    b = 0\n    def bar():\n        pass
    E302: def a():\n    pass\n\ndef b(n):\n    pass
    E302: def a():\n    pass\n\nasync def b(n):\n    pass
    E303: def a():\n    pass\n\n\n\ndef b(n):\n    pass
    E303: def a():\n\n\n\n    pass
    E304: @decorator\n\ndef a():\n    pass
    E305: def a():\n    pass\na()
    E306: def a():\n    def b():\n        pass\n    def c():\n        pass

🌿37 extraneous_whitespace(logical_line)

extraneous_whitespace(logical_line), module=pycodestyle, line:417 at site-packages\pycodestyle.py

避免多余的空白。
    在这些情况下避免使用多余的空格:
        -立即在圆括号,括号或大括号内。
        —紧接在逗号、分号或冒号前。
    Okay: spam(ham[1], {eggs: 2})
    E201: spam( ham[1], {eggs: 2})
    E201: spam(ham[ 1], {eggs: 2})
    E201: spam(ham[1], { eggs: 2})
    E202: spam(ham[1], {eggs: 2} )
    E202: spam(ham[1 ], {eggs: 2})
    E202: spam(ham[1], {eggs: 2 })

    E203: if x == 4: print x, y; x, y = y , x
    E203: if x == 4: print x, y ; x, y = y, x
    E203: if x == 4 : print x, y; x, y = y, x

🌿38 whitespace_around_keywords(logical_line)

whitespace_around_keywords(logical_line), module=pycodestyle, line:450 at site-packages\pycodestyle.py

避免在关键字周围使用多余的空白。
    Okay: True and False
    E271: True and  False
    E272: True  and False
    E273: True and\tFalse
    E274: True\tand False

🌿39 missing_whitespace_after_keyword(logical_line, tokens)

missing_whitespace_after_keyword(logical_line, tokens), module=pycodestyle, line:474 at site-packages\pycodestyle.py

关键字后面应该有空格。
    Okay: from foo import (bar, baz)
    E275: from foo import(bar, baz)
    E275: from importable.module import(bar, baz)
    E275: if(foo): bar

🌿40 missing_whitespace(logical_line)

missing_whitespace(logical_line), module=pycodestyle, line:497 at site-packages\pycodestyle.py

每个逗号、分号或冒号后面都应该有空格。
    Okay: [a, b]
    Okay: (3,)
    Okay: a[3,] = 1
    Okay: a[1:4]
    Okay: a[:4]
    Okay: a[1:]
    Okay: a[1:4:2]
    E231: ['a','b']
    E231: foo(bar,baz)
    E231: [{'a':'b'}]

🌿41 indentation(logical_line, previous_logical, indent_char, indent_level, previous_indent_level, indent_size)

indentation(logical_line, previous_logical, indent_char, indent_level, previous_indent_level, indent_size), module=pycodestyle, line:528 at site-packages\pycodestyle.py

每个缩进级别使用缩进大小(PEP8规定为4)空格。
    对于你不想弄乱的旧代码,你可以继续使用8空格制表符。
    Okay: a = 1
    Okay: if a == 0:\n    a = 1
    E111:   a = 1
    E114:   # a = 1

    Okay: for item in items:\n    pass
    E112: for item in items:\npass
    E115: for item in items:\n# Hi\n    pass

    Okay: a = 1\nb = 2
    E113: a = 1\n    b = 2
    E116: a = 1\n    # b = 2

🌿42 continued_indentation(logical_line, tokens, indent_level, hang_closing, indent_char, indent_size, noqa, verbose)

continued_indentation(logical_line, tokens, indent_level, hang_closing, indent_char, indent_size, noqa, verbose), module=pycodestyle, line:570 at site-packages\pycodestyle.py

延续行缩进。
    延续行应该使用Python隐式的圆括号、方括号和大括号内的行连接垂直对齐换行元素,或者使用悬挂缩进。
    当使用悬挂缩进时,应该考虑以下几点:
        -第一行上不应该有参数,并且
        -应该使用进一步的缩进来清楚地区分自己是一个延续行。
    Okay: a = (\n)
    E123: a = (\n    )

    Okay: a = (\n    42)
    E121: a = (\n   42)
    E122: a = (\n42)
    E123: a = (\n    42\n    )
    E124: a = (24,\n     42\n)
    E125: if (\n    b):\n    pass
    E126: a = (\n        42)
    E127: a = (24,\n      42)
    E128: a = (24,\n    42)
    E129: if (a or\n    b):\n    pass
    E131: a = (\n    42\n 24)

🌿43 whitespace_before_parameters(logical_line, tokens)

whitespace_before_parameters(logical_line, tokens), module=pycodestyle, line:777 at site-packages\pycodestyle.py

避免多余的空白。
    在以下情况下避免多余的空白:
        -在函数调用的参数列表开始的圆括号之前。
        -在开始索引或切片的左括号之前。
    Okay: spam(1)
    E211: spam (1)

    Okay: dict['key'] = list[index]
    E211: dict ['key'] = list[index]
    E211: dict['key'] = list [index]

🌿44 whitespace_around_operator(logical_line)

whitespace_around_operator(logical_line), module=pycodestyle, line:817 at site-packages\pycodestyle.py

避免在操作符周围使用多余的空白。
    Okay: a = 12 + 3
    E221: a = 4  + 5
    E222: a = 4 +  5
    E223: a = 4\t+ 5
    E224: a = 4 +\t5

🌿45 missing_whitespace_around_operator(logical_line, tokens)

missing_whitespace_around_operator(logical_line, tokens), module=pycodestyle, line:841 at site-packages\pycodestyle.py

在操作符的两侧使用一个空格。
    -总是在这些二元操作符的两边用一个空格括起来:
        赋值(=),增广赋值(+=,-=等),比较(=,<,>,!=,<=,>=,in, not in, is, is not),布尔值(and, or, not)。
    —如果使用不同优先级的操作符,请考虑在优先级最低的操作符周围添加空白。

    Okay: i = i + 1
    Okay: submitted += 1
    Okay: x = x * 2 - 1
    Okay: hypot2 = x * x + y * y
    Okay: c = (a + b) * (a - b)
    Okay: foo(bar, key='word', *args, **kwargs)
    Okay: alpha[:-i]

    E225: i=i+1
    E225: submitted +=1
    E225: x = x /2 - 1
    E225: z = x **y
    E225: z = 1and 1
    E226: c = (a+b) * (a-b)
    E226: hypot2 = x*x + y*y
    E227: c = a|b
    E228: msg = fmt%(errno, errmsg)

🌿46 whitespace_around_comma(logical_line)

whitespace_around_comma(logical_line), module=pycodestyle, line:956 at site-packages\pycodestyle.py

避免逗号或冒号后面出现多余的空白。
    注意:这些检查在默认情况下是禁用的
    Okay: a = (1, 2)
    E241: a = (1,  2)
    E242: a = (1,\t2)

🌿47 whitespace_around_named_parameter_equals(logical_line, tokens)

whitespace_around_named_parameter_equals(logical_line, tokens), module=pycodestyle, line:975 at site-packages\pycodestyle.py

不要在函数参数中的'='符号周围使用空格。
当用于指示关键字参数或默认形参值时,不要在'='符号周围使用空格,除非使用类型注释。
    Okay: def complex(real, imag=0.0):
    Okay: return magic(r=real, i=imag)
    Okay: boolean(a == b)
    Okay: boolean(a != b)
    Okay: boolean(a <= b)
    Okay: boolean(a >= b)
    Okay: def foo(arg: int = 42):
    Okay: async def foo(arg: int = 42):

    E251: def complex(real, imag = 0.0):
    E251: return magic(r = real, i = imag)
    E252: def complex(real, image: float=0.0):

🌿48 whitespace_before_comment(logical_line, tokens)

whitespace_before_comment(logical_line, tokens), module=pycodestyle, line:1041 at site-packages\pycodestyle.py

将内联注释分开至少两个空格。
    内联注释是与语句在同一行的注释。
    内联注释与语句之间应该至少间隔两个空格。它们应该以#和一个空格开头。
    块注释的每一行都以#和一个或多个空格开头,因为注释中可以有缩进的文本。
    Okay: x = x + 1  # Increment x
    Okay: x = x + 1    # Increment x
    Okay: # Block comments:
    Okay: #  - Block comment list
    Okay: #  - Block comment list
    E261: x = x + 1 # Increment x
    E262: x = x + 1  #Increment x
    E262: x = x + 1  #  Increment x
    E262: x = x + 1  #  Increment x
    E265: #Block comment
    E266: ### Block comment

🌿49 imports_on_separate_lines(logical_line)

imports_on_separate_lines(logical_line), module=pycodestyle, line:1086 at site-packages\pycodestyle.py

将导入放到单独的行上。
    Okay: import os\nimport sys
    E401: import sys, os

    Okay: from subprocess import Popen, PIPE
    Okay: from myclas import MyClass
    Okay: from foo.bar.yourclass import YourClass
    Okay: import myclass
    Okay: import foo.bar.yourclass

🌿50 module_imports_on_top_of_file(logical_line, indent_level, checker_state, noqa)

module_imports_on_top_of_file(logical_line, indent_level, checker_state, noqa), module=pycodestyle, line:1106 at site-packages\pycodestyle.py

将导入放在文件的顶部。
    总是把导入放在文件的顶部,就在模块注释和文档字符串之后,模块全局变量和常量之前。
    Okay: import os
    Okay: # this is a comment\nimport os
    Okay: '''this is a module docstring'''\nimport os
    Okay: r'''this is a module docstring'''\nimport os
    Okay:
    try:\n\timport x\nexcept ImportError:\n\tpass\nelse:\n\tpass\nimport y
    Okay:
    try:\n\timport x\nexcept ImportError:\n\tpass\nfinally:\n\tpass\nimport y
    E402: a=1\nimport os
    E402: 'One string'\n"Two string"\nimport os
    E402: a=1\nfrom sys import x

    Okay: if x:\n    import os

🌿51 compound_statements(logical_line)

compound_statements(logical_line), module=pycodestyle, line:1165 at site-packages\pycodestyle.py

通常不鼓励使用复合语句(在同一行)。
    虽然有时将if/for/ While语句与一个小体放在同一行是可以的,但对于多子句语句永远不要这样做。
    也要避免折叠这么长的线!始终使用def语句,而不是将lambda表达式直接绑定到名称的赋值语句。

    Okay: if foo == 'blah':\n    do_blah_thing()
    Okay: do_one()
    Okay: do_two()
    Okay: do_three()

    E701: if foo == 'blah': do_blah_thing()
    E701: for x in lst: total += x
    E701: while t < 10: t = delay()
    E701: if foo == 'blah': do_blah_thing()
    E701: else: do_non_blah_thing()
    E701: try: something()
    E701: finally: cleanup()
    E701: if foo == 'blah': one(); two(); three()
    E702: do_one(); do_two(); do_three()
    E703: do_four();  # useless semicolon
    E704: def f(x): return 2*x
    E731: f = lambda x: 2*x

🌿52 explicit_line_join(logical_line, tokens)

explicit_line_join(logical_line, tokens), module=pycodestyle, line:1229 at site-packages\pycodestyle.py

避免括号之间显式的行连接。
    换行的首选方法是在括号、方括号和大括号内使用Python隐含的行延续。
    通过将表达式括在括号中,可以将长行分隔成多行。
    这些应该优先于使用反斜杠进行行延续。
    E502: aaa = [123, \\n       123]
    E502: aaa = ("bbb " \\n       "ccc")

    Okay: aaa = [123,\n       123]
    Okay: aaa = ("bbb "\n       "ccc")
    Okay: aaa = "bbb " \\n    "ccc"
    Okay: aaa = 123  # \\

🌿53 _is_binary_operator(token_type, text)

_is_binary_operator(token_type, text), module=pycodestyle, line:1276 at site-packages\pycodestyle.py

🌿54 _break_around_binary_operators(tokens)

_break_around_binary_operators(tokens), module=pycodestyle, line:1285 at site-packages\pycodestyle.py

私人功能,以减少重复。
    这就把 :func:`break_before_binary_operator` 和 :func:`break_after_binary_operator` 的共享细节分解出来了。

🌿55 break_before_binary_operator(logical_line, tokens)

break_before_binary_operator(logical_line, tokens), module=pycodestyle, line:1311 at site-packages\pycodestyle.py

避免在二进制操作符之前中断。
    绕过二进制运算符的最佳位置是在运算符之后,而不是在运算符之前。
    W503: (width == 0\n + height == 0)
    W503: (width == 0\n and height == 0)
    W503: var = (1\n       & ~2)
    W503: var = (1\n       / -2)
    W503: var = (1\n       + -1\n       + -2)

    Okay: foo(\n    -x)
    Okay: foo(x\n    [])
    Okay: x = '''\n''' + ''
    Okay: foo(x,\n    -y)
    Okay: foo(x,  # comment\n    -y)

🌿56 break_after_binary_operator(logical_line, tokens)

break_after_binary_operator(logical_line, tokens), module=pycodestyle, line:1341 at site-packages\pycodestyle.py

避免在二进制运算符之后中断。
    绕过二进制运算符的最佳位置是在运算符之前,而不是之后。
    W504: (width == 0 +\n height == 0)
    W504: (width == 0 and\n height == 0)
    W504: var = (1 &\n       ~2)

    Okay: foo(\n    -x)
    Okay: foo(x\n    [])
    Okay: x = '''\n''' + ''
    Okay: x = '' + '''\n'''
    Okay: foo(x,\n    -y)
    Okay: foo(x,  # comment\n    -y)
    下面应该是W504,但是unary_context在这方面很棘手
    Okay: var = (1 /\n       -2)
    Okay: var = (1 +\n       -1 +\n       -2)

🌿57 comparison_to_singleton(logical_line, noqa)

comparison_to_singleton(logical_line, noqa), module=pycodestyle, line:1376 at site-packages\pycodestyle.py

与单例的比较应该使用“is”或“is not”。
    与None这样的单例比较应该总是使用"is"或"is not",而不是相等操作符。
    Okay: if arg is not None:
    E711: if arg != None:
    E711: if None == arg:
    E712: if arg == True:
    E712: if False == arg:
    另外,当你真正的意思是如果x不是None时,注意不要写if x
    -例如,当测试默认为None的变量或参数是否被设置为其他值时。另一个值的类型(例如容器)在布尔上下文中可能为false !

🌿58 comparison_negative(logical_line)

comparison_negative(logical_line), module=pycodestyle, line:1413 at site-packages\pycodestyle.py

否定比较应该使用“not in”和“is not”。
    Okay: if x not in y:\n    pass
    Okay: assert (X in Y or X is Z)
    Okay: if not (X in Y):\n    pass
    Okay: zz = x is not y
    E713: Z = not X in Y
    E713: if not X.B in Y:\n    pass
    E714: if not X is Y:\n    pass
    E714: Z = not X.B is Y

🌿59 comparison_type(logical_line, noqa)

comparison_type(logical_line, noqa), module=pycodestyle, line:1435 at site-packages\pycodestyle.py

对象类型比较应该始终使用isinstance()。
    不要直接比较类型。
    Okay: if isinstance(obj, int):
    E721: if type(obj) is type(1):
    当检查一个对象是否是字符串时,请记住它也可能是unicode字符串!
    在Python 2.3中,str和unicode有一个共同的基类basestring,所以你可以这样做:
    Okay: if isinstance(obj, basestring):
    Okay: if type(a1) is type(b1):

🌿60 bare_except(logical_line, noqa)

bare_except(logical_line, noqa), module=pycodestyle, line:1459 at site-packages\pycodestyle.py

在捕获异常时,尽可能提及特定的异常。
    Okay: except Exception:
    Okay: except BaseException:
    E722: except:

🌿61 ambiguous_identifier(logical_line, tokens)

ambiguous_identifier(logical_line, tokens), module=pycodestyle, line:1476 at site-packages\pycodestyle.py

永远不要使用字符“l”、“O”或“I”作为变量名。
    在某些字体中,这些字符与数字1和0无法区分。当你想用“l”的时候,就用“L”代替。
    Okay: L = 0
    Okay: o = 123
    Okay: i = 42
    E741: l = 0
    E741: O = 123
    E741: I = 42
    变量可以在其他几个上下文中绑定,包括类和函数定义、lambda函数、“全局”和“非局部”语句、异常处理程序以及“with”和“for”语句。

    Okay: except AttributeError as o:
    Okay: with lock as L:
    Okay: foo(l=12)
    Okay: foo(l=I)
    Okay: for a in foo(l=12):
    Okay: lambda arg: arg * l
    Okay: lambda a=l[I:5]: None
    Okay: lambda x=a.I: None
    Okay: if l >= 12:
    E741: except AttributeError as O:
    E741: with lock as l:
    E741: global I
    E741: nonlocal l
    E741: def foo(l):
    E741: def foo(l=12):
    E741: l = foo(l=12)
    E741: for l in range(10):
    E741: [l for l in lines if l]
    E741: lambda l: None
    E741: lambda a=x[1:5], l: None
    E741: lambda **l:
    E741: def f(**l):
    E742: class I(object):
    E743: def l(x):

🌿62 python_3000_invalid_escape_sequence(logical_line, tokens, noqa)

python_3000_invalid_escape_sequence(logical_line, tokens, noqa), module=pycodestyle, line:1576 at site-packages\pycodestyle.py

无效转义序列在Python 3.6中已弃用。
    Okay: regex = r'\.png$'
    W605: regex = '\.png$'

🌿63 python_3000_async_await_keywords(logical_line, tokens)

python_3000_async_await_keywords(logical_line, tokens), module=pycodestyle, line:1636 at site-packages\pycodestyle.py

从Python 3.7开始,'async'和'await'是保留关键字。
    W606: async = 42
    W606: await = 42
    Okay: async def read(db):
    data = await db.fetch('SELECT ...')

🌿64 maximum_doc_length(logical_line, max_doc_length, noqa, tokens)

maximum_doc_length(logical_line, max_doc_length, noqa, tokens), module=pycodestyle, line:1707 at site-packages\pycodestyle.py

将所有文档行限制为最多72个字符。
    对于长文本块(文档字符串或注释),建议将长度限制为72个字符。
    报告警告W505

🌿65 readlines(filename)

readlines(filename), module=pycodestyle, line:1760 at site-packages\pycodestyle.py

阅读源代码。

🌿66 stdin_get_value()

stdin_get_value(), module=pycodestyle, line:1771 at site-packages\pycodestyle.py

从stdin中读取值。

🌿67 expand_indent(line)

expand_indent(line), module=pycodestyle, line:1779 at site-packages\pycodestyle.py

返回缩进量。
    制表符将展开到下一个8的倍数。
    >>> expand_indent('    ')
    4
    >>> expand_indent('\t')
    8
    >>> expand_indent('       \t')
    8
    >>> expand_indent('        \t')
    16

🌿68 mute_string(text)

mute_string(text), module=pycodestyle, line:1807 at site-packages\pycodestyle.py

将内容替换为'xxx'以防止语法匹配。
    >>> mute_string('"abc"')
    '"xxx"'
    >>> mute_string("'''abc'''")
    "'''xxx'''"
    >>> mute_string("r'abc'")
    "r'xxx'"

🌿69 parse_udiff(diff, patterns=None, parent=‘.’)

parse_udiff(diff, patterns=None, parent=‘.’), module=pycodestyle, line:1827 at site-packages\pycodestyle.py

返回匹配行的字典。

🌿70 normalize_paths(value, parent=‘.’)

normalize_paths(value, parent=‘.’), module=pycodestyle, line:1856 at site-packages\pycodestyle.py

解析以逗号分隔的路径列表。返回一个绝对路径列表。

🌿71 filename_match(filename, patterns, default=True)

filename_match(filename, patterns, default=True), module=pycodestyle, line:1874 at site-packages\pycodestyle.py

检查patterns是否包含与filename匹配的模式。
    如果patterns未指定,则总是返回True。

🌿72 update_counts(s, counts)

update_counts(s, counts), module=pycodestyle, line:1884 at site-packages\pycodestyle.py

对于计数中的字符,将s中的字符每次出现的次数加1

🌿73 _is_eol_token(token)

_is_eol_token(token), module=pycodestyle, line:1892 at site-packages\pycodestyle.py

🌿74 get_parser(prog=‘pycodestyle’, version=‘2.10.0’)

get_parser(prog=‘pycodestyle’, version=‘2.10.0’), module=pycodestyle, line:2481 at site-packages\pycodestyle.py

为程序创建解析器。

🌿75 read_config(options, args, arglist, parser)

read_config(options, args, arglist, parser), module=pycodestyle, line:2551 at site-packages\pycodestyle.py

读取和解析配置。
    如果在命令行中使用“--config”选项指定了配置文件,那么只有它被用于配置。
    否则,用户配置(~/.config/pycodestyle)和当前目录或以上目录中的任何本地配置将使用ConfigParser的read方法合并在一起(按此顺序)。

🌿76 process_options(arglist=None, parse_argv=False, config_file=None, parser=None, verbose=None)

process_options(arglist=None, parse_argv=False, config_file=None, parser=None, verbose=None), module=pycodestyle, line:2626 at site-packages\pycodestyle.py

通过参数列表或命令行参数传递的进程选项。
    传入``config_file``参数允许其他工具,如flake8指定自己的选项以pycodestyle进行处理。

🌿77 _parse_multi_options(options, split_token=‘,’)

_parse_multi_options(options, split_token=‘,’), module=pycodestyle, line:2681 at site-packages\pycodestyle.py

拆开,剥去,丢弃空的。
    把下面的句子变成:
    A,
    B,
    into ["A", "B"]

🌿78 _main()

_main(), module=pycodestyle, line:2697 at site-packages\pycodestyle.py

解析选项并在Python源代码上运行检查。

🔵类

🌿79 optparse.OptionParser

OptionParser, optparse.OptionParser, module=optparse, line:0 at

解析器的命令行选项。

🌿80 pycodestyle.Checker

Checker, pycodestyle.Checker, module=pycodestyle, line:1901 at site-packages\pycodestyle.py

加载Python源文件,标记它,检查编码风格。
method
1 build_tokens_line(self)

kind=method class=Checker objtype=function line:1997 at …\lib\site-packages\pycodestyle.py

从令牌构建逻辑行。
2 check_all(self, expected=None, line_offset=0)

kind=method class=Checker objtype=function line:2134 at …\lib\site-packages\pycodestyle.py

对输入文件运行所有检查。
3 check_ast(self)

kind=method class=Checker objtype=function line:2065 at …\lib\site-packages\pycodestyle.py

构建文件的AST并运行所有AST检查。
4 check_logical(self)

kind=method class=Checker objtype=function line:2030 at …\lib\site-packages\pycodestyle.py

从令牌构建一行,并在其上运行所有逻辑检查。
5 check_physical(self, line)

kind=method class=Checker objtype=function line:1985 at …\lib\site-packages\pycodestyle.py

在原始输入行上运行所有物理检查。
6 generate_tokens(self)

kind=method class=Checker objtype=function line:2077 at …\lib\site-packages\pycodestyle.py

标记文件,运行物理行检查并生成标记。
7 init_checker_state(self, name, argument_names)

kind=method class=Checker objtype=function line:1980 at …\lib\site-packages\pycodestyle.py

为特定的检查器插件准备自定义状态。
8 maybe_check_physical(self, token, prev_physical)

kind=method class=Checker objtype=function line:2094 at …\lib\site-packages\pycodestyle.py

如果合适的话,检查当前的物理线路。
9 readline(self)

kind=method class=Checker objtype=function line:1963 at …\lib\site-packages\pycodestyle.py

从输入缓冲区中获取下一行。
10 report_invalid_syntax(self)

kind=method class=Checker objtype=function line:1950 at …\lib\site-packages\pycodestyle.py

检查语法是否有效。
11 run_check(self, check, argument_names)

kind=method class=Checker objtype=function line:1973 at …\lib\site-packages\pycodestyle.py

运行检查插件。

🌿81 pycodestyle.BaseReport

BaseReport, pycodestyle.BaseReport, module=pycodestyle, line:2180 at site-packages\pycodestyle.py

收集检查结果。
data

1 print_filename=False kind:data type:bool class:<class ‘pycodestyle.BaseReport’>

method
2 error(self, line_number, offset, text, check)

kind=method class=BaseReport objtype=function line:2216 at …\lib\site-packages\pycodestyle.py

根据选项报告错误。
3 get_count(self, prefix=‘’)

kind=method class=BaseReport objtype=function line:2239 at …\lib\site-packages\pycodestyle.py

返回错误和警告的总数。
4 get_file_results(self)

kind=method class=BaseReport objtype=function line:2235 at …\lib\site-packages\pycodestyle.py

返回该文件的错误和警告计数。
5 get_statistics(self, prefix=‘’)

kind=method class=BaseReport objtype=function line:2244 at …\lib\site-packages\pycodestyle.py

获取以该前缀开头的消息代码的统计信息。
    prefix='' 匹配所有错误和警告前缀
    prefix='E' 匹配所有错误前缀
    prefix='W' 匹配所有警告前缀
    prefix='E4' 匹配所有与导入有关的错误
6 increment_logical_line(self)

kind=method class=BaseReport objtype=function line:2212 at …\lib\site-packages\pycodestyle.py

标记一条新的逻辑线。
7 init_file(self, filename, lines, expected, line_offset)

kind=method class=BaseReport objtype=function line:2202 at …\lib\site-packages\pycodestyle.py

给新文件发信号。
8 print_benchmark(self)

kind=method class=BaseReport objtype=function line:2260 at …\lib\site-packages\pycodestyle.py

打印基准数据。
9 print_statistics(self, prefix=‘’)

kind=method class=BaseReport objtype=function line:2255 at …\lib\site-packages\pycodestyle.py

打印总体统计信息(错误和警告的数量)。
10 start(self)

kind=method class=BaseReport objtype=function line:2194 at …\lib\site-packages\pycodestyle.py

启动计时器。
11 stop(self)

kind=method class=BaseReport objtype=function line:2198 at …\lib\site-packages\pycodestyle.py

停止计时器。

🌿82 pycodestyle.FileReport

FileReport, pycodestyle.FileReport, module=pycodestyle, line:2270 at site-packages\pycodestyle.py

收集检查结果并打印文件名。
data

1 print_filename=True kind:data type:bool class:<class ‘pycodestyle.FileReport’>

🌿83 pycodestyle.StandardReport

StandardReport, pycodestyle.StandardReport, module=pycodestyle, line:2276 at site-packages\pycodestyle.py

收集并打印检查结果。
method
1 error(self, line_number, offset, text, check)

kind=method class=StandardReport objtype=function line:2293 at …\lib\site-packages\pycodestyle.py

根据选项报告错误。
2 get_file_results(self)

kind=method class=StandardReport objtype=function line:2301 at …\lib\site-packages\pycodestyle.py

打印结果并返回该文件的总计数。
3 init_file(self, filename, lines, expected, line_offset)

kind=method class=StandardReport objtype=function line:2287 at …\lib\site-packages\pycodestyle.py

给新文件发信号。

🌿84 pycodestyle.DiffReport

DiffReport, pycodestyle.DiffReport, module=pycodestyle, line:2330 at site-packages\pycodestyle.py

仅收集和打印更改行的结果。
method
1 error(self, line_number, offset, text, check)

kind=method class=DiffReport objtype=function line:2337 at …\lib\site-packages\pycodestyle.py

🌿85 pycodestyle.StyleGuide

StyleGuide, pycodestyle.StyleGuide, module=pycodestyle, line:2343 at site-packages\pycodestyle.py

初始化带有少量选项的PEP-8实例。
method
1 check_files(self, paths=None)

kind=method class=StyleGuide objtype=function line:2389 at …\lib\site-packages\pycodestyle.py

对路径执行所有检查。
2 excluded(self, filename, parent=None)

kind=method class=StyleGuide objtype=function line:2439 at …\lib\site-packages\pycodestyle.py

检查是否应该排除该文件。
    检查它的选项'options.exclude'是否包含一个模式匹配的文件名。
3 get_checks(self, argument_name)

kind=method class=StyleGuide objtype=function line:2467 at …\lib\site-packages\pycodestyle.py

得到这个类别的所有检查。
    查找所有全局可见的函数,其中第一个参数名称以参数名称开头,并且包含选定的测试。
4 ignore_code(self, code)

kind=method class=StyleGuide objtype=function line:2454 at …\lib\site-packages\pycodestyle.py

检查是否应该忽略错误代码。
    如果'options.select'包含错误码的前缀,返回False。
    否则,if 'options.ignore'包含错误代码的前缀,返回True。
5 init_report(self, reporter=None)

kind=method class=StyleGuide objtype=function line:2384 at …\lib\site-packages\pycodestyle.py

初始化报表实例。
6 input_dir(self, dirname)

kind=method class=StyleGuide objtype=function line:2415 at …\lib\site-packages\pycodestyle.py

检查此目录和所有子目录中的所有文件。
7 input_file(self, filename, lines=None, expected=None, line_offset=0)

kind=method class=StyleGuide objtype=function line:2407 at …\lib\site-packages\pycodestyle.py

对Python源文件运行所有检查。

🔵私有或局部

86 _checks {‘physical_line’: {<function tabs_or_spaces at 0x0000020A3540D9D8>: ([‘E101’], [‘physical_line’, ‘indent_char’]), <funct…
87 _get_parameters <function _get_parameters at 0x0000020A353B34C8>
88 _is_one_liner <function _is_one_liner at 0x0000020A35414168>
89 _SYMBOLIC_OPS frozenset({‘(’, ‘;’, ‘,’, ‘:’, ‘{’, ‘~’, ‘.’, ‘…’, ‘[’, ‘=’, ‘)’, ‘@’, ‘]’, ‘}’, ‘%’})
90 _is_binary_operator <function _is_binary_operator at 0x0000020A35446D38>
91 _break_around_binary_operators <function _break_around_binary_operators at 0x0000020A35446DC8>
92 _is_eol_token <function _is_eol_token at 0x0000020A3544D8B8>
93 _parse_multi_options <function _parse_multi_options at 0x0000020A35453048>
94 _main <function _main at 0x0000020A354530D8>

🔵剩余

95 loader <_frozen_importlib_external.SourceFileLoader object at 0x0000020A330697C8>
96 spec ModuleSpec(name=‘pycodestyle’, loader=<frozen_importlib_external.SourceFileLoader object at 0x0000020A330697C8>, origin=‘…\lib\site-packages\pycodestyle.py’)
97 SINGLETONS frozenset({‘True’, ‘None’, ‘False’})
98 KEYWORDS frozenset({‘async’, ‘finally’, ‘from’, ‘for’, ‘nonlocal’, ‘import’, ‘or’, ‘yield’, ‘is’, ‘await’, ‘print’, ‘and’, ‘if’, ‘class’, ‘lambda’, ‘continue’, ‘global’, ‘in’, ‘elif’, ‘as’, ‘def’, ‘not’, ‘break’, ‘pass’, ‘return’, ‘assert’, ‘with’, ‘try’, ‘while’, ‘raise’, ‘else’, ‘del’, ‘except’})
99 UNARY_OPERATORS frozenset({‘-’, ‘>>’, ‘+’, ‘‘, ‘*’})
100 ARITHMETIC_OP frozenset({’-', ‘+’, ‘/’, '
’, ‘@’, ‘//’, ‘‘})
101 WS_OPTIONAL_OPERATORS frozenset({’<<', ‘/’, ‘**’, ‘-’, ‘>>’, ‘&’, ‘+’, ‘|’, ‘^’, ‘@’, ‘//’, '
’, ‘%’})
102 WS_NEEDED_OPERATORS frozenset({‘=‘, ‘/=’, ‘->’, ‘**=’, ‘|=’, ‘or’, ‘is’, ‘>’, ‘and’, ‘>=’, ‘<<=’, ‘%=’, ‘-=’, ‘>>=’, ‘&=’, ‘<=’, ‘^=’, ‘<’, ‘in’, ‘!=’, ‘//=’, ‘+=’, ‘<>’, ‘=’, ‘==’})
103 WHITESPACE frozenset({’ ‘, ‘\t’, ‘\xa0’})
104 NEWLINE frozenset({56, 4})
105 SKIP_TOKENS frozenset({56, 4, 5, 6})
106 SKIP_COMMENTS frozenset({4, 5, 6, 54, 55, 56})
107 INDENT_REGEX re.compile(’([ \t]
)’)
108 ERRORCODE_REGEX re.compile(‘\b[A-Z]\d{3}\b’)
109 DOCSTRING_REGEX re.compile(‘u?r?["\’]‘)
110 EXTRANEOUS_WHITESPACE_REGEX re.compile(’\[({][ \t]|[ \t][\]}),;:‘)
111 WHITESPACE_AFTER_COMMA_REGEX re.compile(’[,;:]\s*(?: |\t)‘)
112 COMPARE_SINGLETON_REGEX re.compile(’(\bNone|\bFalse|\bTrue)?\s*([=!]=)\s*(?(1)|(None|False|True))\b’)
113 COMPARE_NEGATIVE_REGEX re.compile(‘\b(?<!is\s)(not)\s+[^][)(}{ ]+\s+(in|is)\s’)
114 COMPARE_TYPE_REGEX re.compile(‘(?:[=!]=|is(?:\s+not)?)\s+type(?😒.\w+Type|\s*\(\s*([)]*[ )])\s*\))’)
115 KEYWORD_REGEX re.compile(‘(\s*)\b(?:async|finally|from|for|nonlocal|import|or|yield|is|await|print|and|if|class|lambda|continue|global|in|elif|as|def|not|break|pass|return|assert|with|try|while|raise|else|del|except)\b(\s)
116 OPERATOR_REGEX re.compile(’(?:[,\s])(\s*)(?:[-+*/|!<=>%&]+|:=)(\s*)‘)
117 LAMBDA_REGEX re.compile(’\blambda\b’)
118 HUNK_REGEX re.compile(‘^@@ -\d+(?:,\d+)? \+(\d+)(?😢\d+))? @@.$‘)
119 STARTSWITH_DEF_REGEX re.compile(’^(async\s+def|def)\b’)
120 STARTSWITH_TOP_LEVEL_REGEX re.compile(‘^(async\s+def\s+|def\s+|class\s+|@)’)
121 STARTSWITH_INDENT_STATEMENT_REGEX re.compile('^\s
(def|async\s+def|for|async\s+for|if|elif|else|try|except|finally|with|async\s+with|class|while)\b’)
122 DUNDER_REGEX re.compile('__([\s]+)__(?::\s*[a-zA-Z.0-9
\[\]\"]+)? = ‘)
123 BLANK_EXCEPT_REGEX re.compile(‘except\s*:’)
124 _SYMBOLIC_OPS frozenset({’(', ‘;’, ‘,’, ‘:’, ‘{’, ‘~’, ‘.’, ‘…’, ‘[’, ‘=’, ‘)’, ‘@’, ‘]’, ‘}’, ‘%’})
125 noqa <functools._lru_cache_wrapper object at 0x0000020A3543A0E8>

☘️【bisect】

bisect, fullname=bisect, file=bisect.py

☘️【configparser】

configparser, fullname=configparser, file=configparser.py

☘️【inspect】

inspect, fullname=inspect, file=inspect.py

☘️【io】

io, fullname=io, file=io.py

☘️【keyword】

keyword, fullname=keyword, file=keyword.py

☘️【os】

os, fullname=os, file=os.py

☘️【re】

re, fullname=re, file=re.py

☘️【sys】

sys, fullname=sys, file=

☘️【time】

time, fullname=time, file=

☘️【tokenize】

tokenize, fullname=tokenize, file=tokenize.py

☘️【warnings】

warnings, fullname=warnings, file=warnings.py

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AhcaoZhu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值