Search code examples
pythondocstring

How do I get the docstring from a calling module?


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.


Solution

  • 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).