循环模块并在每个方法上运行inspect.getdoc()

问题描述 投票:0回答:1

我可以打印所有内置函数的列表:

for i, b in __builtins__.__dict__:
    print(i, b)

__name__
__doc__
__package__
__loader__
__spec__
__build_class__
__import__
abs
all
any
ascii
...

然后

import inspect
inspect.getdoc(<some_module>)

第一个想法是:

for b in __builtins__.__dict__:
    print(b, inspect.getdoc(b))

但是你知道此时“b”只是模块名称的字符串。

尝试过:

dir(__builtins__)
,这似乎也是一个字符串列表。

使用

list
不起作用:

list(__builtins__)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not iterable

显然,我可以在线阅读文档,但我想知道是否有可以在Python中做我想做的事情……而不是如何可以完成。

最终,如果有一个可以将它们一一输出的小生成器,那就太酷了:

mybuiltins.next() Method: reversed Doc: 'Return a reverse iterator over the values of the given sequence.'
    
python python-3.x introspection
1个回答
0
投票
这应该可以使用

dict.items

:

builtins = {k: inspect.getdoc(v) for k, v in __builtins__.__dict__.items()}
以下是一些示例用法:

# Get a specific builtin builtins['reversed'] # 'Return a reverse iterator over the values of the given sequence.' getattr(__builtins__, 'reversed') # <class 'reversed'>
# List all the builtin names, and their doc, as in your example
for k, v in builtins:
    print(k, v)
    
© www.soinside.com 2019 - 2024. All rights reserved.