跳转至

Flake8 PEP8代码规范检查

概要: flake8在检查Python代码格式规范的使用方法

创建时间: 2022.10.02 17:57:56

更新时间: 2023.07.28 22:41:19

PEP8规范

PEP 8是Python代码风格规范,统一代码风格的重要意义在于“代码被阅读的时间要远大于被编写的时间”,所以代码的可读性极其重要,除非你写的是一次性代码,用完即扔。

Flake8工具

Flake8是 pycodestyle(Python代码风格检查工具), PyFlakes(Python代码错误检查工具), McCabe(Python代码圈复杂度检查工具)三者合一的Python代码检查工具。除了兼具上面三个工具的功能,还支持海量的扩展,提供更多更全面的检查或其他功能。
Flake8及其扩展可以融合到Python项目的CI流水线中对代码进行检查,避免坏代码合入到项目,延缓项目代码腐化。

Flake8扩展

Flake8支持周边扩展,提供Flake8工具原生不支持的检查功能(原生支持的类型及错误码参考 Error / Violation Codes — flake8 5.0.4 documentation)。推荐DmytroLitvinov/awesome-flake8-extensions: A curated awesome list of flake8 extensions. Feel free to contribute!项目来选择合适的扩展,此处介绍几个常用的扩展如下,按照字母顺序排序。

测试平台

Python 3.10.4
macOS 12.6 (M1 Max)

警告

mkdocs会将代码最后的空行自动移除

flake8-builtins

提示

flake8-builtins用于检查是否代码中是否使用了Python的内置类型作为变量或者参数名

坏代码示例

Python
str = 'abc'
print(str)
运行检查
Python
pip install flake8 flake8-builtins
flake8 bad_code.py 
检查结果
Text Only
bad_code.py:1:1: A001 variable "str" is shadowing a python builtin

flake8-docstring-checker

提示

flake8-docstring-checker 用于检查Python代码文档是否齐全

ID Description
DC100 Module has no docstring
DC101 Missing docstring in class
DC102 Missing docstring in public function
DC103 Missing docstring in private function
DC104 Missing docstring in special function

坏代码示例

Python
1
2
3
4
5
6
7
8
9
import datetime


class MyDateTime:
    def get_now(self):
        return self._to_string(datetime.datetime.now())

    def _to_string(self, dt):
        return str(dt)
运行检查
Python
pip install flake8 flake8-docstring-checker
flake8 bad_code.py 
检查结果
Text Only
1
2
3
4
bad_code.py:0:1: DC100 Module has no docstring
bad_code.py:4:1: DC101 Missing docstring in class MyDateTime
bad_code.py:5:5: DC102 Missing docstring in public function get_now
bad_code.py:8:5: DC103 Missing docstring in private function _to_string
修复代码
Python
"""
this module to handle datetime
"""
import datetime


class MyDateTime:
    """handle datetime class
    """
    def get_now(self):
        """get now datetime string

        Returns:
            _type_: str
        """
        return self._to_string(datetime.datetime.now())

    def _to_string(self, dt):
        """convert datetime object to string

        Args:
            dt (_type_): datetime

        Returns:
            _type_: str
        """
        return str(dt)

flake8-html

提示

flake8-html用于将flake8的检查结果输出到html中,可以方便在浏览器中查看

警告

测试时 flake8-html 的版本为 0.4.2 ,不支持 flake8 5.0+版本,需要手动降级到 4.0.1

坏代码示例

Python
1
2
3
4
5
import os
def add(a,b):
    return a +b

print( add(3,   5) ) 
运行检查
Python
1
2
3
pip install flake8==4.0.1
pip install flake8-html
flake8 bad_code.py --format=html --htmldir=flake8-report
检查结果
Text Only
bad_code.py has issues: high: 1 medium: 8
查看浏览器
image.png
image.png
image.png
image.png

flake8-import-order

提示

flake8-import-order用于检查Python模块的导入顺序是否符合规范

坏代码示例

Python
1
2
3
4
5
6
7
import os
import datetime

if os.path.exists('./code.py'):
    x = datetime.datetime.today()
else:
    x = datetime.datetime.now()
运行检查
Python
pip install flake8 flake8-import-order
flake8 bad_code.py
检查结果
Text Only
bad_code.py:2:1: I100 Import statements are in the wrong order. 'import datetime' should be before 'import os'

pep8-naming

提示

pep8-naming用于检查代码中的命名是否符合规范,详见 Error Codes

坏代码示例

Python
1
2
3
class badClass():
    def CalcluateCube(cla, inNumber):
        return inNumber ** 3
运行检查
Python
pip install flake8 pep8-naming
flake8 bad_code.py
检查结果
Text Only
1
2
3
4
bad_code.py:1:8: N801 class name 'badClass' should use CapWords convention
bad_code.py:2:10: N802 function name 'CalcluateCube' should be lowercase
bad_code.py:2:24: N805 first argument of a method should be named 'self'
bad_code.py:2:29: N803 argument name 'inNumber' should be lowercase

flake8-print

提示

flake8-print用于检查代码中是否有print语句出现,如果在项目需要统一使用log输出,那么需要禁用print以保证输出形式规范

坏代码示例

Python
print('hello world')
运行检查
Python
pip install flake8 flake8-print
flake8 bad_code.py
检查结果
Text Only
bad_code.py:1:1: T201 print found.

flake8-requirements

提示

flake8-requirements用于检查代码中是否导入了某个模块却没有使用,或者使用了某个第三方模块却没有在requirements.txt中标明,此扩展有利于项目的依赖管理

坏代码示例

Python
1
2
3
from loguru import logger as log

log.info('hello world')
运行检查
Python
pip install flake8 flake8-requirements
flake8 bad_code.py
检查结果
Text Only
bad_code.py:1:1: I900 'loguru' not listed as a requirement

Flake8实践

配置文件 tox.ini

此文件放置于Python项目的根目录,用于归档Flake8的配置,详细配置方式参考 Configuring Flake8 — flake8 5.0.4 documentation 目前我的配置如下

Text Only
1
2
3
4
5
6
7
[flake8]
exclude = .git,.mypy_cache,flake8_report,__pycache__
format = html
htmldir = flake8-report
extend-ignore =
    DC100
max-line-length = 100

项目依赖 requirements.txt

此处记录需要安装的一些Flake8相关的依赖包

Text Only
1
2
3
4
5
6
7
8
flake8==4.0.1
flake8-builtins
flake8-docstring-checker
flake8-html
flake8-import-order
pep8-naming
flake8-print
flake8-requirements

参考

主要

扩展