如何用Python设计可扩展的数据处理管道?
进阶Python
答题要点
from abc import ABC, abstractmethod
from typing import Iterator, TypeVar, Generic
T = TypeVar('T')
U = TypeVar('U')
# 管道步骤抽象
class PipelineStep(ABC, Generic[T, U]):
@abstractmethod
def process(self, data: Iterator[T]) -> Iterator[U]:
pass
def __or__(self, other: 'PipelineStep') -> 'Pipeline':
return Pipeline([self, other])
# 具体步骤实现
class FilterStep(PipelineStep):
def __init__(self, predicate):
self.predicate = predicate
def process(self, data):
for item in data:
if self.predicate(item):
yield item
class TransformStep(PipelineStep):
def __init__(self, func):
self.func = func
def process(self, data):
for item in data:
yield self.func(item)
class BatchStep(PipelineStep):
def __init__(self, size):
self.size = size
def process(self, data):
batch = []
for item in data:
batch.append(item)
if len(batch) >= self.size:
yield batch
batch = []
if batch:
yield batch
# 管道组合
class Pipeline:
def __init__(self, steps=None):
self.steps = steps or []
def add(self, step):
self.steps.append(step)
return self
def execute(self, data):
result = iter(data)
for step in self.steps:
result = step.process(result)
return result
# 使用示例
pipeline = (
FilterStep(lambda x: x['status'] == 'active')
| TransformStep(lambda x: {'id': x['id'], 'value': x['amount'] * 1.1})
| BatchStep(100)
)
for batch in pipeline.execute(data_source):
save_to_database(batch)
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题