invoking yield for a generator in another function

后端 未结 5 2427
灰色年华
灰色年华 2021-02-14 16:06

suppose I have some manager object. This object\'s API has a main_hook function, that gets another function f as it\'s argument, and runs the given

5条回答
  •  离开以前
    2021-02-14 16:14

    I don't understand the whole either (what does the main_hook caller look like ?), but i would say, Throw a StopNow exception, when you should stop, just like you should throw StopIteration when your generator is finished.

    here is how i understood the thing as well as what i would do.

    class StopNow(Exception):
        pass
    
    def main_hook(self,f):
        got_stop_now_exc = False
        while (!got_stop_now_exc and self.shouldContinue()):
            #do some preparations
            try:
                 f(self)
            except StopNow:
                 got_stop_now_exc = True
    
            #do some compulsary tear down, exception or not
    
    def stop_and_do_stuff()
        raise StopNow()
    def my_f():
        if needed:
            stop_and_do_stuff()
    
    def the_main_hook_caller():
        while i_should:
            managerthingie.main_hook(my_f)
            do_stuff()
    

提交回复
热议问题