2013-06-18 64 views

回答

4

您可以使用inspect模塊:

import inspect 
import sys 


def test(): 
    pass 

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

打印:

['test'] 
+1

絕對迄今提出1的最好的方式 –

4

您可以使用globals()搶在文件的全局範圍內定義的一切,inspect篩選你所關心的對象。

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

使用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'] 
1
>>> def test(): 
...  pass 
... 
>>> [k for k, v in globals().items() if callable(v)] 
['test'] 
1

首先,我們將創建我們想找到test功能。

def test(): 
    pass 

接下來,我們將創建您想要的some_command_here函數。

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

最後,我們呼籲新的功能和過濾器轉換成tuple觀看。

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