在Python环境中查找所有定义的函数

2024-04-19 18:08:41 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以找到在python环境中定义的所有函数?你知道吗

例如,如果我

def test:
   pass

some_command_here将返回test


Tags: 方法函数testhere定义环境defsome
3条回答

您可以使用inspect模块:

import inspect
import sys


def test():
    pass

functions = [name for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isfunction)]
print functions

印刷品:

['test']

可以使用globals()获取文件全局范围中定义的所有内容,使用inspect筛选所关心的对象。你知道吗

[ f for f in globals().values() if inspect.isfunction(f) ]

使用globals()types.FunctionType

>>> from types import FunctionType
>>> functions = [x for x in globals().values() if isinstance( x, FunctionType)]

演示:

from types import FunctionType
def func():pass
print [x for x in globals().values() if isinstance(x, FunctionType)]
#[<function func at 0xb74d795c>]

#to return just name
print [x for x in globals().keys() if isinstance(globals()[x], FunctionType)]
#['func']

相关问题 更多 >