Discuss / Python / My Solution

My Solution

Topic source
def log_it(func_outer=None, fmt_str='[log it] call: {}'):

    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            print(fmt_str.format(func.__name__))
            return func(*args, **kwargs)
        return wrapper

    # support with/without decorator parameters.
    # Or isinstance(func_outer, types.FunctionType)
    if callable(func_outer):
        return decorator(func_outer)
    else:
        return decorator

@log_it
def yesterday():
    print("Hello Yesterday!")

@log_it(fmt_str='[log tomorrow] {}')
def tomorrow():
    print("Hello Tomorrow!")

  • 1

Reply