[three]Bean
Getting the docstring of a function (without the name)
Sep 13, 2011 | categories: python, oops View CommentsI was using argparse
and entry-points [console_scripts] in a
project at work and I wanted each of the 12 console scripts to have a --help
option that would display (among other things) the __doc__ of their main entry
function. This way I wouldn't have to rewrite those docs over and over when I
added a new script.
I came up with this little guy:
#!/usr/bin/env python """ The module level docstring """ import inspect def f(): """ The function level docstring """ print __my_doc__() def g(): """ Another function level docstring """ print __my_doc__() def __my_doc__(): """ Print the docstring of the calling function """ return globals()[inspect.stack()[1][0].f_code.co_name].__doc__ if __name__ == '__main__': f() g()
You could use it to, say, do:
import argparse def some_command(): """ This command will knock your socks off! """ parser = argparse.ArgumentParser(description=__my_doc__()) args = parser.parse_args() raise NotImplementedError("TODO -- gotta write this command still...")
Relying on globals()
really sucks. If anyone can think of a
better way to do it, let me know!
Thanks to some inspiration from @heewa, I landed on this solution which is much more portable.
import inspect def __my_doc__(n=1): """ Print the docstring of the calling function. Because this function doesn't rely on :py:func:`globals()`, it is more portable. It can now live in its own module and be invoked from elsewhere. """ frame = inspect.stack()[n][0] return frame.f_globals[frame.f_code.co_name].__doc__