# just_pipline **Repository Path**: GodanKing/just_pipline ## Basic Information - **Project Name**: just_pipline - **Description**: pipeline sytle call for python.管线(流水线)式调用。 - **Primary Language**: Python - **License**: MulanPSL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-09-06 - **Last Updated**: 2024-09-03 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # just_pipeline 简单的管线风格调用库包装。将嵌套函数调用改为序列调用。 ```python f4(f3(f2(f1()))) # 管线式: pipeline(f1())( pipe(f2), pipe(f3), pipe(f4), ) ``` ## 快速开始 ```python from just_pipeline.pipeline import pipeline, pipe, pipe_last, Pipeline from just_pipeline.immutable import immutable_args # Or operator.concat def concat(ls: list, other: list): return ls + other @immutable_args def sort(ls: list): ls.sort() return ls def main(): ls = [1, 2, 3] final_ls = pipeline(ls)( pipe(concat, [4]), pipe(concat, [7]), pipe(concat, [5, 6]), pipe(sort), ) # Equal: # t = ls + [4] + [7] + [5, 6] # t.sort() # final_ls = t print(f"final ls: {final_ls}") print(f"ls: {ls}") # Output: # # final ls: [1, 2, 3, 4, 5, 6, 7] # ls: [1, 2, 3] # pipe_last兼容Python函数式,如:map、filter、reduce 等 def object_call(obj, attr: str, *args, **kwargs): """调用`obj`的指定成员函数""" return getattr(obj, attr)(*args, **kwargs) got = pipeline("a=1,b=2,bad,d='ok'")( pipe(object_call, "split", ","), # 按","分割字符串为数组 pipe_last(map, lambda x: x.split("=")), # 将数组元素按"="分割 pipe_last(filter, lambda x: len(x) == 2), # 选出数组中被"="分为两段的元素 ) # Equal: # t ="a=1,b=2,bad,d='ok'".split(",") # t = map(lambda x: x.split("="), t) # t = filter(lambda x: len(x) == 2, t) # got = t 但got计算过程遵从immutable,不产生副作用 print(got) # Output: # # {"a": "1", "b": "2", "d": "'ok'"} ``` **说明** - pipeline 管线,用于串联管道 - pipe 管道,用于计算处理数据,并返回结果 - pipe_last 管道,传入数据被放在参数末尾,以支持Python函数式编程风格,比如 map、filter、reduce 等 单从数据流向上看,数据好比沿着“烤串”的签子传递,`pipeline`好比烤串签子,`pipe`好比签子上穿的食物。 - `@immutable_args`深拷贝参数,用于保障参数不受函数中修改的影响。 - `Pipeline` 风格方便将管线保存起来用于参数传递或延迟执行。 - `pipeline` 是`pipeline`短名字版本。 ## 最佳实践 使用管线式调用时,必须将函数签名(函数名、入参、返回值)定义清楚,并添加注释阐释意图,避免代码将难以理解维护。 - 函数名必须表意清晰,最好添加注释说明。 - 入参、返回值都必须注明类型、结构和用途。