py项目构建与维护
https://juejin.im/post/6869560352859193357
使用 black 和 isort 进行代码格式化
Black 是毫不妥协的 Python 代码格式化库。通过使用它,你将放弃手动调整代码格式的细节。作为回报,Black 可以带来速度、确定性和避免调整 Python 代码风格的烦恼,从而有更多的精力和时间放在更重要的事情上。 无论你正在阅读什么样的项目,用 black 格式化过的代码看起来都差不多。一段时间后格式不再是问题,这样你就可以更专注于内容。 black 通过减少代码的差异性,使代码检查更快。
安装: pip install black
默认一行限制在 88 个字符
https://github.com/PyCQA/isort
Black 和 isort 并不兼容的默认选项,因此我们将让 isort 遵循 black 的原则。创建一个 setup.cfg 文件并添加以下配置:
1 2 3 4 5 6 |
|
include_trailing_comma: 加入尾部逗号
使用:
格式化项目:项目根目录执行isort **/*.py && black .
格式某个文件:项目根目录执行isort xxx.py && black xxx.py
使用 flake8 保证代码风格
https://github.com/PyCQA/flake8
https://flake8.pycqa.org/en/latest/index.html#quickstart
安装:pip install flake8
更新: pip install --upgrade flake8
配置:
根目录下创建setup.cfg
文件
写入如下内容:
1 2 3 4 5 6 |
|
extend-ignore = E203
: 使用black
格式化时,会在切片的冒号前加空格,E203 不允许加空格,所以会有冲突
使用:在项目根目录下执行flake8 .
__init__.py
中报 F401 错误:可以在这一行后面加上# noqa: F401
例如:
1 |
|
如果__doc__
字符串太长报错 E501,也可以加上注释:# noqa: E501
取消检查
如果同时忽略多个检查,可以用逗号隔开:# noqa: E501,F401
pylint
根目录创建文件:pylintrc
1 2 |
|
C0111: 要求模块和类写文档
使用 mypy 进行静态类型检查
https://github.com/python/mypy
安装:pip install mypy
配置:
setup.cfg
写入如下内容:
1 2 |
|
使用:在项目根目录下执行mypy .
https://mypy.readthedocs.io/en/stable/config_file.html
mypy 通过添加# type: ignore
注释来忽略对某一行的检查:
1 |
|
pytest
https://github.com/pytest-dev/pytest/
https://docs.pytest.org/en/latest/
uml
1 2 3 4 |
|