The following code prints each function's docstring from an imported module. However, the results incude some functions that were not defined within the module, but rather, were imported by the module.
import inspect
import my_module
all_functions = inspect.getmembers(my_module, inspect.isfunction)
for i in all_functions:
print i[0] # print function name
print i[1].__doc__ # print docstring
How can I print only the docstrings of functions defined within the module?
Functions have a __module__
attribute storing the name of the module they were defined in. You can check if that matches the module you're inspecting. Note that this will frequently miss functions that actually are part of a module's API, but were defined in a different module. For example, heapq.heappush.__module__ == '_heapq'
, because the function is actually defined in a C module _heapq
and import *
ed into the Python module heapq
.