【问题标题】:listing all functions in a module [duplicate]列出模块中的所有功能[重复]
【发布时间】:2019-08-05 03:15:10
【问题描述】:

我想在一个模块中列出所有功能,但我被困在一个点上。 我只得到__init__.py 中的函数 但不是包中的所有功能。这是我已经准备好的代码:

import package
functions = []
for i in dir(package):
    functions.append(i)
print(functions)

所以现在我得到了__init__.py 中所有函数的列表,但不是整个包。如何获取“包”中的所有功能? 我想像这样得到它:

import package
functions = []
for i in dir(package):
    #here like adding function and then make package function.other_package
print(functions)

有人可以帮我吗?

它不是重复的,因为我不想要一个文档,而只是一个包中所有文件的所有功能

【问题讨论】:

  • 如果你说pacakge,你是指一个特定文件夹下的所有文件,你想成为包根,还是你有许多import声明定义包的内容是?
  • 什么是package?它是在哪里定义的?
  • 我的意思是像 tqdm 包是 tqdm 并且是导入的

标签: python python-3.x


【解决方案1】:

package 的确切定义有点棘手,所以我只假设非常基础的内容:您有一个目录,假设为包根目录,其中直接包含许多 python 文件或嵌套更深,您认为它是包的一部分。可能是这样的:

# 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

你期望得到这样的结果:

foo/bar.py: [bar]
foo/__init__.py: [foo]
foo/baz/qux.py: [qux, baz]
foo/baz/__init__.py: []

如果没有其他假设,了解你的包包含哪些函数的唯一方法是让python自己编译文件并显示它们的内容:

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}')

这个截图为我打印了上面的结果。据我所知,没有办法询问包的所有功能,而不仅仅是它愿意公开的功能。


另请参阅this QAthis post,了解从代码对象中提取函数的替代和更准确(尽管更复杂)的方法。

【讨论】:

    猜你喜欢
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多