Search code examples
pythondocstring

Printing help docstring of all the functions in the string module: Python


I am trying to print all the functions and their help docstrings in the strings module but am not getting the desired results. Below are the things which I have tried:

r = 'A random string'

1.  [help(fn) for fn in r.__dir__() if not fn.startswith('__')]
2.  [help(r.fn) for fn in r.__dir__() if not fn.startswith('__')]
3.  [fn.__doc__ for fn in r.__dir__() if not fn.startswith('__')]
4.  [r.fn.__doc__ for fn in r.__dir__() if not fn.startswith('__')]

and a few things more. Some of them throw errors saying that r does not have attribute named 'fn'. Others just print the help documentation for the 'str' function. Is there any way I can print this for all the functions dynamically?


Solution

  • In python2:

    for i in dir(r):
        if not i.startswith('__'):
            print getattr(r, i).__doc__
    

    In python3:

    for i in dir(r):
        if not i.startswith('__'):
            print(getattr(r, i).__doc__)
    

    (it's basically the same, changes the print function only). You need to get the method object wth getattr in order to show its __doc__ attribute.