2011-11-17 4 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

관련 문제