decorating functions with generic signatures (not for the faint of heart)

Michele Simionato michele.simionato at gmail.com
Fri Apr 8 07:59:33 EDT 2005


Yes, this is essentially the same idea. You compile the codestring to
bytecode,
whereas I just evalue the codestring to a lambda function. We are
essentially implementing a runtime macro by hand. I wonder if there is
any alternative
approach to get the same result, without manipulation of the source
code.
BTW, I have fixed another small bug in my original code. 'decorator'
should read

import inspect

def decorate(func, caller):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    argdefs = defaults or ()
    argcount = func.func_code.co_argcount
    varnames = args + (varargs or []) + (varkw or [])
    signature = ", ".join(_signature_gen(varnames, len(argdefs),
argcount))
    variables = ", ".join(_signature_gen(varnames, len(argdefs),
argcount,
                                        rm_defaults=True))
    lambda_src = "lambda %s: call(func, %s)" % (signature, variables)
    print func.__name__, "->", lambda_src
    dec_func = eval(lambda_src, dict(func=func, call=caller,
arg=argdefs))
    dec_func.__name__ = func.__name__
    dec_func.__doc__ = func.__doc__
    dec_func.__dict__ = func.__dict__.copy()
    return dec_func




More information about the Python-list mailing list