字数 1252,阅读大约需 7 分钟
Python:Type Hints 功能为代码的静态类型检查
什么是Typing
Typing 是 Python 标准库中的一个模块,专门用来支持 Type Hints(类型提示)功能
基本类型:
int: 整数类型
float: 浮点数类型
bool: 布尔类型
str: 字符串类型
bytes: 字节类型
Any: 任意类型
Union: 多个类型的联合类型,表示可以是其中任意一个类型
Tuple: 固定长度的元组类型
List: 列表类型
Dict: 字典类型,用于键值对的映射
泛型:
Generic: 泛型基类,用于创建泛型类或泛型函数
TypeVar: 类型变量,用于创建表示不确定类型的占位符
Callable: 可调用对象类型,用于表示函数类型
Optional: 可选类型,表示一个值可以为指定类型或None
Iterable: 可迭代对象类型
Mapping: 映射类型,用于表示键值对的映射
Sequence: 序列类型,用于表示有序集合类型
Type:泛型类,用于表示类型本身
学习
typing --- 对类型提示的支持 — Python 3.13.8 文档[1]
Python3 Typing模块详解-腾讯云开发者社区-腾讯云[2]
探索 Python Type Hints 中的冷门但实用的特性-腾讯云开发者社区-腾讯云[3]
代码
import typing
class TypingTest(object):
"""
TypingTest 类用于演示 Python typing 库的常见功能和使用方法。
"""
def __init__(self):
pass
# 1. 基本类型提示
def greet(self, name: str) -> str:
"""
演示基本类型提示:字符串输入和字符串输出。
"""
return f"Hello, {name}"
# 2. 列表类型提示
def sum_numbers(self, numbers: typing.List[int]) -> int:
"""
演示列表类型提示:接受一个整数列表,返回它们的和。
"""
return sum(numbers)
# 3. 字典类型提示
def get_user_info(self, user_id: int) -> typing.Dict[str, typing.Any]:
"""
演示字典类型提示:接受用户ID,返回包含用户信息的字典。
"""
# 模拟从数据库获取数据
users = {
1: {"name": "Alice", "age": 30},
2: {"name": "Bob", "age": 24}
}
return users.get(user_id, {})
# 4. 元组类型提示
def get_coordinates(self) -> typing.Tuple[float, float]:
"""
演示元组类型提示:返回一个包含两个浮点数的元组(坐标)。
"""
return (10.5, 20.3)
# 5. 集合类型提示
def get_unique_items(self, items: typing.Set[str]) -> typing.Set[str]:
"""
演示集合类型提示:接受一个字符串集合,返回相同的集合(去重)。
"""
return items
# 6. 可选类型提示 (Optional)
def get_optional_value(self, value: typing.Optional[str]) -> str:
"""
演示 Optional 类型提示:接受一个可选的字符串,如果为 None 则返回默认值。
"""
return value if value is not None else "Default Value"
# 7. 联合类型提示 (Union)
def process_data(self, data: typing.Union[str, int]) -> str:
"""
演示 Union 类型提示:接受字符串或整数,并返回其字符串表示。
"""
return str(data)
# 8. Any 类型提示
def handle_anything(self, item: typing.Any) -> None:
"""
演示 Any 类型提示:接受任何类型的参数,不进行类型检查。
"""
print(f"Handling item of type {type(item)}: {item}")
# 9. Callable 类型提示
def apply_function(self, func: typing.Callable[[int, int], int], a: int, b: int) -> int:
"""
演示 Callable 类型提示:接受一个函数和两个整数,并应用该函数。
"""
return func(a, b)
# 10. TypeVar 类型变量
T = typing.TypeVar('T')
def first_element(self, items: typing.List[T]) -> T:
"""
演示 TypeVar 类型变量:接受一个列表,返回第一个元素。
"""
return items[0]
# 11. TypedDict 类型字典 (Python 3.8+)
class User(typing.TypedDict):
name: str
age: int
email: typing.Optional[str]
def create_user(self, user_data: User) -> User:
"""
演示 TypedDict 类型字典:接受一个符合 User 结构的字典。
"""
print(f"Creating user: {user_data['name']}")
return user_data
# 12. Literal 类型 (Python 3.8+)
def set_status(self, status: typing.Literal["pending", "completed", "failed"]) -> str:
"""
演示 Literal 类型:接受一个只能是指定字符串字面量之一的参数。
"""
return f"Status set to: {status}"
# 13. Final 类型 (Python 3.8+)
PI: typing.Final[float] = 3.14159
def get_pi(self) -> typing.Final[float]:
"""
演示 Final 类型:表示一个常量,不能被重新赋值。
"""
return self.PI
# 14. Protocol 类型 (Python 3.8+)
class SupportsLen(typing.Protocol):
def __len__(self) -> int:
...
def get_length(self, obj: SupportsLen) -> int:
"""
演示 Protocol 类型:接受一个支持 __len__ 方法的对象。
"""
return len(obj)
# 15. NewType 类型
UserId = typing.NewType('UserId', int)
def get_user_by_id(self, user_id: UserId) -> str:
"""
演示 NewType 类型:创建一个新的、语义上不同的类型,基于现有类型。
"""
return f"Fetching user with ID: {user_id}"
# 示例用法
if __name__ == "__main__":
test_instance = TypingTest()
print("--- 基本类型提示 ---")
print(test_instance.greet("Kilo Code"))
print("\n--- 列表类型提示 ---")
print(test_instance.sum_numbers([1, 2, 3, 4, 5]))
print("\n--- 字典类型提示 ---")
print(test_instance.get_user_info(1))
print(test_instance.get_user_info(3))
print("\n--- 元组类型提示 ---")
print(test_instance.get_coordinates())
print("\n--- 集合类型提示 ---")
print(test_instance.get_unique_items({"apple", "banana", "apple"}))
print("\n--- 可选类型提示 ---")
print(test_instance.get_optional_value("Hello"))
print(test_instance.get_optional_value(None))
print("\n--- 联合类型提示 ---")
print(test_instance.process_data("test_string"))
print(test_instance.process_data(123))
print("\n--- Any 类型提示 ---")
test_instance.handle_anything(100)
test_instance.handle_anything("a string")
test_instance.handle_anything([1, 2, 3])
print("\n--- Callable 类型提示 ---")
def add(x: int, y: int) -> int:
return x + y
print(test_instance.apply_function(add, 5, 3))
print("\n--- TypeVar 类型变量 ---")
print(test_instance.first_element([1, 2, 3]))
print(test_instance.first_element(["a", "b", "c"]))
print("\n--- TypedDict 类型字典 ---")
user_data_1: TypingTest.User = {"name": "Charlie", "age": 25, "email": "[email protected]"}
user_data_2: TypingTest.User = {"name": "David", "age": 35} # email 是可选的
print(test_instance.create_user(user_data_1))
print(test_instance.create_user(user_data_2))
print("\n--- Literal 类型 ---")
print(test_instance.set_status("pending"))
# print(test_instance.set_status("unknown")) # 这会在类型检查时报错
print("\n--- Final 类型 ---")
print(test_instance.get_pi())
# TypingTest.PI = 3.14 # 这会在类型检查时报错
print("\n--- Protocol 类型 ---")
class MyList:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
my_list_instance = MyList([1, 2, 3])
print(test_instance.get_length(my_list_instance))
print(test_instance.get_length("hello")) # 字符串也支持 __len__
print("\n--- NewType 类型 ---")
user_id_val = TypingTest.UserId(123)
print(test_instance.get_user_by_id(user_id_val))
引用链接
[1]
typing --- 对类型提示的支持 — Python 3.13.8 文档: https://docs.python.org/zh-cn/3.13/library/typing.html[2]
Python3 Typing模块详解-腾讯云开发者社区-腾讯云: https://cloud.tencent.com/developer/article/2359631[3]
探索 Python Type Hints 中的冷门但实用的特性-腾讯云开发者社区-腾讯云: https://cloud.tencent.com/developer/article/2545850?policyId=1004
评论区