10

如果我有这样的脚本:

import sys

def square(x):
    return x*x

def cube(x):
    return x**3

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

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

4

4 回答 4

15
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']
于 2013-08-26T19:28:36.493 回答
9

使用检查模块:

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

请参阅:没有joinos.path.

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

于 2013-08-26T19:31:49.577 回答
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>)]

于 2013-08-26T19:36:40.407 回答
1

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

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

我收到以下错误: Traceback(最近一次调用最后一次):文件“C:\Users\Name\Path\filename.py”,第 X 行,在 for 键中,在 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)
于 2022-01-11T19:07:11.910 回答