decorator of function in py

decorator…

you may think it is used for an extend of an original function.

so you should call the original function in your decorator by your design

(although some rare case, like using a test function to replace the original function)

So, a decorator is a way to extend or modify the behavior of an existing function without modifying its source code.

From POE:

Yes, a decorator is a way to extend or modify the behavior of an existing function without modifying its source code.

When you apply a decorator to a function, the decorator creates a new function that wraps the original function with some additional behavior. The resulting wrapped function can then be called just like the original function, but with the added behavior provided by the decorator.

For example, consider the following decorator function that adds some behavior before and after the wrapped function is called:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before the function is called.")
        result = func(*args, **kwargs)
        print("After the function is called.")
        return result
    return wrapper

In this example, my_decorator is a function that takes another function func as an argument and returns a new function wrapper that wraps func with some additional behavior. The resulting wrapper function can be called just like func, but with the added behavior provided by my_decorator.

Using this decorator function, you can extend the behavior of any function by applying the decorator to the function using the @ syntax, like this:

@my_decorator
def my_function(x):
    return x * 2

In this example, the @my_decorator syntax applies the my_decorator decorator to the my_function function, so that when you call my_function(2), the wrapper function returned by my_decorator is called instead, which first prints “Before the function is called.”, then calls my_function(2), which returns 4. Finally, the wrapper function prints “After the function is called.” and returns 4.

So, a decorator is a way to extend or modify the behavior of an existing function without modifying its source code.