Wrapping pure function (not method)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • xxALxx
    New Member
    • Feb 2012
    • 1

    Wrapping pure function (not method)

    Is there any way to wrap function call in Python?
    I've tried the following:

    Code:
    def wrap(f, wrapper):
    
        def h(*args, **opts):  pass
        h.func_code = f.func_code
    
        def w(*args, **opts):
            wrapper(args, opts)
            return h(args, opts)
        
        f.func_code = w.func_code
        return w
    
    
    def test_f():
        print 'test_f()'
    
    def test_wrapper(*args):
        print 'test_wrapper()'
    
    wrap(test_f, test_wrapper)
    but it doesn't work since assignment "f.func_cod e = w.func_code" requires that code objects contain same sets of free vars (exactly, error message was "ValueError: test_f() requires a code object with 0 free vars, not 2" for call wrap(test_f, test_wrapper))
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    Code:
    wrap(test_f, test_wrapper)
    test_f and test_wrapper in the above code are strings, not functions(). You can use something like the following but it may not be what you are trying to do since we don't know what you are trying to do.
    Code:
    def wrap(f):
         print "f()", f()
     
    def test_f():
         print 'test_f() called'
    
    wrap(test_f)
    I would suggest using a dictionary and passing the dictionary
    Code:
    def wrap():
        print "wrap called"
     
    def test_f():
        print 'test_f() called'
    
    def run_it(input_dict, name_to_run):
        input_dict[name_to_run]()
    
    wrap_dict={"test_f":test_f, "wrap":wrap}
    run_it(wrap_dict, "wrap")

    Comment

    Working...