Python 函数的 -> 及参数的强类型注解详解

Python 函数的 -> 及参数的强类型注解详解

什么是类型注解?

📌 Python 从 3.5 开始支持类型注解(Type Hinting),用于指定函数参数和返回值的类型,使代码更可读、可维护,并可使用 mypy 等工具进行静态类型检查。

💡 语法:

1
2
def 函数名(参数1: 类型, 参数2: 类型) -> 返回类型:
代码块

🔹 示例

1
2
def add(x: int, y: int) -> int:
return x + y

✅ 这里 x: int y: int 指定参数类型,-> int 指定返回值类型。

为什么要使用类型注解?

特点 无类型注解 有类型注解
代码可读性
静态错误检测 ❌ 运行时报错 ✅ 提前检查
IDE 支持 较差,提示不精准 ✅ 自动补全更准确
适用于大型项目 ❌ 维护困难 ✅ 代码更稳定

基础类型注解

📌 Python 中常见的类型:

数据类型 注解方式 示例
整数 int x: int = 10
浮点数 float y: float = 3.14
字符串 str name: str = "Tom"
布尔值 bool flag: bool = True
列表 List[类型] scores: List[int] = [90, 80, 70]
元组 Tuple[类型1, 类型2] data: Tuple[int, str] = (1, "hello")
字典 Dict[键类型, 值类型] info: Dict[str, int] = {"age": 25}
集合 Set[类型] nums: Set[int] = {1, 2, 3}

进阶:可选参数 (Optional)

📌 有些参数可能是 None,可以使用 Optional(等价于 Union[类型, None])。

1
2
3
4
5
6
7
8
from typing import Optional

def get_username(user_id: int, nickname: Optional[str] = None) -> str:
return nickname if nickname else f"User-{user_id}"

print(get_username(1)) # ✅ 输出: User-1
print(get_username(2, "Tom")) # ✅ 输出: Tom

进阶:多个返回类型(Union)

📌 如果函数可能返回多种类型,如 intstr,可以使用 Union

1
2
3
4
5
6
7
from typing import Union

def get_discount(price: float) -> Union[float, str]:
return price * 0.9 if price > 100 else "无折扣"

print(get_discount(120)) # ✅ 输出: 108.0
print(get_discount(80)) # ✅ 输出: 无折扣

高级:泛型 (Generics)

📌 当参数或返回值的类型不确定时,可以使用泛型(TypeVar)

1
2
3
4
5
6
7
8
9
10
from typing import TypeVar, List

T = TypeVar("T") # 定义泛型变量

def first_element(elements: List[T]) -> T:
return elements[0]

print(first_element([1, 2, 3])) # ✅ 1
print(first_element(["a", "b", "c"])) # ✅ 'a'

Callable(函数类型)

📌 有时,我们需要传递函数作为参数,可以使用 Callable 指定函数的参数和返回类型:

1
2
3
4
5
6
7
8
9
from typing import Callable

def execute_twice(func: Callable[[int], int], value: int) -> int:
return func(func(value))

def square(x: int) -> int:
return x * x

print(execute_twice(square, 2)) # ✅ 16

Any(任意类型)

📌 如果参数或返回值可以是任意类型,使用 Any

1
2
3
4
5
6
7
8
from typing import Any

def print_value(value: Any) -> None:
print(value)

print_value(123) # ✅ 输出: 123
print_value("hello") # ✅ 输出: hello
print_value([1, 2, 3]) # ✅ 输出: [1, 2, 3]

企业实战:数据库查询

📌 在企业开发中,我们常用类型注解来约束数据库返回的数据结构。

1
2
3
4
5
6
7
from typing import Dict, Union

def get_user_info(user_id: int) -> Dict[str, Union[str, int]]:
return {"id": user_id, "name": "Alice", "age": 25}

print(get_user_info(1)) # ✅ {'id': 1, 'name': 'Alice', 'age': 25}

结合 mypy 进行静态类型检查

📌 Python 本身不会强制类型检查,但可以使用 mypy 进行静态检查:

1
2
pip install mypy
mypy my_script.py

⚠️ 如果 my_script.py 里有错误:

1
2
3
4
def add(x: int, y: int) -> int:
return x + y

print(add("hello", 5)) # ❌ TypeError

🔴 mypy 会报错:

1
error: Argument 1 to "add" has incompatible type "str"; expected "int"

使用 @overload 进行重载

📌 在 Python 中,函数可以有不同的参数和返回值,使用 @overload 提供更精准的类型提示:

1
2
3
4
5
6
7
8
9
10
11
12
13
from typing import overload

@overload
def process_data(data: str) -> int: ...
@overload
def process_data(data: int) -> str: ...

def process_data(data):
return len(data) if isinstance(data, str) else str(data)

print(process_data("hello")) # ✅ 5
print(process_data(123)) # ✅ '123'

总结

概念 作用 示例
参数类型注解 指定函数参数类型 def func(a: int):
返回值注解 指定返回值类型 -> int
Optional 允许None Optional[str]
Union 多种可能类型 Union[int, str]
List/Dict 复杂数据类型 List[int]/Dict[str, int]
泛型TypeVar 适配多个类型 T = TypeVar("T")
Callable 传递函数 Callable[[int], int]
Any 任意类型 Any
mypy 静态类型检查 mypy script.py

Python 函数的 -> 及参数的强类型注解详解
https://dreamshao.github.io/2025/03/28/Python函数参数的强类型注解详解/
作者
Yun Shao
发布于
2025年3月28日
许可协议