How do I get the docstring from a calling module?

Viewed 78

Can I get the __doc__ string of the main script?

Here is the starting script, which would be run from command line: python a.py

module a.py

import b
b.func()

module b.py

def func():
    ???.__doc__

How can I get the calling module, as an object?

I am not asking about how to get the file name as string. I know how to retrieve the file's name from stack trace. I don't want to retrieve the doc string by parsing manually. Also, I don't think I can just import by m = __import__(a) because of circular import loop.

2 Answers

a.py

"""
Foo bar
"""

import b
if __name__ == '__main__':
    b.show_your_docs()

b.py

def show_your_docs():
    name = caller_name(1)
    print(__import__(name).__doc__)

Where caller_name is code from this gist

The weakness of this approach though is it is getting a string representation of the module name and reimporting it, instead of getting a reference to the module (type).

This is the full solution from @MatthewMartin 's accepted answer:

def show_your_docs():
    name = caller_name(1)
    print(__import__(name).__doc__)

def caller_docstring(level=1):
    name = caller_name(level)
    return __import__(name).__doc__

    def caller_name(skip=2):
        def stack_(frame):
            framelist = []
            while frame:
                framelist.append(frame)
                frame = frame.f_back
            return framelist

        stack = stack_(sys._getframe(1))
        start = 0 + skip
        if len(stack) < start + 1:
            return ''
        parentframe = stack[start]

        name = []
        module = inspect.getmodule(parentframe)
        if module:
            name.append(module.__name__)
        if 'self' in parentframe.f_locals:
            name.append(parentframe.f_locals['self'].__class__.__name__)
        codename = parentframe.f_code.co_name
        if codename != '<module>':  # top level usually
            name.append(codename)  # function or a method
        del parentframe
        return ".".join(name)
text = caller_docstring(2)
Related