Is there a Python function that checks if a generator is started?

前端 未结 4 428
轻奢々
轻奢々 2021-01-05 00:46

I try to define a generator function mycount() that can be reset with the generator function send(0) as in the example below. Everything works fine

4条回答
  •  离开以前
    2021-01-05 01:07

    Here's a complete implementation Python2 compatible routine, getgeneratorstate(gtor), with test code.

    import unittest
    import enum
    
    class GtorState(enum.Enum):
        GEN_RUNNING ='GEN_RUNNING'
        GEN_CLOSED ='GEN_CLOSED'
        GEN_CREATED ='GEN_CREATED'
        GEN_SUSPENDED ='GEN_SUSPENDED'
    
        @staticmethod
        def getgeneratorstate(gtor):
            if gtor.gi_running:
                return GtorState.GEN_RUNNING
    
            if gtor.gi_frame is None:
                return GtorState.GEN_CLOSED
    
            if gtor.gi_frame.f_lasti == -1:
                return GtorState.GEN_CREATED
    
            return GtorState.GEN_SUSPENDED
        #end-def
    
    def coro000():
        """ a coroutine that does little 
    
        """ 
        print('-> coroutine started')
        x =yield
        print('-> coroutine received ', x)
    
    
    class Test_Coro(unittest.TestCase):
        def test_coro000(self):
    
            my_coro000 =coro000()
            self.assertEqual( GtorState.getgeneratorstate(my_coro000), GtorState.GEN_CREATED)
    
            next(my_coro000)  # prints '-> coroutine started'
            self.assertEqual( GtorState.getgeneratorstate(my_coro000), GtorState.GEN_SUSPENDED)
    
            try:
                my_coro000.send(42)  # prints '-> coroutine received 42 
                self.assertEqual( GtorState.getgeneratorstate(my_coro000), GtorState.GEN_SUSPENDED)
    
                self.fail('should have raised StopIteration ')
    
            except StopIteration:
                self.assertTrue(True, 'On exit a coroutine will throw StopIteration')
                self.assertEqual( GtorState.getgeneratorstate(my_coro000), GtorState.GEN_CLOSED)
    

提交回复
热议问题