Decorater inside a function? Is there a way?

George Sakkis gsakkis at rutgers.edu
Sun Apr 3 14:17:35 EDT 2005


>def define(func):
>    if not ENABLE_TYPECHECKING:
>        return lambda func: func
>    # else decorate func

A small correction: The argument of the decorator is not 'func' but the
parameter checks you want to enforce. A template for define would be:

def define(inputTypes, outputType):
    if not ENABLE_TYPECHECKING:
        return lambda func: func
    def decorate(func):
        def typecheckedFunc(*args,**kwds):
            ##### TYPECHECK *args, **kwds HERE #####
            r = func(*args,**kwds)
            ##### TYPECHECK r HERE #####
            return r
        return typecheckedFunc
    return decorate


Depending on how much flexibility you allow in inputTypes, filling in
the typechecking logic can be from easy to challenging. For example,
does typechecking have to be applied in all arguments or you allow
non-typechecked aruments ? Can it handle *varargs and **kwdargs in the
original function ? An orthogonal extension is to support 'templated
types' (ala C++), so that you can check if something is 'a dict with
string keys and lists of integers for values'. I would post my module
here or the cookbook but at 560 (commented) lines it's a bit long to
qualify for a recipe :-)

George




More information about the Python-list mailing list