5

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)?

4
  • What's the context for this - why do you need the calling function's docstring? Commented Apr 20, 2017 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': Commented Apr 20, 2017 at 13:57
  • 1
    Also the ast module might be of use Commented Apr 20, 2017 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. Commented Apr 20, 2017 at 14:22

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

1 Comment

It's worth noting that 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.