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

Python回调函数循环执行场景下如何为指定回调添加额外参数

解决方案

以下两种都是符合Pythonic规范的生产常用实现:

方案1:无侵入式参数预绑定(推荐优先使用)

不需要修改现有timed_execution逻辑,用Python标准库functools.partial对需要额外参数的回调做偏应用处理即可,本质是提前固定部分参数,返回一个新的可调用对象,调用时仅需要传入era参数即可。

from functools import partial
import time

# 原有代码无需修改
def dummy_function(period, letter='A'):
    """ Debugging purposes only """
    print(f'This function prints the letter {letter}.')
    from time import sleep
    sleep(3)

def timed_execution(callbacks, era):
    for callback in callbacks:
        start_time = time.time()
        callback(era)
        end_time = time.time()
        print(f'{callback.__name__} took {end_time-start_time:.3f}s')

def another_function(era):
    pass

def yet_another_function(era):
    pass

def calculate_insights(era):
    timed_execution([
        # 仅需对需要额外参数的函数做partial包装
        partial(dummy_function, letter='B'),
        another_function,
        yet_another_function,
    ], era)

calculate_insights(2024)

注意:也可以用lambda表达式实现类似效果lambda era: dummy_function(era, letter='B'),但lambda会丢失原函数的__name__元信息,计时打印时会显示为<lambda>,兼容性不如partial。如果dummy_function是类内的实例方法,直接绑定实例即可partial(self.dummy_function, letter='B'),无需额外调整。

方案2:高扩展性改造执行函数

如果后续有更复杂的参数场景(比如部分回调不需要传era、需要多个可变参数),可以改造timed_execution支持多元组格式的回调配置:

import time

def timed_execution(callbacks, era):
    for item in callbacks:
        # 兼容两种传入格式:直接传函数/传(函数, 额外位置参数元组, 额外关键字参数字典)
        if callable(item):
            func, extra_args, extra_kwargs = item, (), {}
        else:
            func, extra_args, extra_kwargs = item
        start_time = time.time()
        # 固定参数era放在最前,拼接额外参数
        func(era, *extra_args, **extra_kwargs)
        end_time = time.time()
        print(f'{func.__name__} took {end_time-start_time:.3f}s')

# 使用示例
def calculate_insights(era):
    timed_execution([
        # 按元组格式传入额外参数即可
        (dummy_function, (), {'letter': 'B'}),
        another_function,
        yet_another_function,
    ], era)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:45:01