Reputation: 22887
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?
Upvotes: 2
Views: 386
Reputation: 569
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()
Upvotes: 0
Reputation: 1123480
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.
Upvotes: 2