使用mypy对python程序进行静态检查 python3.6以后,允许为参数和函数返回类型添加类型标注(type hinting),这就为程序进行静态类型检查提供了可能,mypy就是一个利用类型注解对python代码进行静态类型检查的工具, 使用pip安装
1. 有问题的代码 class Stu : def __init__ (self, name, age ): self .name = name self .age = age def __str__ (self ): return '{name} {age}' .format (name=self .name, age=self .age) stu1 = Stu('小明' , 16.5 ) stu2 = Stu('小刚' , '17' ) print (stu1, stu2)
上面的代码在执行时不会报任何错误,但严格来讲是存在问题的,在创建Stu实例时,age参数应该传入int类型数据。但由于python是动态类型语言,因此,传入float或者字符串都不会引发错误,除非在后续的属性使用中对类型有明确要求。这样的代码是不安全的,在程序运行前,可以通过静态类型检查来发现问题,这需要类型标注的帮助
2. 添加类型标注并使用mypy检查 class Stu : def __init__ (self, name: str , age: int ): self .name = name self .age = age def __str__ (self ): return '{name} {age}' .format (name=self .name, age=self .age) stu1 = Stu('小明' , 16.5 ) stu2 = Stu('小刚' , '17' ) print (stu1, stu2)
仅仅是添加了类型标注,我所使用的pycharm就已经提示我创建Stu实例时的age参数有问题,这种提示是委婉的,你可以不用理会。接下来使用mypy进行静态类型检查
mypy demo.py demo.py:10: error: Argument 2 to "Stu" has incompatible type "float"; expected "int" demo.py:11: error: Argument 2 to "Stu" has incompatible type "str"; expected "int" Found 2 errors in 1 file (checked 1 source file)
mypy准确的找出了两处类型与参数预期不符的情况