Skip to main content
5 of 6
added 1 characters in body
tshepang
  • 752
  • 6
  • 19

Displaying user-defined functions and their docstrings

Let's say I want to create dynamic documentation of functions I wrote, without using the help() function (I don't want the user to care about arguments accepted by my function, nor get cluttered with other stuff like the copyright info, or other stuff that aren't functions).

Here's an attempt:

import inspect

def foo():
    """Return 'foo' string"""
    return "foo"

def user_defined_functions():
    """Return names of user-defined functions"""
    for name in globals():
        if inspect.isfunction(eval(name)):
            docstring = eval(name + ".__doc__")
            print("{}:\n   {}".format(name, docstring))

And here's the pretty result:

>>> import test
>>> test.user_defined_functions()
user_defined_functions:
   Return names of user-defined functions
foo:
   Return 'foo' string

If I had just used the help function I could have gotten extra stuff I don't need (I'm not writing a library, so the user doesn't need all of this):

Help on module test:

NAME
    test

FUNCTIONS
    foo()
        Return 'foo' string
    
    user_defined_functions()
        Return names of user-defined functions

FILE
    /home/wena/src/utils/test.py

EDIT (after review):

import inspect

def foo():
    """Return 'foo' string"""
    return "foo"

def user_defined_functions():
    """Return names of user-defined functions"""
    for name, value in globals().items():
        if inspect.isfunction(value):
            print("{}:\n   {}".format(name, value.__doc__))
tshepang
  • 752
  • 6
  • 19