# ~parson/DataMine/coroutine.py D. Parson Fall 2022 def makeClosure(boundParameter): # Model from an earlier assignment is binding columns for # attributes here, then apply returned closure function a row # at a time. def closure(callParameter): return boundParameter + callParameter return closure cl = makeClosure(1) print('\nOn cl = makeClosure(1), cl(10)=', cl(10), 'TYPE', type(cl)) print('On cl = makeClosure(1), cl(100)=', cl(100), 'TYPE', type(cl)) print() def makeGenerator(start, end, inc): # Model from current CSC assignments is a _generator.py # they yields a new table of regressors or classifiers # + data on every iteration. for i in range(start, end, inc): yield i gen = makeGenerator(11, 100, 11) for value in gen: print('makeGenerator(11, 100, 11) yields', value, 'TYPE', type(gen)) def makeCoroutine(start, end, inc): # Yield passes values in as well as out. # A coroutine is a non-preemptive thread of control that does not # terminate until it returns None or falls off the bottom, but runs # only when scheduled from another non-preemptive thread via send(...). yield 0 j = 1 for i in range(start, end, inc): print('\tIn coroutine, i=',i,'j=',j) j = yield i*j print() cor = makeCoroutine(2, 23, 2) sendval = 0 cor.__next__() # Takes execution to the first yield. while True: try: sendval += 3 recvval = cor.send(sendval) print('makeCoroutine(2, 23, 2),sendval=',sendval,'recvval=',recvval, 'TYPE', type(cor)) except StopIteration: # fell off bottom of coroutine. break # out of loop # BELOW IS THE DEMO RUN: # On cl = makeClosure(1), cl(10)= 11 TYPE # On cl = makeClosure(1), cl(100)= 101 TYPE # # makeGenerator(11, 100, 11) yields 11 TYPE # makeGenerator(11, 100, 11) yields 22 TYPE # makeGenerator(11, 100, 11) yields 33 TYPE # makeGenerator(11, 100, 11) yields 44 TYPE # makeGenerator(11, 100, 11) yields 55 TYPE # makeGenerator(11, 100, 11) yields 66 TYPE # makeGenerator(11, 100, 11) yields 77 TYPE # makeGenerator(11, 100, 11) yields 88 TYPE # makeGenerator(11, 100, 11) yields 99 TYPE # # In coroutine, i= 2 j= 1 # makeCoroutine(2, 23, 2),sendval= 3 recvval= 2 TYPE # In coroutine, i= 4 j= 6 # makeCoroutine(2, 23, 2),sendval= 6 recvval= 24 TYPE # In coroutine, i= 6 j= 9 # makeCoroutine(2, 23, 2),sendval= 9 recvval= 54 TYPE # In coroutine, i= 8 j= 12 # makeCoroutine(2, 23, 2),sendval= 12 recvval= 96 TYPE # In coroutine, i= 10 j= 15 # makeCoroutine(2, 23, 2),sendval= 15 recvval= 150 TYPE # In coroutine, i= 12 j= 18 # makeCoroutine(2, 23, 2),sendval= 18 recvval= 216 TYPE # In coroutine, i= 14 j= 21 # makeCoroutine(2, 23, 2),sendval= 21 recvval= 294 TYPE # In coroutine, i= 16 j= 24 # makeCoroutine(2, 23, 2),sendval= 24 recvval= 384 TYPE # In coroutine, i= 18 j= 27 # makeCoroutine(2, 23, 2),sendval= 27 recvval= 486 TYPE # In coroutine, i= 20 j= 30 # makeCoroutine(2, 23, 2),sendval= 30 recvval= 600 TYPE # In coroutine, i= 22 j= 33 # makeCoroutine(2, 23, 2),sendval= 33 recvval= 726 TYPE