我有几个字符串处理函数,例如:
def func1(s):
return re.sub(r'\s', "", s)
def func2(s):
return f"[{s}]"
...
我想将它们组合成一个管道函数:
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]"
目标是使用
my_pipeline
作为参数,否则我需要一一调用这些函数。
谢谢你。
您可以编写一个简单的工厂函数或类来构建管道函数:
def pipeline(*functions):
def _pipeline(arg):
result = arg
for func in functions:
result = func(result)
return result
return _pipeline
测试:
>>> rec = Record(" hell o")
>>> rec.apply_func(pipeline(func1, func2))
'[hello]'
这是参考this使用
functools.reduce
编写的更精致的版本:
from functools import reduce
def pipeline(*functions):
return lambda initial: reduce(lambda arg, func: func(arg), functions, initial)
我没有测试,但根据我的直觉,每个循环都会在python级别多调用一次该函数,所以性能可能不如循环实现。
您可以创建一个调用这些函数的函数:
def my_pipeline(s):
return func1(func2(s))
使用函数列表(这样您就可以在其他地方组装它们):
def func1(s):
return re.sub(r'\s', "", s)
def func2(s):
return f"[{s}]"
def func3(s):
return s + 'tada '
def callfuncs(s, pipeline):
f0 = s
pipeline.reverse()
for f in pipeline:
f0 = f(f0)
return f0
class Record:
def __init__(self, s):
self.name = s
def apply_func(self, pipeline):
return callfuncs(s.name, pipeline)
# calling order func1(func2(func3(s)))
my_pipeline = [func1, func2, func3]
rec = Record(" hell o")
output = rec.apply_func(my_pipeline)
您可以使用 quent 库来实现:
from quent import Chain
...
my_pipeline = Chain().then(func1).then(func2)
rec = Record(" hell o")
output = rec.apply_func(my_pipeline)
免责声明:我是该库的作者。