简体   繁体   中英

Get function object of caller in Python 2.7?

In playing with inspect and reading the other questions here, I still cannot figure out how to get the function object of the caller more cleanly than to load the module by its path and then find the function within that.

In other words, how would you complete the following so that caller() returns a method object?

import inspect

def caller():
    frame = inspect.stack()[2]
    code = frame[0]
    path = frame[1]
    line = frame[2] 
    name = frame[3] # function NAME string
    # TODO: now what?
    return func

def cry_wolf():
    func = caller()
    print "%s cried 'WOLF!'" % (func.__name__,)

def peter():
    cry_wolf()

Remember, I already know the function name but what I'm trying to access is the function object that the calling code is running in. The result desired is:

peter cried 'WOLF!'

DONE! Thanks to user 61612, I have completed this code:

import imp, inspect, sys

def caller():
    frame = inspect.stack()[2]
    code = frame[0]
    path = frame[1]
    line = frame[2] 
    name = frame[3]
    return code.f_globals[name]

def cry_wolf():
    func = caller()
    print "%s cried 'WOLF!'" % (func.__name__,)

def peter():
    cry_wolf()

Awesome!

Frame objects have the f_globals attribute :

import inspect

def caller():
    tup = inspect.stack()[2]
    return tup[0].f_globals[tup[3]] # <function peter at address>

def cry_wolf():
    func = caller()
    print("%s cried 'WOLF!'" % (func.__name__,)) # peter cried 'WOLF!'

def peter():
    cry_wolf()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM