# mypy-静态类型检查

# 概述

mypy是一个基于Python的静态类型检查工具,可以在代码编写过程中发现类型错误和不一致,从而提高代码的可读性、可维护性和可靠性。mypy使用Python的类型注解来描述函数和变量的类型信息,并使用静态分析技术检查类型错误和不一致。

使用mypy模块可以在Python代码编写过程中发现类型错误和不一致,以及其他潜在问题,例如:

  • 函数或方法的参数或返回值类型错误;
  • 变量或属性类型错误或不一致;
  • 对未定义的变量或属性进行访问;
  • 对不同类型的对象进行操作;
  • 程序流程不正确或不完整。

# 使用示例

编写以下代码

def greeting(name: str) -> str:
    return 'Hello, ' + name

print(greeting('Alice'))
print(greeting(42))

执行静态检查:

python -m mypy --strict mypy_test.py

"""
mypy_test.py:6: error: Argument 1 to "greeting" has incompatible type "int"; expected "str"  [arg-type]
Found 1 error in 1 file (checked 1 source file)
"""