typing 模块是 python 提供的一个标准库,主要用于为函数、变量和类定义类型提示(type hints),从而提高代码的可读性和类型安全性。虽然 python 是动态类型语言,但通过 typing 模块,开发者可以明确指定变量和函数的参数、返回值的类型,帮助 ide 或静态代码分析工具提供更好的代码提示和错误检查。虽然 python 本身不会强制执行这些类型检查,但借助 mypy 等工具,可以进行静态类型分析,帮助发现潜在问题。
源码位置:d:\python310\lib\typing.py

一.常见类型提示
1.list 和 dict
用于表示列表和字典类型。
(1)list[type] 表示一个包含特定类型元素的列表。
(2)dict[key_type, value_type] 表示键和值有特定类型的字典。
2.tuple
表示一个包含特定类型的元组。tuple[type1, type2] 表示一个包含两个特定类型的元组。
3.optional
表示变量可以是某种类型,也可以是 none。optional[type] 等价于 union[type, none],表示某个值可以是 type 或 none。
4.union
表示一个变量可以是多个类型之一。union[type1, type2, ...] 表示变量可以是 type1、type2 等中的任意一种。
5.any
表示可以是任意类型。any 用于声明一个变量可以是任意类型,不做类型检查。
6.callable
表示可调用的对象,如函数。callable[[arg_type1, arg_type2], return_type] 用于表示一个函数,参数类型为 arg_type1、arg_type2,返回值类型为 return_type。
7.typevar
用于定义泛型。typevar 用于创建通用函数或类。
8.literal
限制变量值为某些特定的值。
9.set
表示一个包含特定类型元素的集合。比如 set[str] 表示一个字符串集合。
10.frozenset
表示一个不可变的集合。比如 frozenset[int] 表示一个不可变的整数集合。
11.generic
用于创建泛型类和泛型接口。比如 class mylist(generic[t]) 表示一个泛型列表类,可以存储类型 t 的元素。
12.type
表示一个类型对象。比如 type[str] 表示 str 类型。
二.常见用法
1.list|dict|tuple示例
from typing import list, dict, tuple
# 一个返回包含字符串的列表的函数
def get_names() -> list[str]:
return ["alice", "bob", "charlie"]
# 一个带有字典类型提示的函数
def get_person_data() -> dict[str, int]:
return {"alice": 30, "bob": 25}
# 一个带有元组类型提示的函数
def get_coordinates() -> tuple[int, int]:
return (10, 20)get_names():返回一个list[str],即一个字符串列表。get_person_data():返回一个dict[str, int],表示字典的键是字符串,值是整数。get_coordinates():返回一个tuple[int, int],即一个包含两个整数的元组。
2.optional 示例
from typing import optional
def find_user(user_id: int) -> optional[str]:
if user_id == 1:
return "alice"
return nonefind_user():返回类型是 optional[str],表示可能返回字符串,或者返回 none。
3.union 示例
from typing import union
def process_input(data: union[int, str]) -> str:
if isinstance(data, int):
return f"received an integer: {data}"
return f"received a string: {data}"process_input():参数类型是 union[int, str],表示该函数接收整数或字符串两种类型。
4.callable 示例
from typing import callable
# 定义一个函数接收另一个函数作为参数
def execute_task(task: callable[[int, int], int], a: int, b: int) -> int:
return task(a, b)
# 示例调用
def add(x: int, y: int) -> int:
return x + y
result = execute_task(add, 3, 4) # 返回 7execute_task():接收一个可调用对象(函数),该对象接收两个整数并返回一个整数。
5.typevar 泛型示例
from typing import typevar, list
t = typevar('t')
def get_first_element(lst: list[t]) -> t:
return lst[0]
# 使用时可以是不同的类型
print(get_first_element([1, 2, 3])) # 返回 1
print(get_first_element(['a', 'b', 'c'])) # 返回 'a'typevar:允许定义一个泛型函数 get_first_element,它可以适用于任何类型的列表。
三.高级用法
1.literal 示例
from typing import literal
def set_mode(mode: literal['read', 'write']) -> none:
if mode == 'read':
print("setting mode to read")
elif mode == 'write':
print("setting mode to write")
set_mode('read') # 合法
set_mode('write') # 合法
set_mode('delete') # 非法,会被静态分析工具标记为错误literal:限制传入的值必须是特定的字面值,在此例中只能是 'read' 或 'write'。
2.typeddict示例
from typing import typeddict
class user(typeddict):
name: str
age: int
def get_user() -> user:
return {"name": "alice", "age": 30}typeddict:用于定义字典的具体结构,使字典的键和值类型更加明确。
3.protocol示例
用于定义接口协议,可以检查对象是否实现了特定的方法和属性。
from typing import protocol
class drawable(protocol):
def draw(self) -> none:
...4.final 示例
表示一个变量、方法或属性不能被重写或修改。
from typing import final max_size: final = 100
5.classvar 示例
表示一个类变量,它不应被视为实例变量的一部分。
from typing import classvar
class myclass:
class_var: classvar[int] = 426.noreturn
表示函数不会返回任何值(通常用于函数抛出异常的情况)。
from typing import noreturn
def terminate() -> noreturn:
raise systemexit参考文献
[1] typing 对类型提示的支持:https://docs.python.org/zh-cn/3/library/typing.html
[2] https://github.com/python/mypy
[3] https://www.mypy-lang.org/
到此这篇关于python 中的 typing 模块常见用法的文章就介绍到这了,更多相关python typing 模块用法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论