前言
写python五六年了,但是在最近接触到一些大型的运维侧Django项目后,总感觉python作为一种极致动态的语言,没有编译期静态类型检查,让人感觉很不放心,所以最近几天一门心思的预研了几种python的类型检查工具,首先声明一下Google的Pytype凭借类型推导在即使没有type hint类型标记的情况下也能做类型检查吊打其它的一切,比如Facebook的pyre,Microsoft的Pylance和Pyright,Python之父的mypy。
实战
去pytype github主页按照指南自行安装好pytype,可以安装到全局解释器里面,然后打开VS Code新建一个task,步骤如下:
第一步:
第二步:
然后会在你的项目的当前目录的.vscode文件夹中新建一个tasks.json文件,打开它写入如下内容即可:
1 2 3 4 5 6 7 8 9 10 11 12 |
{ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "label": "Check", "type": "shell", "command": "pytype -j='auto' -k -d='import-error' ${cwd}" } ] } |
pytype命令参数说明:
-j='auto' 参数会跟根据你的电脑的cpu核数进行多核心加速检查
-k 用来忽略错误尽可能多的进行检查
-d='import-error' 用来忽略import错误,因为目前好像有点bug
${cwd} 表明是当前工作目录,这是vs code的宏变量。
上面的重点是"label": "Check"键值对,这个很重要,等下launch.json中要用到,现在打开launch.json新增一个叫"preLaunchTask": "Check"的键值对,你注意到了么,这里的"Check"就是前面的"label"的值。如果launch.json中不新增一个叫"preLaunchTask": "Check"的键值对的话,是不会启动pytype的静态类型推导检查的,那样我们的实战就失败了,你可以自行试一下,我已经试过了。
下面贴一下完整的launch.json的内容,以供参考:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "preLaunchTask": "Check", "request": "launch", "program": "${file}", "console": "integratedTerminal", "justMyCode": true } ] } |
下面是实战效果:
你看到了么,右侧的debug console在启动之前先运行了我们的Check这个task,然后terminal中返回了Success,至此我们的实战大功告成。