0%

Python-代码规范

与 Python 编码规范相关的模块,如:

  • this:【标准库】python 之禅,The Zen of Python
  • flake8:PEP8(检查代码风格)+ Pyflakes(检查代码错误)+ McCabe(检查代码复杂度)等工具组合,用于检查 Python 代码风格和质量。
  • black:less is more,不妥协的代码格式化工具

概述

编码规范

pep8:Python 程序规范代码标准/风格指南

  • 建议:直接使用 IDE 的相关工具来实现规范。

this

this:【标准库】python 之禅,The Zen of Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

flake8

flake8:PEP8(检查代码风格)+ Pyflakes(检查代码错误)+ McCabe(检查代码复杂度)等工具组合,用于检查 Python 代码风格和质量。

pylint:检查违反 PEP8 规范和常见错误的库,静态检查,过于严格、速度慢些,OUT
mypy:Python 代码静态检查工具

1
flake8 test.py
1
2
3
4
5
6
7
--exclude : 排除的文件或者目录,使用逗号分割,可以是直接文件名,也可以是正则匹配的文件名,默认:default: .svn,CVS,.bzr,.hg,.git,__pycache
--filename : 要进行检测的文件,使用逗号分割,可以是直接文件名,也可以是正则匹配的文件名,默认:*.py
--select : 默认使用的错误和警告,默认关闭
--ignore : 如果你觉得 flake8 太严苛了,可以适当的调整下忽略下.,如果不设置,默认:E123/E133, E226 and E241/E242
--max-line-length : 一行最大的字符长度,默认:79,推荐 120
--format : 错误的显示格式
--max-complexity=12 : 复杂度因子, 常设 12 .

black

black:less is more,不妥协的代码格式化工具

autopep8:以最低限度的标准对不符合 pep8 标准的代码进行修正
yapf:旨在让代码看起来更整洁更友好,pep8 + 代码风格不一致的地方重新格式化。

  • 当前选择:blake,不妥协
  • 常见功能
    • 自动格式化代码,如重新缩进行、修复缩进、重构常见的比较错误等

遇到的问题

  • 问题:git 项目下 black 有点问题,报 UnicodeDecodeError: 'gbk' codec can't decode byte 0xb9 in position 20: illegal multibyte sequence
  • 解决方案:原因在于 black 的源代码中有个地方打开时没有加 encoding
1
2
# {python_dir}\lib\site-packages\black\__init__.py,line:5822,open()里加个 encoding
with gitignore.open(encoding='utf-8') as gf:
给博主来一杯卡布奇诺