2013-08-26 80 views
4

如果我有這樣的腳本:獲取的本地定義的函數列表在python

import sys 

def square(x): 
    return x*x 

def cube(x): 
    return x**3 

我怎樣才能返回程序中的['square', 'cube']本地定義的所有功能列表,而不是那些進口。

當我嘗試dir()時,會包含它們,但所有變量和其他導入的模塊也是如此。我不知道要將dir放入本地執行的文件中。

+0

嘗試'當地人()',但我不知道如何有幫助,將是 – inspectorG4dget

回答

5
l = [] 
for key, value in locals().items(): 
    if callable(value) and value.__module__ == __name__: 
     l.append(key) 
print l 

所以一個與內容的文件:

from os.path import join 

def square(x): 
    return x*x 

def cube(x): 
    return x**3 

l = [] 
for key, value in locals().items(): 
    if callable(value) and value.__module__ == __name__: 
     l.append(key) 
print l 

打印:

['square', 'cube'] 

本地範圍也行:

def square(x): 
    return x*x 

def encapsulated(): 
    from os.path import join 

    def cube(x): 
     return x**3 

    l = [] 
    for key, value in locals().items(): 
     if callable(value) and value.__module__ == __name__: 
      l.append(key) 
    print l 

encapsulated() 

打印出只:

['cube'] 
+2

即使作爲一個的one_liner:'功能= [名稱(姓名,東西)in local()。items()if callable(thing))' – 9000

+0

@ user2357112更新了答案。 –

+0

我喜歡這個解決方案,因爲它不依賴於導入其他模塊,但是當我在我的實際腳本中嘗試這個時,它包含''value''作爲'l'中的條目,原因是我無法弄清楚...「價值」不會出現在腳本的其他地方。 – beroe

7

inspect使用模塊:

def is_function_local(object): 
    return isinstance(object, types.FunctionType) and object.__module__ == __name__ 

import sys 
print inspect.getmembers(sys.modules[__name__], predicate=is_function_local) 

實施例:

import inspect 
import types 
from os.path import join 

def square(x): 
    return x*x 

def cube(x): 
    return x**3 

def is_local(object): 
    return isinstance(object, types.FunctionType) and object.__module__ == __name__ 

import sys 
print [name for name, value in inspect.getmembers(sys.modules[__name__], predicate=is_local)] 

打印:

['cube', 'is_local', 'square'] 

參見:沒有join函數從os.path導入。

is_local在這裏,因爲它是一個功能是當前模塊。您可以將它移動到另一個模塊或手動排除它,或者定義lambda(作爲@BartoszKP建議)。

+0

給出[( '立方體',<在0x0294AC70功能立方體>),( '加入',<功能加入在0x025A58B0>),( '正方形',<函數在0x028BBAB0平方>)]當從'進口os.path中加入'加 – BartoszKP

+0

@ user2357112更新了答案 – alecxe

+0

@Marcin:這個例子只出現排除進口功能,因爲內置函數不爲'inspect.isfunction'計數。儘管如此,新版本仍然有效。 – user2357112

1
import sys 
import inspect 
from os.path import join 

def square(x): 
    return x*x 

def cube(x): 
    return x**3 

print inspect.getmembers(sys.modules[__name__], \ 
     predicate = lambda f: inspect.isfunction(f) and f.__module__ == __name__) 

打印:

[('cube', <function cube at 0x027BAC70>), ('square', <function square at 0x0272BAB0>)]