In python, how to print the docstrings of all functions defined in an imported module, without the functions that the imported module itself imported?

StackOverflow https://stackoverflow.com/questions/17936358

Вопрос

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top