Python3: 快速来一发装饰器

一直非常喜欢这个东西,简洁、明快~

from decorator import decorator
import time


@decorator
def time_counter(func, ignore: bool = False, *args, **kwargs):
    start = time.time()
    if ignore:
        result = False
    else:
        result = func(*args, **kwargs)
    end = time.time()
    delta = end - start
    print(f"The function runs {delta} seconds.")
    return result


@time_counter
def do_sleep(secondes):
    time.sleep(secondes)
    return True


@time_counter(ignore=True)
def do_nothing(secondes):
    time.sleep(secondes)
    return True


if do_sleep(4.5):
    print("Take a sleep :)")
if not do_nothing(4.5):
    print("Doing nothing :(")

$ python3 de_func.py
The function runs 4.505078077316284 seconds.
Take a sleep :)
The function runs 0.0 seconds.
Doing nothing :(