2011-11-17 77 views
2

我就倒閉閱讀幾篇文章,而不是,但即時通訊試圖創建一個特定的命名功能是什麼動態創建函數具有特定名稱

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返回像這樣修改字符串時,我打電話_load_helpers我想要將現有的字符串列表修改爲即時調用的那些函數。

這是可能的,我在作出任何意義,因爲我很困惑:(

回答

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' 
+0

感謝一大堆! – battlemidget