0

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?

sgarza62
  • 5,998
  • 8
  • 49
  • 69

1 Answers1

1

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Awesome, thanks! Had to convert the function to a `str` on the if statement in order to do the check: `if str(i[1].__module__) == 'my_module':` (in reference to the example in the question) – sgarza62 Jul 30 '13 at 00:47