动态创建具有特定名称的函数

时间:2011-11-17 00:12:18

标签: 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)

当我调用_load_helpers时,img会返回一个修改后的字符串,我希望将现有的字符串列表修改为我调用的那些函数。

这是可能的,我有任何意义,因为我很困惑:(

1 个答案:

答案 0 :(得分:2)

我认为functools.wraps应该做你想做的事:

from functools import wraps

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

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