can't consumo all'interno di coroutine. Per implementare la tua idea, l'unico modo che vedo è implementare Asynchronous Iterator. Se ho ragione, qualcosa del genere:
class MapFilter:
def __init__(self, aiterable, p, func):
self.aiterable = aiterable
self.p = p
self.func = func
async def __aiter__(self):
return self
async def __anext__(self):
while True:
payload = await self.aiterable.__anext__() # StopAsyncIteration would be raise here on no new values
if self.p(payload):
return self.func(payload)
Proviamoci. Ecco esempio completo di aiuto arange
classe (l'ho preso da here):
import asyncio
class arange:
def __init__(self, n):
self.n = n
self.i = 0
async def __aiter__(self):
return self
async def __anext__(self):
i = self.i
self.i += 1
if self.i <= self.n:
await asyncio.sleep(0) # insert yield point
return i
else:
raise StopAsyncIteration
class MapFilter:
def __init__(self, aiterable, p, func):
self.aiterable = aiterable
self.p = p
self.func = func
async def __aiter__(self):
return self
async def __anext__(self):
while True:
payload = await self.aiterable.__anext__()
if self.p(payload):
return self.func(payload)
async def main():
aiterable = arange(5)
p = lambda x: bool(x>2)
func = lambda x: x*2
async for i in MapFilter(aiterable, p, func):
print(i)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
uscita:
6
8
fonte
2016-03-18 21:20:55
Hai guardato ad es. https://pypi.python.org/pypi/paralleltools/0.0.3? – jonrsharpe
@jonrsharpe questa libreria non riguarda asyncio ma discussioni. –
Tentativo di implementare il metodo per ottenere all'interno delle funzioni asincrone: http://stackoverflow.com/a/37572657/1113207 –