说起来容易做起来难。我们都知道代码的可读性非常重要,但我们总是想写什么就写什么,不管类型提示、导入顺序和PEP8规范如何。今天我将分享一个小技巧,通过一个简单的步骤让你的Python代码更干净。这是预提交:您可以在提交前自动检查您的代码是否符合您想要的规范。使用前先安装pip:pipinstallpre-commit然后在项目根目录下创建两个文件:.pre-commit-config.yaml和pyproject.toml。.pre-commit-config.yaml文件内容如下:exclude:_pb2\.py$repos:-repo:https://github.com/psf/blackrev:22.3.0hooks:-id:blackargs:[--skip-string-normalization]-repo:https://github.com/pre-commit/pre-commit-hooksrev:v4.0.1hooks:-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-hooksrev:v1.9.0hooks:-id:python-check-mock-methods-id:python-use-type-annotations-repo:https://github.com/pre-commit/mirrors-mypyrev:"v0.910"钩子:-id:mypyargs:[--ignore-missing-imports,--warn-no-return,--warn-redundant-casts,--disallow-incomplete-defs,]additional_dependencies:[types-all]-repo:https://github.com/PyCQA/isortrev:5.9.3hooks:-id:isortargs:[--profile,black,--filter-files]Black,mypy,check-docstring在这里配置-首先是isort等工具,id是对应的工具,可以说这个配置文件基本够用了。在.pre-commit-config.yaml文件中,我们可以指定将使用哪些挂钩。在pyproject.toml中,我们可以为这些单独的钩子指定参数。pyproject.toml文件内容如下:[tool.black]line-length=88target-version=["py38"][tool.isort]profile="black"multi_line_output=3black和isort的相关配置在这里配置。然后在项目根目录下执行pre-commitinstall命令安装pre-commit插件。然后每次更新代码,当你提交代码时,这些钩子会被触发,并自动执行以下操作:sortimportPEP8formatcodecheckyouryamlandjsonfilesforcorrectnesstypecheck(ifyouusetypehints)最后你可以把这两个文件复制到你自己的项目根目录下,然后执行pre-commitinstall,这样每次提交代码都是cleancode,是不是很方便?
