2

I've read several articles on closures and what not but im attempting to create a specific named function

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 return a modified string like so when i call _load_helpers i want to modify the existing list of strings to those functions im calling.

is this possible and am i making any sense because i am confused :(

battlemidget
  • 249
  • 1
  • 4
  • 15

1 Answers1

2

I think functools.wraps should do what you want:

from functools import wraps

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

>>> somefunc = _makefunc(list)
>>> somefunc()
[]
>>> somefunc.__name__
'list'
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306