mypy)提前发现潜在的错误。为变量指定类型,格式为 变量名: 类型 = 值:
name: str = "拾光" # 字符串
age: int = 18 # 整数
height: float = 1.75 # 浮点数
is_student: bool = False # 布尔值def 函数名(参数: 类型, ...)def 函数名(...) -> 返回类型def greet(name: str) -> str:
"""向指定名称的人打招呼"""
return f"Hello, {name}!"
def add(a: int, b: int) -> int:
"""返回两个整数的和"""
return a + b需从 typing 模块导入泛型类型(Python 3.9+ 可直接用内置容器加中括号):
# Python 3.9+ 的写法
from typing import List, Tuple, Dict, Set # 兼容旧版本,3.9+ 可省略
# 列表(元素均为 int)
numbers: list[int] = [1, 2, 3]
# 元组
person: tuple[str, int] = ("拾光", 18) # (姓名, 年龄)
# 字典
scores: dict[str, int] = {"math": 90, "english": 85}
# 集合
hobbies: set[str] = {"reading", "coding"}Optional)表示变量 / 参数可以是指定类型或 None
from typing import Optional
def find_user(user_id: int) -> Optional[str]:
"""查找用户,找到返回用户名,否则返回 None"""
if user_id == 1:
return "拾光"
return None # 允许返回 None等价于 Union[type, None]
Union)表示变量 / 参数可以是多种类型中的一种
from typing import Union
def print_id(user_id: Union[int, str]) -> None:
"""接受整数或字符串类型的用户 ID 并打印"""
print(f"User ID: {user_id}")
print_id(123) # 合法(int)
print_id("u456") # 合法(str)Callable)表示参数或返回值是函数
from typing import Callable
def calculate(a: int, b: int, func: Callable[[int, int], int]) -> int:
"""使用传入的函数计算 a 和 b 的结果"""
return func(a, b)
def multiply(x: int, y: int) -> int:
return x * y
result = calculate(3, 4, multiply) # 传入函数作为参数
print(result) # 输出:12可为复杂类型定义别名
from typing import List, Tuple
# 定义类型别名:用户信息(姓名,年龄,爱好列表)
UserInfo = Tuple[str, int, List[str]]
def get_user() -> UserInfo:
return ("Charlie", 30, ["hiking", "photography"])mypy)mypy 是常用的静态检查工具,可在运行前检测类型不匹配的问题:
# pip install mypy
def add(a: int, b: int) -> int:
return a + b
result = add("1", 2) # 错误:第一个参数应为 int,实际传入 str运行检查:
mypy demo.py输出错误提示:
error: Argument 1 to "add" has incompatible type "str"; expected "int"类型提示是 Python 代码工程化的重要工具,合理使用能显著提升代码质量和可维护性
#Python #python类型提示