Frage

I use the following code to get the caller's method name in the called method:

import inspect

def B():
    outerframe = inspect.currentframe().f_back
    functionname = outerframe.f_code.co_name
    docstring = ??
    return "caller's name: {0}, docsting: {1}".format(functionname, docstring)

def A():
    """docstring for A"""
    return B()


print A()

but I also want to get the docstring from the caller's method in the called method. How do I do that?

War es hilfreich?

Lösung

You can't, because you do not have a reference to the function object. It's the function object that has the __doc__ attribute, not the associated code object.

You'd have to use the filename and linenumber information to try and make an educated guess as to what the docstring might be, but due to the dynamic nature of Python that is not going to be guaranteed to be correct and current.

Andere Tipps

I wouldn't necessarily advise it, but you can always use the globals() to find the function by name. It would go something like this:

import inspect

def B():
    """test"""
    outerframe = inspect.currentframe().f_back
    functionname = outerframe.f_code.co_name
    docstring = globals()[ functionname ].__doc__
    return "caller's name: {0}, docsting: {1}".format(functionname, docstring)

def A():
    """docstring for A"""
    return B()

print A()
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top