优雅的方式来抽象多个函数调用?

Rei*_*ica 1 python function

例:

>>> def write_to_terminal(fmt, *args):
...     print fmt % args
>>> LOG = logging.getLogger(__name__)
>>> info = multicall(write_to_terminal, LOG.info)
>>> debug = multicall(write_debug_to_terminal, LOG.debug)
>>> ...
>>> info('Hello %s', 'guido') # display in terminal *and* log the message
Run Code Online (Sandbox Code Playgroud)

有优雅的写作方式multicall吗?也许在标准库的帮助下......没有重新发明轮子?

Ste*_*eef 5

像这样的东西?

def multicall(*functions):
    def call_functions(*args, **kwds):
        for function in functions:
            function(*args, **kwds)
    return call_functions
Run Code Online (Sandbox Code Playgroud)

如果你想汇总结果:

def multicall(*functions):
    def call_functions(*args, **kwds):
        return [function(*args, **kwds) for function in functions]
    return call_functions
Run Code Online (Sandbox Code Playgroud)

编辑

建议装饰者; 在这种情况下,它看起来像这样:

def appendcalls(*functions):
    def decorator(decorated_function):
        all_functions = [decorated_function] + list(functions)
        def call_functions(*args, **kwds):
            for function in all_functions:
                function(*args, **kwds)
        return call_functions
    return decorator


LOG = logging.getLogger(__name__)

@appendcalls(LOG.info)
def info(fmt, *args):
    print fmt % args

info('Hello %s', 'guido')
Run Code Online (Sandbox Code Playgroud)

appendcalls()在装饰函数之后调用任意数量的函数.您可能希望以不同的方式实现装饰器,具体取决于您想要的返回值 - 装饰函数的原始值,所有函数结果的列表或根本没有.