The problem of anonymity with decorators

Alex Martelli aleaxit at yahoo.com
Tue Feb 7 11:12:35 EST 2006


Franck Pommereau <pommereau at univ-paris12.fr> wrote:
   ...
>     import new
>     def rename (fun, name) :
>         return new.function(fun.func_code, {}, name)

You need to make a new code object too:

def int_result(fun) :
    def wrapped(*largs, **kwargs) :
        result = fun(*largs, **kwargs)
        if not isinstance(result, int) :
            raise TypeError, "should return int"
        return result
    w = wrapped.func_code
    c = new.code(w.co_argcount, w.co_nlocals, w.co_stacksize,
                 w.co_flags, w.co_code, w.co_consts, w.co_names,
                 w.co_varnames, w.co_filename, fun.func_name,
                 w.co_firstlineno, w.co_lnotab,
                 w.co_freevars, w.co_cellvars)
    return new.function(c, fun.func_globals, fun.func_name,
                        fun.func_defaults, wrapped.func_closure)

Of course, you should refactor these last three statement into a

def remix(wrapped, fun): ...
   """ return a function like 'wrapped' but w/name and defaults fm 'fun'
   """
   ...same 3 statements as above, from w = ... onwards...



Alex




More information about the Python-list mailing list