Getting callable object from the frame

前端 未结 3 989
悲哀的现实
悲哀的现实 2021-02-06 11:31

Given the frame object (as returned by sys._getframe, for instance), can I get the underlying callable object?

Code explanation:

def foo():
    frame = s         


        
3条回答
  •  情话喂你
    2021-02-06 12:18

    Not really an answer, but a comment. I'd add it as a comment, but I don't have enough "reputation points".

    For what it's worth, here's a reasonable (I think) use case for wanting to do this sort of thing.

    My app uses gtk, and spins a lot of threads. As anyone whose done both of these at once knows, you can't touch the GUI outside the main thread. A typical workaround is to hand the callable that will touch the GUI to idle_add(), which will run it later, in the main thread, where it is safe. So I have a lot of occurrences of:

    def threaded_gui_func(self, arg1, arg2):
        if threading.currentThread().name != 'MainThread':
            gobject.idle_add(self.threaded_gui_func, arg1, arg2)
            return
        # code that touches the GUI
    

    It would be just a bit shorter and easier (and more conducive to cut-n-paste) if I could just do

    def thread_gui_func(self, arg1, arg2):
        if idleIfNotMain(): return
        # code that touches the GUI
    

    where idleIfNotMain() just returns False if we are in the main thread, but if not, it uses inspect (or whatever) to figure out the callable and args to hand off to idle_add(), then returns True. Getting the args I can figure out. Getting the callable appears not to be too easy. :-(

提交回复
热议问题