用 python 做 Leetcode 第一题的时候,将官方提供的函数声明拷贝到本地 IDE ,编写完代码之后,在终端运行,出现如下错误:
def twoSum(self, nums: List[int], target: int) -> List[int]: NameError: name ‘List’ is not defined
查看官方文档:https://docs.python.org/3/library/typing.html
需要在前面增加如下语句:
from typing import List
同时也了解了下变量类型注解和函数返回注解,如前面错误提示中,函数 towSum 中的入参通过在变量后面跟 :类型 来表明参数类型,通过 -> 类型 来表示函数的返回类型
不过如文档中提到
The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.
这些注解对实际代码运行并不是强制的,运行时和没加注解前没有任何区别,比如下面的示例代码
#2test.py
def twoSum(nums: int, target: int) -> int:
return nums + target
def main():
print(twoSum(3, 9))
print(twoSum("yzsijin", ".cn"))
if __name__ == "__main__":
main()
执行后都可以正常输出结果:
➜ python python3.6 2test.py
12
yzsijin.cn
那代码注解的好处是啥呢,可能一方面是便于代码阅读,另一方面它也提到可以通过第三方工具进行检测,比如 type checkers, IDEs, linters 等。
通过搜索 type checkers 了解到可以通过 mypy 工具进行检测,我也安装操作了下
pip install mypy
安装完之后提示
WARNING: The scripts dmypy, mypy, stubgen and stubtest are installed in ‘/Library/Frameworks/Python.framework/Versions/3.6/bin’ which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use –no-warn-script-location.
需将 mypy 执行路径添加到 PATH 路径下,在 ~/.bash_profile 文件里修改
export PATH=”$PATH:/Library/Frameworks/Python.framework/Versions/3.6/bin/”
保存文件后,执行 source ~/.bash_profile
命令使其生效
然后在终端执行 mypy 2test.py
,尴尬的发现没有报任何错误
$mypy 2test.py
Success: no issues found in 1 source file
不过我修改成下面这样
def twoSum(nums: int, target: str) -> int:
return nums + target
再执行 mypy 2test.py
命令,则提示如下错误:
2test.py:3: error: Unsupported operand types for + (“int” and “str”) Found 1 error in 1 file (checked 1 source file)
还是可以做到类型匹配检测的。