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

如何实现通用高阶函数,可重复执行传入的目标函数直到获得正确结果

通用重试函数实现方案

你完全可以实现支持传入任意目标函数的通用版本,只需要把要执行的函数、对应参数都作为入参传入即可,具体实现如下:

def execute_until_good_result(func, *args, **kwargs):
    while True:
        try:
            return func(*args, **kwargs)
        except Exception as e:
            print(e)

调用示例

你原来的场景可以直接替换为以下写法:

result = execute_until_good_result(get_number_from_range, 'Enter value from range <100, 999>.', 100, 999)

可选优化:增加最大重试次数限制

如果需要避免无限循环,可以新增可选的最大重试次数参数:

def execute_until_good_result(func, max_retries=None, *args, **kwargs):
    retry_count = 0
    while max_retries is None or retry_count < max_retries:
        try:
            return func(*args, **kwargs)
        except Exception as e:
            print(e)
            retry_count += 1
    raise RuntimeError(f"已达到最大重试次数:{max_retries}")

带重试次数限制的调用示例:

# 最多重试3次
result = execute_until_good_result(get_number_from_range, 3, 'Enter value from range <100, 999>.', 100, 999)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:12:03