Discuss / Python / return decorator1 if callable(argument) else decorator2

return decorator1 if callable(argument) else decorator2

Topic source
import functools

def log(argument):

    def decorator1(*args, **kw):
        print('begin call')
        ret = argument(*args, **kw)
        print('end call')
        return ret

    def decorator2(func):
           @functools.wraps(func)
        def wrapper(*args, **kw):
               print('begin call')
            ret = func(*args, **kw)
            print('end call')
            return ret
        return wrapper

    return decorator1 if callable(argument) else decorator2

@log
def f1():
    print('@log')

@log('execute')
def f2():
    print("@log('execute')")

  • 1

Reply