2

I am trying to chaining two decorators . but some how end up running only one. can some one suggest me solution for that

def decorator_redis(func_name):
    def redis_decorator(func):
        @wraps(func)
        def redis_wrapper(*args):
            redis_utilty = RedisUtilties()
            entity_id = args[0]
            return 'hello' + entity_id
        return redis_wrapper
    return redis_decorator

def decorator_ES(func_name):
    def ES_decorator(func):
        @wraps(func)
        def ES_wrapper(*args):
            return args[0]+ '!'
        return ES_wrapper
    return ES_decorator

@decorator_redis('find')
@decorator_ES('find')
def fetch_entity(name):
    return

print(fetch_entity('John'))

I need to print hello John!. But able to print out hello John or John ! depending on which decorator I used individually.

Sergey Vasilyev
  • 3,919
  • 3
  • 26
  • 37

1 Answers1

0

You should call the decorated function in the decorator's wrapper (each of them):

def decorator_ES(func_name):
    def ES_decorator(func):
        @wraps(func)
        def ES_wrapper(*args):
            return func(args[0]+ '!')  # <-- HERE
        return ES_wrapper
    return ES_decorator

Same for another decorator.

Otherwise, you effectively replace the function with the latest (topmost) wrapper. So, when you call it, it never gets to the bottom decorator or to the function itself.

Sergey Vasilyev
  • 3,919
  • 3
  • 26
  • 37