2

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?

Community
  • 1
  • 1
BioGeek
  • 21,897
  • 23
  • 83
  • 145

2 Answers2

2

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

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()
max k.
  • 549
  • 4
  • 9
  • The function name is not necessarily the name under which it was stored; you can reassign functions just like any other object. Nor are they always going to be globals, methods on classes certainly are not globals. – Martijn Pieters Mar 11 '13 at 17:02
  • Yeah like I said, certainly wouldn't recommend it but if you absolutely need a quick fix in a small program then it is a possibility – max k. Mar 11 '13 at 22:05