如果我有這樣的腳本:獲取的本地定義的函數列表在python
import sys
def square(x):
return x*x
def cube(x):
return x**3
我怎樣才能返回程序中的['square', 'cube']
本地定義的所有功能列表,而不是那些進口。
當我嘗試dir()
時,會包含它們,但所有變量和其他導入的模塊也是如此。我不知道要將dir
放入本地執行的文件中。
如果我有這樣的腳本:獲取的本地定義的函數列表在python
import sys
def square(x):
return x*x
def cube(x):
return x**3
我怎樣才能返回程序中的['square', 'cube']
本地定義的所有功能列表,而不是那些進口。
當我嘗試dir()
時,會包含它們,但所有變量和其他導入的模塊也是如此。我不知道要將dir
放入本地執行的文件中。
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']
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建議)。
給出[( '立方體',<在0x0294AC70功能立方體>),( '加入',<功能加入在0x025A58B0>),( '正方形',<函數在0x028BBAB0平方>)]當從'進口os.path中加入'加 – BartoszKP
@ user2357112更新了答案 – alecxe
@Marcin:這個例子只出現排除進口功能,因爲內置函數不爲'inspect.isfunction'計數。儘管如此,新版本仍然有效。 – user2357112
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>)]
嘗試'當地人()',但我不知道如何有幫助,將是 – inspectorG4dget