Getting callable object from the frame

前端 未结 3 988
悲哀的现实
悲哀的现实 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:34

    A little ugly but here it is:

    frame.f_globals[frame.f_code.co_name]
    

    Full example:

    #!/usr/bin/env python
    
    import sys
    
    def foo():
      frame = sys._getframe()
      x = frame.f_globals[frame.f_code.co_name]
    
      print foo is x
    
    foo()
    

    Prints 'True'.

提交回复
热议问题