Python 将多个函数链接到一个函数中

Mon*_*key 0 python pipeline function chain

我有几个字符串处理函数,例如:

def func1(s):
    return re.sub(r'\s', "", s)

def func2(s):
    return f"[{s}]"
...
Run Code Online (Sandbox Code Playgroud)

我想将它们组合成一个管道函数:my_pipeline(),以便我可以将其用作参数,例如:

class Record:
    def __init__(self, s):
        self.name = s
    
    def apply_func(self, func):
        return func(self.name)

rec = Record(" hell o")
output = rec.apply_func(my_pipeline)
# output = "[hello]"
Run Code Online (Sandbox Code Playgroud)

目标是用作my_pipeline参数,否则我需要一一调用这些函数。

谢谢。

Mec*_*Pig 5

您可以编写一个简单的工厂函数或类来构建管道函数:

def pipeline(*functions):
    def _pipeline(arg):
        result = arg
        for func in functions:
            result = func(result)
        return result
    return _pipeline
Run Code Online (Sandbox Code Playgroud)

测试:

>>> rec = Record(" hell o")
>>> rec.apply_func(pipeline(func1, func2))
'[hello]'
Run Code Online (Sandbox Code Playgroud)

这是参考编写的更精致的版本,使用functools.reduce

from functools import reduce

def pipeline(*functions):
    return lambda initial: reduce(lambda arg, func: func(arg), functions, initial)
Run Code Online (Sandbox Code Playgroud)

我没有测试,但根据我的直觉,每个循环都会在python级别多调用一次该函数,因此性能可能不如循环实现。