【问题标题】:Getting a list of locally-defined functions in python在python中获取本地定义的函数列表
【发布时间】:2013-08-29 09:07:47
【问题描述】:

如果我有这样的脚本:

import sys

def square(x):
    return x*x

def cube(x):
    return x**3

如何返回程序 ['square', 'cube'] 中本地定义的所有函数的列表,而不是导入的函数。

当我尝试dir() 时,它们被包括在内,但所有变量和其他导入的模块也是如此。我不知道在dir 中放入什么来引用本地执行的文件。

【问题讨论】:

  • 试试locals(),但我不确定这会有多大帮助

标签: python function


【解决方案1】:
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']

【讨论】:

  • 即使是 one_liner:functions = [name for (name, thing) in locals().items() if callable(thing])
  • @user2357112 更新了答案。
  • 我喜欢这个解决方案,因为它不依赖于导入其他模块,但是当我在我的实际脚本中尝试这个时,它包含 'value' 作为 l 中的一个条目,出于某种原因,我无法弄清楚...“值”没有出现在脚本的其他地方。
  • @beroe 你可能会这样做两次吗?
  • 1. 如果我在程序中得到了 alecxe 的答案以及这个答案,并且它从他的作业中打印出“价值”,所以我猜它正在工作但受到影响通过其他呼叫inspect()2@9000 的单行也显示了我导入的函数,可能是因为它省略了val.__module__ == __name__(你的右括号也有错字)。这有效:functions = [name for (name, thing) in locals().items() if (callable(thing) and thing.__module__ == __name__)]
【解决方案2】:

使用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']

请参阅:没有从 os.path 导入的 join 函数。

is_local 在这里,因为它是当前模块的函数。您可以将其移动到另一个模块或手动排除它,或者改为定义lambda(如@BartoszKP 建议的那样)。

【讨论】:

  • 给出 [('cube', ), ('join', ), ('square', )] from os.path import join 已添加
  • @Marcin:该示例似乎只排除了导入的函数,因为内置函数不计入inspect.isfunction。不过,新版本有效。
  • 我修改了is_local 以排除自身,这很有效。谢谢。 return isinstance(object, types.FunctionType) and object.__module__ == __name__ and object.__name__ !='is_local'
【解决方案3】:
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>)]

【讨论】:

    【解决方案4】:

    使用 Python 3.9.7, 尝试最受好评的答案时:

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

    我收到以下错误: 回溯(最近一次通话最后): 文件“C:\Users\Name\Path\filename.py”,第 X 行,在 对于 key, value in locals().items(): RuntimeError:字典在迭代期间改变了大小

    因为答案:locals() 会打印:

    'test_01': <function test_01 at 0x00000285B0F2F5E0>
    'test_02': <function test_02 at 0x00000285B0F2FA60>
    

    我只是检查我们是否在字典中得到字符串:“function”。

    我使用以下代码来实现我的需求。希望这可能会有所帮助。

    l = []
    copy_dict = dict(locals())
    for key, value in copy_dict.items():
        if "function" in str(value):
            l.append(key)
    print(l)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多