动态创建具有特定nam的函数

2024-04-20 09:43:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我读过几篇关于闭包和什么的文章,但是我试图创建一个特定的命名函数

from app.conf import html_helpers

# html_helpers = ['img','js','meta']

def _makefunc(val):
    def result(): # Make this name of function?
        return val()
    return result

def _load_func_from_module(module_list):
    for module in module_list:
        m = __import__("app.system.contrib.html.%s" % (module,), fromlist="*")
        for attr in [a for a in dir(m) if '_' not in a]:
            if attr in html_helpers and hasattr(m, attr):
                idx = html_helpers.index(attr)
                html_helpers[idx] = _makefunc(getattr(m,attr))

def _load_helpers():
    """ defines what helper methods to expose to all templates """
    m = __import__("app.system.contrib.html", fromlist=['elements','textfilter'])
    modules = list()
    for attr in [a for a in dir(m) if '_' not in a]:
        print attr
        modules.append(attr)
    return _load_func_from_module(modules)

img返回一个修改过的字符串,比如当我调用“加载”helpers时,我想将现有的字符串列表修改为im调用的函数。在

这有可能吗?我是否因为困惑而有任何意义


Tags: infromimportmodulesappforreturnif
1条回答
网友
1楼 · 发布于 2024-04-20 09:43:08

我认为^{}应该做你想做的:

from functools import wraps

def _makefunc(val):
    @wraps(val)
    def result():
        return val()
    return result

>>> somefunc = _makefunc(list)
>>> somefunc()
[]
>>> somefunc.__name__
'list'

相关问题 更多 >