2017 m. spalio 21 d., šeštadienis

python decorators

1. Simple decorator:

def decorator_function(passed_method):
    def returns_method():
        print("Decorating function: {}".format(passed_method.__name__))
        return passed_method()

    return returns_method


def speak():
    print("01101")


speak = decorator_function(speak)
speak()


Is same as:

def decorator_function(passed_method):
    def returns_method():
        print("Decorating function: {}".format(passed_method.__name__))
        return passed_method()

    return returns_method


@decorator_function
def speak():
    print("01101")

speak()


Output:
Decorating function: speak 
01101

1.2 Decoration with arguments:

def decorator_function(passed_method):
    def returns_method(*args, **kwargs):
        print("Decorating function: {}".format(passed_method.__name__))
        return passed_method(*args, **kwargs)

    return returns_method


@decorator_function
def speak(word):
    print(word)


@decorator_function
def say(argument):
    print(argument)


speak("Hello")
say("World is round")

Output:
Hello
Decorating function: say
World is round

2. Example: get function time decorator:

def function_time(passed_method):
    import time

    def returns_method(*args, **kwargs):
        t1 = time.time()
        result = passed_method(*args, **kwargs)
        time_span = time.time() - t1
        print("Function: {}, Time: {}".format(passed_method.__name__, time_span))

        return result

    return returns_method


@function_time
def process():
    return [x for x in range(10000)]


process()
Output:
Function: process, Time: 0.0006840229034423828