如何让 你的Python 代码更专业?

Python绿色通道

共 1825字,需浏览 4分钟

 · 2022-05-17


↑ 关注 + 星标 ,每天学Python新技能

后台回复【大礼包】送你Python自学大礼包

自己写代码只给自己看,其实怎么写都行。一旦有团队合作,或者要分享自己的代码,就要好好写了,专业的代码可以为自己积累技术影响力。

今天就来分享如何使用 black、mypy、pylint 来让自己的代码更加专业。

1、用 black 来格式化

black 可以按照 PEP8 的规范进行格式化,同时注重代码的阅读体验。

如果问我对哪一种格式化工具最满意,毫无疑问是 black。写完代码,觉得代码看着不爽,就在命令行 black xxx.py 就可以了,也可以 black 一个目录,对该目录的所有文件进行格式化。

安装:

pip install black

除了简单的 black 文件名或目录,black 还有很多选项非常实用。

比如指定 Python 版本进行格式化(不同版本略有不同):

black -t py310 some_python_file.py
#black --target-version=py310

设置代码行的长度:

black -l 79 some_python_file.py

仅仅检查而不修改:

black --check some_python_file.py

2、用 mypy 检查类型提示

mypy 是 Python 的静态类型检查器,可用于检查添加到 Python 代码中的类型注释。mypy 在检查不同函数甚至模块之间的类型依赖关系方面非常强大。

之前写过一篇文章 mypy 这个工具,让Python的类型提示变得非常实用

里面有安装、使用、配置的方法,这里就不再赘述。

3、使用 pylint 分析代码

Pylint 是一个自动 Python 代码分析工具,可以检测编程错误并根据 PEP8 给出重构建议。

安装:

pip install pylint

使用:

$ pylint some_python_scripts.py
************* Module some_python_scripts
some_python_scripts.py:1:0: C0114: Missing module docstring (missing-module-docstring)
some_python_scripts.py:5:16: C0103: Argument name "n" doesn't conform to snake_case naming style (invalid-name)
some_python_scripts.py:5:0: C0116: Missing function or method docstring (missing-function-docstring)
some_python_scripts.py:21:0: C0116: Missing function or method docstring (missing-function-docstring)
some_python_scripts.py:21:18: W0621: Redefining name '
numbers' from outer scope (line 46) (redefined-outer-name)
some_python_scripts.py:27:14: C0209: Formatting a regular string which could be a f-string (consider-using-f-string)
------------------------------------------------------------------
Your code has been rated at 7.50/10 (previous run: 7.50/10, +0.00)

根据以上输出,重构代码。

为 VSCode 配置这三个工具

1、为 VSCode 配置 black:

打开首选项 -> 设置,搜索 Python,按下图进行配置

2、为 VSCode 配置 mypy:

3、为 VSCode 配置 pylint:



  1. 30个案例,305页!超有趣的Python学习资料!

  2. 浏览器可以运行 Python 代码了,Python 也许会变成前后端通吃的语言

  3. 一个迅速崛起的国产开源OCR项目



浏览 22
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报