5

一个简单的步骤让你的 Python 代码更干净

 2 years ago
source link: https://www.51cto.com/article/721612.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

一个简单的步骤让你的 Python 代码更干净

作者:somenzz 2022-10-31 07:09:15
你可以将这两个文件拷贝到自己的项目根目录中,然后执行一次 pre-commit install,这样每次提交代码的时候,都是干净的代码,是不是很方便?

说起来容易做起来难,我们都知道代码可读性非常重要,但是写的时候总是随心所欲,不考虑类型提示、import 排序、PEP8 规范。今天分享一个小技巧,通过一个简单的步骤就可以让你的 Python 代码更干净。

这就是 pre-commit:

图片

可以让你的代码提交之前自动检查是否符合你想要的规范。

使用之前,先 pip 安装一下:

pip install pre-commit

然后在项目的根目录下创建两个文件:.pre-commit-config.yaml 和 pyproject.toml。

.pre-commit-config.yaml 文件内容如下:

exclude: _pb2\.py$
repos:
  - repo: https://github.com/psf/black
    rev: 22.3.0
    hooks:
      - id: black
        args: [--skip-string-normalization]
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.0.1
    hooks:
      - id: check-docstring-first
      - id: check-json
      - id: check-merge-conflict
      - id: check-yaml
      - id: debug-statements
      - id: end-of-file-fixer
      - id: trailing-whitespace
      - id: requirements-txt-fixer
  - repo: https://github.com/pre-commit/pygrep-hooks
    rev: v1.9.0
    hooks:
      - id: python-check-mock-methods
      - id: python-use-type-annotations
  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: "v0.910"
    hooks:
      - id: mypy
        args:
          [
            --ignore-missing-imports,
            --warn-no-return,
            --warn-redundant-casts,
            --disallow-incomplete-defs,
          ]
        additional_dependencies: [types-all]
  - repo: https://github.com/PyCQA/isort
    rev: 5.9.3
    hooks:
      - id: isort
        args: [--profile, black, --filter-files]

这里面配置了 black、mypy、check-docstring-first、isort 等工具,id 就是对应的工具,可以说这个配置文件基本上就够用了。

在 .pre-commit-config.yaml 文件中,我们可以指定将使用哪些挂钩,在 pyproject.toml 中,我们可以为这些单独的钩子指定参数。

pyproject.toml 文件内容如下:

[tool.black]
line-length = 88
target-version = ["py38"]

[tool.isort]
profile = "black"
multi_line_output = 3

这里配置了 black 和 isort 的相关配置。

然后执行在项目的根目录执行 pre-commit install 命令,就可以安装 pre-commit 插件。

然后每次更新代码,提交代码时,这些钩子都会触发,会自动执行如下操作:

排序 import

PEP8 的格式代码

检查您的 yaml 和 json 文件的正确性

类型检查(如果你使用了类型提示)

图片
最后

你可以将这两个文件拷贝到自己的项目根目录中,然后执行一次 pre-commit install,这样每次提交代码的时候,都是干净的代码,是不是很方便?

责任编辑:武晓燕 来源: Python七号

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK