coroutine.py (737B)
1 #!/usr/bin/env python3 2 # File : coroutine.py 3 # Description: Simple coroutine example 4 # Copyright 2022 Harvard University. All Rights Reserved. 5 from inspect import getgeneratorstate 6 7 8 def coroutine(): 9 ncalls = 0 10 while True: 11 x = yield ncalls 12 ncalls += 1 13 print(f'coroutine(): {x} (call id: {ncalls})') 14 15 16 def main(): 17 c = coroutine() 18 print(getgeneratorstate(c)) 19 next(c) # prime the coroutine; next() returns 0 here 20 print(getgeneratorstate(c)) 21 22 c.send('CS107') 23 print('main(): control back in main function') 24 n_call = c.send('AC207') 25 print(f'main(): called coroutine() {n_call} times') 26 27 c.close() 28 print(getgeneratorstate(c)) 29 30 31 if __name__ == "__main__": 32 main()