Decorators as classes

4099 views class
-4

Trying to rewrite a decorator as a Class isn't working as expected. My actual decorator is:

def check(callback):
    def decorator(function):
        def wrapper(*args, **kwargs):
            result = function(*args, **kwargs)
            cb_result = callback()
            return result 
        return wrapper
    return decorator

My approach to class format is

class Check(object):
    def __init__(self, *args, **kwargs):
        self._args = args
        self._kwargs = kwargs

    def __call__(self, *call_args, **call_kwargs):
        function = call_args[0]
        return self.__param__call__(function)

    def __param__call__(self, function):
        def wrapper(*args, **kwargs):
            result = function(*args, **kwargs)
            cb_result = callback()
            return result 
        return wrapper

I expect to use the decorator as in:

@Check(callback=a_function_callback)
def my_function():
    ...

What is my mistake while rewriting it as a class, I'm also always trying to keep backwards compatibility (aka Python 2.7 compliance).

answered question

1 Answer

3

You should accept callback as a parameter in your Check class' __init__ method, so that your wrapper function can actually reference it as a callback function:

class Check(object):
    def __init__(self, callback):
        self.callback = callback

    def __call__(self, func):
        return self.__param__call__(func)

    def __param__call__(self, func):
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            cb_result = self.callback()
            return result 
        return wrapper

posted this

Have an answer?

JD

Please login first before posting an answer.