Search code examples
pythonmodulenamespacesdocstring

Storing docstrings of functions defined in any module as String


So the deal is that i have to gather all functions and classes and whatnot from any module and display them on a webpage. Displaying them is not the hard part. The hard part is retrieving the docstrings and store them as strings. I have found a couple of ways to do it, however they are not perfect.

To elaborate, I have to do exactly what the help() function does in the interpreter. That is to ONLY list docstrings of the functions/classes etc defined in the module itself, NOT imported functions. I have very little clue of how help() it works.

First I tried this:

functions_list = [o for o in getmembers(my_module) if isfunction(o[1])]
for f_name, func in function_list:
    print(func.__doc__)

This will get values of module's dict, and works pretty fine. All though if you import something, say from foo import thud, this will list thud as a function in function_list, which is not what I want to do. My other idea was to use some sort of regexing, but this will be overkill I think. There must be a better solution out there. Any idea of what the solution is? Thanks


Solution

  • You can use the pyclbr module to read the module source statically:

    import pyclbr
    
    for name, obj in pyclbr.readmodule_ex('my_module', ['/path/to/module']).items():
        if isinstance(obj, pyclbr.Function):
            print(name, getattr(my_module, name).__doc__)