简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM