获取python中本地定义函数的列表
如果我有这样一个脚本:获取python中本地定义函数的列表,python,function,Python,Function,如果我有这样一个脚本: 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(va
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']
使用模块:
例如:
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']
请参阅:从os.path
导入的无join
函数
是本地的,因为它是当前模块的一个函数。您可以将其移动到另一个模块或手动将其排除,或者定义一个lambda
(如@BartoszKP所建议的)
印刷品:
['square', 'cube']
[('cube',),('square',)]
试试locals()
,但我不确定这对一行有多大帮助:函数=[name for(name,thing)in locals()。items()如果可以调用(thing))
@user2357112更新了答案。我喜欢这个解决方案,因为它不依赖于导入其他模块,但当我在实际脚本中尝试此操作时,它将'value'
作为l
中的一个条目,原因是我无法理解。。。“值”不会出现在脚本的其他地方。@beroe您是否要重复两次?1。如果我在程序中有alecxe的答案和这个答案,并且它从他的作业中打印“值”,那么我猜它正在工作,但是受到对inspect()
的其他调用的影响?2@9000的一行代码也显示了我导入的函数,可能是因为它省略了val.。\uuuuu module\uuuu==\uuuuuuuu name\uuuuu
(右括号中还有一个拼写错误)。这是有效的:functions=[name for(name,thing)in locals().items()if(callable(thing)and thing.\uuuu模块\uuuuuuuuu==\uuuu name\uuuuu)]
给出[('cube',),('join',),('square',]当从os.path导入连接时
added@Marcin:该示例仅排除导入的函数,因为内置函数不计入inspect.isfunction
。不过,新版本可以工作。我修改了is_local
以排除它自己,这很有效。谢谢<代码>返回isinstance(object,types.FunctionType)和object.\uuuuu模块\uuuuu==\uuuuuuu名称\uuuuu和object.\uuuuu名称\uuuuu!='是本地的吗?
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__)