listing all functions in a module
本问题已经有最佳答案,请猛点这里访问。
我想在一个模块中列出所有的功能,但我有一个重点。我只得到
1 2 3 4 5 | import package functions = [] for i in dir(package): functions.append(i) print(functions) |
所以现在我得到了
1 2 3 4 5 | import package functions = [] for i in dir(package): #here like adding function and then make package function.other_package print(functions) |
有人能帮我吗?
it is not a duplicate becuse i not want a doc but just only all the functions of all the files in a package
对
1 2 3 4 5 6 7 | # package foo foo ├── bar.py # has a function"bar" ├── __init__.py # has a function"foo" └── baz ├── qux.py # has functions"baz" and"qux" └── __init__.py |
你期望这样的结果:
1 2 3 4 | foo/bar.py: [bar] foo/__init__.py: [foo] foo/baz/qux.py: [qux, baz] foo/baz/__init__.py: [] |
如果没有进行其他假设,了解包中包含哪些函数的唯一方法是让python自己编译文件并显示其内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import os import inspect import typing # find all python files below a certain folder files = [] for (dirpath, dirnames, filenames) in os.walk('path/to/a/package/foo'): for filename in filenames: if filename.endswith('.py'): files.append(os.sep.join([dirpath, filename])) for f in files: # turn the files into code objects and find declared constants functions = [] code_obj = compile(open(f).read(), f, 'exec') members = dict(inspect.getmembers(code_obj)) for idx in range(len(members['co_consts'])//2): val = members['co_consts'][idx * 2] name = members['co_consts'][idx * 2 + 1] # suboptimal: this check also allows lambdas and classes if isinstance(val, types.CodeType): functions.append(name) print(f'{f}: {functions}') |
这张剪下来的照片正是上面的结果。据我所知,没有办法向一个包询问它的所有功能,不仅是那些它愿意公开的功能。
另请参阅本qa和本帖,了解从代码对象中提取函数的其他更准确(尽管更复杂)的方法。