Я пишу код обработки данных с использованием сопрограмм на основе генератора, где данные непрерывно считываются с датчиков или файлов (источника), затем преобразуются с использованием одной или нескольких функций (фильтров) и, наконец, записываются куда-то (приемник).Вот пример использования некоторых фиктивных функций:
def coroutine(func):
def primed(*args, **kwargs):
coro = func(*args, **kwargs)
next(coro)
return coro
return primed
def source(name):
for x in range(1,4):
yield f'{name}{x}'
config = {
'filter1': '_F1',
'filter2': '_F2',
'filter3': '_F3',
}
@coroutine
def filter1(**config):
"""Coroutine that consumes AND produces"""
data = ''
while True:
data = yield data + config['filter1']
@coroutine
def filter2(**config):
"""Coroutine that consumes AND produces"""
data = ''
while True:
data = yield data + config['filter2']
@coroutine
def filter3(**config):
"""Coroutine that consumes AND produces"""
data = ''
while True:
data = yield data + config['filter3']
@coroutine
def writer(where):
while True:
data = yield
print(f'writing to {where}: {data}')
def pipeline(source, transforms, sinks):
for data in source:
for f in transforms:
transformed = f(**config).send(data)
for sink in sinks:
sink.send(transformed)
pipeline(source('data'),
transforms=[
filter1,
filter2,
filter3,
],
sinks=[
writer('console'),
writer('file'),
])
Обычно не рекомендуется смешивать поведение потребителя / производителя в сопрограммах (см. здесь . Однако этот подход позволяет мненаписать функцию pipeline
без жесткого кодирования отдельных функций преобразования (filter
). Если бы мне пришлось придерживаться «потребляющего» поведения сопрограмм, вот что я смог придумать:
def coroutine(func):
def primed(*args, **kwargs):
coro = func(*args, **kwargs)
next(coro)
return coro
return primed
def source(name, target):
for x in range(1,4):
target.send(f'{name}{x}')
config = {
'filter1': '_F1',
'filter2': '_F2',
'filter3': '_F3',
}
@coroutine
def filter1(target, **config):
"""This coroutine only consumes"""
while True:
data = yield
target.send(data + config['filter1'])
@coroutine
def filter2(target, **config):
"""This coroutine only consumes"""
while True:
data = yield
target.send(data + config['filter2'])
@coroutine
def filter3(target, **config):
"""This coroutine only consumes"""
while True:
data = yield
target.send(data + config['filter3'])
@coroutine
def writer(where):
while True:
data = yield
print(f'writing to {where}: {data}')
def pipeline():
f3 = filter3(writer('console'), **config)
f2 = filter2(f3, **config)
f1 = filter1(f2, **config)
source('data', f1)
pipeline()
Теперь мой вопрос: нужна ли первая реализация плохая идея, и если да, то что может пойти не так? Мне нравится это лучше, чем второй подход, хотя я понимаю, что я смешиваю поведение генератора / сопрограммы...