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

在Python环境中查找所有定义的函数,python,function,Python,Function,是否有一种方法可以查找python环境中定义的所有函数 例如,如果我有 def test: pass 此处的某些命令将返回test您可以使用globals()获取文件全局范围中定义的所有内容,并使用检查过滤您关心的对象 [ f for f in globals().values() if inspect.isfunction(f) ] 使用globals()和类型。FunctionType >>> from types import FunctionType >

是否有一种方法可以查找python环境中定义的所有函数

例如,如果我有

def test:
   pass
此处的某些命令将返回
test

您可以使用
globals()
获取文件全局范围中定义的所有内容,并使用
检查
过滤您关心的对象

[ f for f in globals().values() if inspect.isfunction(f) ]
使用
globals()
类型。FunctionType

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

从类型导入函数类型
def func():传递
在globals()中打印[x代表x.values(),如果是instance(x,FunctionType)]
#[]
#仅返回名称
在globals().keys()中打印[x代表x如果是instance(globals()[x],FunctionType)]
#['func']
您可以使用模块:

印刷品:

['test']

首先,我们将创建要查找的
test
函数

def test():
    pass
接下来,我们将在此处创建所需的
some\u命令
函数

def some_command_here():
    return filter(callable, globals().values())
最后,我们调用新函数并将过滤器转换为一个
元组
,以供查看

tuple(some_command_here())
注意:这将搜索当前全局命名空间并返回任何可调用的内容(不仅仅是函数)


示例:

>>> def test():
    pass

>>> def some_command_here():
    return filter(callable, globals().values())

>>> tuple(some_command_here())
(<function test at 0x02F78660>,
 <class '_frozen_importlib.BuiltinImporter'>,
 <function some_command_here at 0x02FAFDF8>)
>>> 
>>def test():
通过
>>>在此处定义一些命令()
返回筛选器(可调用,globals().values())
>>>元组(此处的某些命令)
(,
,
)
>>> 

绝对是迄今为止提出的最好的方法+1
def some_command_here():
    return filter(callable, globals().values())
tuple(some_command_here())
>>> def test():
    pass

>>> def some_command_here():
    return filter(callable, globals().values())

>>> tuple(some_command_here())
(<function test at 0x02F78660>,
 <class '_frozen_importlib.BuiltinImporter'>,
 <function some_command_here at 0x02FAFDF8>)
>>>