invoking yield for a generator in another function

后端 未结 5 2436
灰色年华
灰色年华 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:33

    I am not quite sure what exactly you are trying to achieve, so maybe if you can explain the problem more instead of giving solution that would be better.

    From my partial understanding why don't you do something like this

    def main_hook(self,f):
        while (self.shouldContinue()):
            #do some preparations
            stop_and_do_stuff = f(self)
            if stop_and_do_stuff :
                yield
                
            #do some tear down
        
    

    So basically f returns a flag to stop or not, and if it says stop we yield to function which called main_hook and that function can continue after doing some stuff

    e.g.

    class A(object):
        def main_hook(self,f):
            while (self.shouldContinue()):
                #do some preparations
                stop = f(self)
                if stop:
                    yield
                    
                #do some tear down
            
        def shouldContinue(self):
            return True
        
    def f(a):
        return True
    
    a = A()
    for x in a.main_hook(f):
        print x
    

提交回复
热议问题