You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为返回filter对象的Python函数编写有意义的类型提示?

问题:为返回filter对象的函数添加精准类型提示

首先看返回列表的原函数:

from typing import List, Tuple

def get_list_of_nums_and_square_nums_with_last_digit_9() -> List[Tuple[int, int]]:
    sqr = lambda n: n * n
    is_last_digit_9 = lambda n: n % 10 == 9
    is_last_digit_of_square_num_9 = lambda t: (lambda n, n_squared: is_last_digit_9(n_squared))(*t)

    nums_and_square_nums = map(lambda n: (n, sqr(n)), range(10))
    return list(filter(is_last_digit_of_square_num_9, nums_and_square_nums))

该函数的返回结果:

>>> get_list_of_nums_and_square_nums_with_last_digit_9()
[(3, 9), (7, 49)]

现在需要一个等价但返回filter对象的函数:

def get_nums_and_square_nums_with_last_digit_9():
    sqr = lambda n: n * n
    is_last_digit_9 = lambda n: n % 10 == 9
    is_last_digit_of_square_num_9 = lambda t: (lambda n, n_squared: is_last_digit_9(n_squared))(*t)

    nums_and_square_nums = map(lambda n: (n, sqr(n)), range(10))
    return filter(is_last_digit_of_square_num_9, nums_and_square_nums)

提问:应使用何种类型提示,才能清晰体现该filter对象迭代后元素的结构?Iterator[Tuple[int, int]]是否正确?有没有更精准的写法?要求能从类型提示中确定元素的Tuple[int, int]结构。


回答

  • Iterator[Tuple[int, int]]是完全正确的写法,它明确告知类型检查工具和其他开发者:该函数返回的是一个迭代器,每次迭代产出的元素是包含两个整数的元组,完全满足你对元素结构明确性的要求。
  • 若要更精准地体现返回对象是filter类型,可以使用filter[Tuple[int, int]](Python 3.9+原生支持,低版本需从typing模块导入Filter)。不过filter本身就是迭代器的子类,这种写法和Iterator[Tuple[int, int]]在类型检查层面的效果几乎一致,核心都是明确元素的Tuple[int, int]结构。
  • 选择建议:如果只需要清晰传达迭代产出的元素结构,Iterator[Tuple[int, int]]足够通用且兼容性更好;如果想强调返回的是filter实例而非其他迭代器,filter[Tuple[int, int]]是更精准的选择。

内容的提问来源于stack exchange,提问作者Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 19:35:35