获取python中本地定义函数的列表

ber*_*roe 6 python function

如果我有这样的脚本:

import sys

def square(x):
    return x*x

def cube(x):
    return x**3
Run Code Online (Sandbox Code Playgroud)

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

我尝试时将它们包括在内,dir()但所有变量和其他导入的模块也是如此.我不知道该怎么做dir才能引用本地执行的文件.

Vik*_*kez 12

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

所以带有内容的文件:

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
Run Code Online (Sandbox Code Playgroud)

打印:

['square', 'cube']
Run Code Online (Sandbox Code Playgroud)

本地范围也有效:

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()
Run Code Online (Sandbox Code Playgroud)

仅打印出来:

['cube']
Run Code Online (Sandbox Code Playgroud)

  • 即使作为one_liner:`functions = [locals()中的(名称,事物)名称.项目()如果可调用(事物)) (5认同)

ale*_*cxe 7

使用检查模块:

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)
Run Code Online (Sandbox Code Playgroud)

例:

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)]
Run Code Online (Sandbox Code Playgroud)

打印:

['cube', 'is_local', 'square']
Run Code Online (Sandbox Code Playgroud)

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

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


Mar*_*rcM 5

使用Python 3.9.7,当尝试获得最多支持的答案时:

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

我收到以下错误:回溯(最近一次调用最后一次):文件“C:\ Users \ Name \ Path \ filename.py”,第X行,用于 键,locals().items()中的值:RuntimeError:字典迭代期间改变大小

因为答案:locals() 打印这个:

'test_01': <function test_01 at 0x00000285B0F2F5E0>
'test_02': <function test_02 at 0x00000285B0F2FA60>
Run Code Online (Sandbox Code Playgroud)

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

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

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