4

I am writing a module that requires the docstring of the calling script. Thus far I have managed to obtain the filename of the calling script using

import inspect
filename = inspect.stack()[1].filename

The docstring can be found inside the calling script using __doc__. Getting the docstring from the called script does not seem trivial however. Of course I could write a function, but this is bound to ignore some uncommon cases. I there a way to actually parse the calling script to find its docstring (without executing its code)?

Octaviour
  • 745
  • 6
  • 18
  • What's the context for this - why do you need the calling function's docstring? – jonrsharpe Apr 20 '17 at 12:46
  • 1
    Would simply importing the file (module) work and then calling module.__doc__ ? As far as I know even pydoc imports the modules to find documentation so safeguarding against execution on import should be in place with an if __name__ == '__main__': – chaos Apr 20 '17 at 13:57
  • 1
    Also the ast module might be of use – chaos Apr 20 '17 at 14:03
  • I am using python to run some experiments in the lab. Measurement results are save to a file on disk. Preferably the file contains a text description of the measurement. Conceptually I think the most logical place to put the description in the measurement script is in the docstring. Since I want to move all file IO to a module, I want to get the docstring from the module. Simply importing the file does not seem to be the best idea as I do not want to add the `if __name__ == '__main__'` statement. ast seems to do what I want. – Octaviour Apr 20 '17 at 14:22

1 Answers1

6

Based on chaos's suggestion to use ast I wrote the following which seems to work nicely.

import ast

with open(fname, 'r') as f:
    tree = ast.parse(f.read())
docstring = ast.get_docstring(tree)
Octaviour
  • 745
  • 6
  • 18
  • It's worth noting that [`ast.get_docstring()`](https://docs.python.org/3/library/ast.html#ast.get_docstring) accepts a second optional boolean argument named _`clean`_ which determines whether the "raw" docstring is returned or one with its indentation cleaned-up. – martineau Mar 02 '21 at 01:12