invoking yield for a generator in another function

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

    The behavior you describe looks exactly like a simple function call. Like below.

    def f(manager):
        print("Entering f")
        manager.stop_and_do_stuff()
        print("Exiting f")
    
    class Manager(Object):
        def shouldContinue(self):
            return True
    
        def stop_and_do_stuff(self):
            print("Manager stop and do stuff")
    
        def main_hook(self,f):
            while self.shouldContinue()
                print("Manager Setup")
                f(self)
                print("Manager Tear Down")
    

    No problem if f() is provided by another user of if stop_and_do_stuff is called from some inner function. If you also want the manager to be able to unwind stack from stop_and_do_stuff and really exit in some cases, no problem. Just raise some exception from it and you would catch it from main_hook or upper code.

    You should be able to do from inside stop_and_and_do_stuff() whatever you want to do from the caller of main hook. If not you should explain why.

    What is unclear in the question is what's happening on the caller side of main_hook() and why you would want to be able to exit the main_hook loop, but not really. Either the main_loop caller expect a generator either it does not. You need to explain that part if you want to get a sensible answer (some context informations would also be nice, if you really explain WTF you are trying to do, and your real restrictions - you said f is provided by some other user and main_hook is in a lib, what of main_hook caller ? - there is probably well known usual solutions).

提交回复
热议问题