fromasyncioimportrun,sleepclassAlternatingGenerator:def__init__(self,gen1,gen2):self.gen1=gen1self.gen2=gen2self.next=gen1def__aiter__(self):returnselfasyncdef__anext__(self):# if we are done we both generators
ifnotself.gen1andnotself.gen2:raiseStopAsyncIterationtry:# saving the current generator into a variable for later
current=self.next# if the other genrerator is not null, alternating to it for the next iteration
ifself.nextisself.gen1andself.gen2:self.next=self.gen2elifself.nextisself.gen2andself.gen1:self.next=self.gen1# calling the generator of the current iteration and returning the next result
returnawaitanext(current)exceptStopAsyncIteration:# unsetting the generator that just finished
ifcurrentisself.gen1:self.gen1=Noneelse:self.gen2=None# recursive call, trying again with the other generator
returnawaitself.__anext__()asyncdefthree():foriinrange(3,31,10):awaitsleep(0.25)yieldiasyncdeffive():foriinrange(5,101,10):awaitsleep(0.25)yieldiasyncdefmain():gen=AlternatingGenerator(three(),five())try:# or just use "async for item in gen:"
whileTrue:print(awaitanext(gen))exceptStopAsyncIteration:passif__name__=='__main__':run(main())
Top comments (0)