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

Python标准/流行库中是否存在适配单元素与Iterable的装饰器?

回答

标准库中没有专门针对该场景的装饰器,但实现一个符合需求的装饰器非常简单,代码量远少于使用单分派的方案:

from collections.abc import Iterable

def handle_iterable(func):
    def wrapper(item_or_iterable):
        # 排除字符串、字节串这类特殊可迭代对象,避免误遍历单个字符/字节
        if isinstance(item_or_iterable, Iterable) and not isinstance(item_or_iterable, (str, bytes)):
            for item in item_or_iterable:
                func(item)
        else:
            func(item_or_iterable)
    return wrapper

使用示例:

@handle_iterable
def process_integer(num):
    print(f"处理数字: {num}")

# 传入单个元素
process_integer(10)
# 输出:处理数字: 10

# 传入可迭代对象
process_integer([1, 2, 3])
# 依次输出:
# 处理数字: 1
# 处理数字: 2
# 处理数字: 3

# 字符串会被当作单个元素处理(不会遍历字符)
process_integer("test")
# 输出:处理数字: test

如果一定要依赖主流第三方库,部分工具库(如toolz)可以结合现有工具实现类似逻辑,但相比自己写这个轻量装饰器,引入依赖反而显得冗余——毕竟该场景的核心逻辑仅需几行代码就能覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:44:51