martin fowler收集管道模式中的迭代器管道包装器
IterPipe的Python项目详细描述
管道
简介
这是python标准库中迭代器函数的包装器,使将它们链接到一个管道中变得更加容易和可读。
这是用python的标准迭代器函数实现martin fowler的collection pipeline模式(https://martinfowler.com/articles/collection-pipeline/)的一种方法。
为了说明这个概念,我们将在每个示例中执行以下步骤序列:
- 从一个
range
迭代器开始, - 然后
filter
只传递大于或等于6的值 - 然后使用
map
函数将步骤2中的每个数字平方 - 然后
sum
第3步中的正方形
这是代码,使用中间变量,没有链接。
deffilter_func(x):# Simple function used in "filter" examples belowreturnx>=6defsquared(x):# Simple function to square it's input. Used in "map" below.returnx*xinput=range(10)intermediate_1=filter(filter_func,input)# Apply squared function to each value returned by intermediate_1 iteratorintermediate_2=map(squared,intermediate_1)output=sum(intermediate_2)print("Output without chaining: {output}".format(output=output))
这里是相同的代码,使用常规的python语法链。注意,执行是由内向外进行的,最后一个操作(sum)出现在前面。
deffilter_func(x):returnx>=6defsquared(x):# Simple function to square it's input. Used in "map" below.returnx*xinput=range(10)output=sum(map(squared,filter(filter_func,input)))print("Output with regular Python chaining: {output}".format(output=output))
这里是同样的代码,使用IterPipe
包装器。注意,它的读取顺序与执行的顺序相同。
fromIterPipeimportIterPipedeffilter_func(x):returnx>=6defsquared(x):# Simple function to square it's input. Used in "map" below.returnx*xinput=range(10)output=(IterPipe(input).filter(filter_func).map(squared).sum())print("Output with IterPipe chaining: {output}".format(output=output))
iterpipe包装器支持对builtins
、itertools
和functools
中的迭代器进行操作的以下函数。
- 累积
- 全部
- 任何
- 链条
- 组合
- 组合_与_替换
- 压缩
- 循环
- dict
- 下降时间
- 枚举
- 过滤器
- 过滤器FALSE
- 冻结集
- 分组方式
- 岛
- 迭代器
- 列表
- 地图
- 最大值
- 最小值
- 下一步
- 置换
- 产品
- 减少
- 设置
- 排序
- 星图
- 总和
- 服用时
- 三通
- 元组
- 拉链
- 拉链最长
安装
适用于Python3.4或更高版本。
pip install -U IterPipe