Python中如何为任意指定数据类型的集合添加类型提示?
问题:如何为支持多种可迭代类型的参数添加类型提示
我有如下函数:
def some_function(paths): for path in paths: other_function(path)
函数设计意图是paths中的每个元素均为字符串,但paths可以是list、tuple、set、numpy array、pandas Series等类型,因此下面这种写法过于局限:
def some_function(paths: list[str]): for path in paths: other_function(path)
请问该如何为参数paths添加正确的类型提示?是否应该使用typing模块中的Collection或Sequence来进行类型提示?
解决方案
用Iterable[str]就够了
你的代码只是对paths做迭代遍历,不需要它具备序列的索引、切片,也不需要集合的额外方法,最适合的类型提示是**Iterable[str]**——它表示所有能迭代出字符串的类型,完美覆盖list、tuple、set、numpy array、pandas Series这些场景。
具体代码写法
Python 3.8及更早版本
from typing import Iterable def some_function(paths: Iterable[str]): for path in paths: other_function(path)
Python 3.9及以后版本(推荐用标准库的抽象基类)
from collections.abc import Iterable def some_function(paths: Iterable[str]): for path in paths: other_function(path)
为啥不用Collection或Sequence?
- Sequence:要求类型必须支持索引、长度获取、切片这些操作,但set、部分numpy array、pandas Series并不满足这个要求,用它反而会把你需要支持的类型排除在外,没必要。
- Collection:这个抽象包含了
__contains__、__len__这些方法,但你的代码根本用不上这些,用它属于过度约束,而且有些你要兼容的类型也不一定严格符合Collection的定义。
特殊场景补充
如果需要让静态类型检查工具明确识别numpy array或pandas Series,可以结合Union扩展标注,但日常场景下单独用Iterable[str]已经足够灵活:
from typing import Iterable, Union import numpy as np import pandas as pd def some_function(paths: Union[Iterable[str], np.ndarray[str], pd.Series[str]]): for path in paths: other_function(path)
内容的提问来源于stack exchange,提问作者johnnybarrels
相关产品推荐
相关产品推荐

