在程序开发时候一套好的开发环境和工具栈, 可以帮我们极大的提高开发的效率, 避免把大量时间浪费在周边琐事上. 本文以 Python 为例, 教大家如何快速打造优秀的 Python 项目开发环境: 内容涵盖了模块依赖管理, 代码风格管理, 调试测试管理和 Git 版本管理, 使用 Git hook 做项目规范检查等.
pipx
Pipx 是一款跨平台的 Python 环境隔离管理工具, 可以在支持在 Linux,Mac OS 和 Windows 上运行. Pipx 默认在是个人用户下建立虚拟 Python 环境, 并以此建立实现完全隔离的 Python 运行环境. 安装 pipx 需要 Pthon 3.6 及以上版本:
- python3 -m pip install --user pipx
- python3 -m pipx ensurepath
升级 Pipx 使用:
python3 -m pip install -U pipx
包依赖管理 pipenv
Pipenv 会自动为你的项目创建和管理虚拟环境, 以 pipfile 文件方式方式管理项目的依赖包, 支持包的安装和卸载. 和 requirements.txt 不同, pipfile 是 TOML 格式, 支持开发环境与正式环境, 还可以使用 Pipfile.lock 锁定环境版本. pipxenv 的安装可以使用 pipx:
pipx install pipenv
有些发行版也是可以直接通过其包管理器安装的:
比如 MacOS 可以下可以使用:
brew install pipenv
一个 pipfile 的示例如下:
Pipfile.lock 的示例部分如下:
代码风格
代码格式化 black
代码格式的统一不光可以给我们一个惬意的代码格式, 而且可以避免由于开发人员之间的代码风格差异导致的沟通和协作问题.
Black 就是用来格式化 Python 代码的程序. 它可以自动帮我们对代码格式进行调整和统一, 提高代码效率和可读性. 而且通过 Black 减小代码风格的差异, 可以极大提高团队进行代码审查的效率.
一个 Black 格式化示例如下:
原始代码:
- def very_important_function(template: str, *variables, file: os.PathLike, engine: str, header: bool = True, debug: bool = False):
- """Applies `variables` to the `template` and writes to `file`."""
- with open(file, 'w') as f:
- ...
格式化后的代码:
- def very_important_function(
- template: str,
- *variables,
- file: os.PathLike,
- engine: str,
- header: bool = True,
- debug: bool = False,
- ):
- """Applies `variables` to the `template` and writes to `file`."""
- with open(file, "w") as f:
- ...
isort 美化 import 部分代码
Python 开发中经常需要 import 第三方的模块, 往往这部分代码混乱不堪, 使用 isort 可以则可以美化这部分的代码. isort 可以按字母表顺序对 import 进行排序, 自动分成多个部分.
我们可以使用 pipenv 安装 black 和 isort:
pipenv install black isort -dev
isort 的效果示例, 可以看下面的动图:
Black 和 isort 同时使用时, 两者默认配置不兼容, 我们需要覆盖 isort 配置, 优先以 Black 的格式化为准. 可以通过 setup.cfg 文件并添如下配置来完成该任务.
- [isort]
- multi_line_output=3
- include_trailing_comma=True
- force_grid_wrap=0
- use_parentheses=True
- line_length=88
flake8 代码风格检测
Flake8 可以用来确保代码遵循 PEP8 中定义的标准 Python 编程约定, 是 Python 官方辅助代码风格检测工具, lake8 检查规则灵活, 支持集成额外插件(比如 VIM,Sublime,PyCharm,vsc 等都有其相关插件), 扩展性强.
其安装也可以使用 pipenv:
pipenv install flake8 -dev
flake8 的使用示例如下:
flake8 example.py 的检查结果:
flake8 默认会忽略一些约定(E,F), 如果我们检查所有约定:
flake8 --select E,F example.py, 结果:
和 isort 一样, 为了配合兼容 Black, 需要在 setup.cfg 中额外配置:
- [flake8]
- ignore = E203, E266, E501, W503
- max-line-length = 88
- max-complexity = 18
- select = B,C,E,F,W,T4
mypy 静态类型
Mypy 是 Python 的可选静态类型检查器, 可以用结合动态 (或 "鸭子") 类型和静态类型优点其他代码的性能. 通过 Mypy 将 Python 的动态类型便捷性和表现力的优势与静态类型强系统和编译时类型检查相结合, 并且生成原生代码, 支持通过 Python VM 运行, 可以没有运行时开销的高性能运行. 在 Python 中使用静态类型好处有:
可以使程序更易于理解和维护;
可以帮助编译时调试和发现错误, 减少测试和调试.
可以在代码部署到生产环境之前就可以找到难以捕捉的错误.
可以使用 pipenv 直接安装 Mypy:
pipenv install mypy -dev
mypy 动态类型和静态类型一个示例如下:
项目配置
默认情况下, Mypy 会递归检查所有类型注释的导入, 这会导致库不包含这些注释时出错. 需要修改 mypy 配置仅检查当前代码运行, 并忽略没有类型注释的 import 模块. 这也可以在 setup.cfg 中设置:
[mypy]
files = 项目, test
ignore_missing_imports=true
代码测试
程序开发中, 除了写代码外, 另外一个重要的部分是单元测试. Python 测试方面我们要介绍的工具有 pytest.
可以使用 pipenv 添加测试工具包及扩展:
pipenv install pytest pytest-cov --dev
Pytest 框架可以让编写小测试变得容易, 而且支持以扩展的方式提供更加复杂的功能. 下面是 pytest 网站的一个简单示例:
- # content of test_sample.py
- def inc(x):
- return x + 1
- def test_answer():
- assert inc(3) == 5
通过以下命令测试
pipenv run pytest
结果如下:
pytest-cov 是 pytest 的单元测试行覆盖率的插件. pytets-cov 的测试结果示例如下:
pytest 还有很多的扩展插件:
pytest-cov: 单元测试覆盖率报告
pytest-django: 对 Django 框架的单元测框架
pytest-asyncio: 对 asyncio 的支持
pytest-twisted: 对 twisted 框架的单元测框架
pytest-instafail: 发送错误时报告错误信息
pytest-BDD 测试驱动开发工具
pytest-konira 测试驱动开发工具
pytest-timeout: 支持超时功能
pytest-pep8: 支持 PEP8 检查
pytest-flakes: 结合 pyflakes 进行代码检查
更多插件可以查看 GitHub pytest-dev 组织下的项目.
项目配置
项目中, 所有的测试都应该放在 test 目录中, 我需要给 setup.cfg 添加配置:
- [tool:pytest]
- testpaths=test
单元覆盖率的项目配置需要创建一个新文件. coveragerc 返回应用程序代码的覆盖率统计信息, 配置示例如下:
[run]
source = 项目
- [report]
- exclude_lines =
- pragma: no cover
- def __repr__
- if self\.debug
- raise AssertionError
- raise NotImplementedError
- if 0:
- if __name__ == .__main__.:
然后再工程中运行一下命令, 测试项目的覆盖率
pipenv run pytest --cov --cov-fail-under =100
如果程序代码的测试覆盖率低于 100%, 就会报错.
Git pre-commit hook 规范检查
Git hook 可以让我们在提交或推送时执行检查脚本, 脚本可以配置对项目镜像测试或者规范性检查. 运行脚本. 我们可以配置 pre-commit hook 允许轻松配置这些钩子, 下面. pre-commit-config.YAML 配置示例可以帮我们自动做代码规范化, 包括 isort 检查, black 检查, flake8 检查, mypy 静态类型检查, pytest 测试, pytest-cov 测试覆盖率检查:
- repos:
- - repo: local
- hooks:
- - id: isort
- name: isort
- stages: [commit]
- language: system
- entry: pipenv run isort
- types: [python]
- - id: black
- name: black
- stages: [commit]
- language: system
- entry: pipenv run black
- types: [python]
- - id: flake8
- name: flake8
- stages: [commit]
- language: system
- entry: pipenv run flake8
- types: [python]
exclude: setup.py
- - id: mypy
- name: mypy
- stages: [commit]
- language: system
- entry: pipenv run mypy
- types: [python]
- pass_filenames: false
- - id: pytest
- name: pytest
- stages: [commit]
- language: system
- entry: pipenv run pytest
- types: [python]
- - id: pytest-cov
- name: pytest
- stages: [push]
- language: system
- entry: pipenv run pytest --cov --cov-fail-under=100
- types: [python]
如果你需要跳过这些钩子, 你可以运行 Git commit --no-verify 或 Git push --no-verify
cookiecutter 自动创建项目
上面我们提到 Python 项目应该具备的工具集和配置, 可以将其作为模版. cookiecutter 的模版定义范例如下:
- cookiecutter.JSON
- {
- "full_name": "Chongchong",
- "email": "chongchong@ijz.me",
- "project_name": "Python-Practice",
- "repo_name": ""Python-Practice",
- "project_short_description": "The Simple Python Development Practice Example.",
- "release_date": "2019-09-02",
- "year": "2019",
- "version": "0.0.1"
- }
然后使用 cookiecutter 自动生成整改工程:
- pipx run cookiecutter Python-Practice
- cd Python-Practice
- Git init
安装依赖项
pipenv install --dev
运行 pre-commit 和 pre-push hook:
- pipenv run pre-commit install -t pre-commit
- pipenv run pre-commit install -t pre-push
总结
本文我们介绍了在 Python 项目开发时候必须要具备的一些开发测试检查工具. 通过这些可以自动生成 Python 项目, 代码风格检查, 代码测试等操作, 可以帮助我们打造一个高效完美的 Python 开发环境.
来源: http://developer.51cto.com/art/201909/602371.htm