Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python decorator function execution

I have below decorator demonstration code. If I execute it without explicitly calling greet function, it is executing print statement inside decorator function and outputs Inside decorator.

I am unable to understand this behavior of decorator. How the time_decorator is called even if I didn't call greet function?

I am using Python 3.

def time_decorator(original_func):
    print('Inside decorator')
    def wrapper(*args, **kwargs):
        start = time.clock()
        result = original_func(*args, **kwargs)
        end = time.clock()
        print('{0} is executed in {1}'.format(original_func.__name__, end-start))
        return result
    return wrapper


@time_decorator
def greet(name):
    return 'Hello {0}'.format(name)
like image 321
thatisvivek Avatar asked Apr 05 '16 19:04

thatisvivek


1 Answers

Decorators are called at start time (when the python interpreter reads the code as the program starts), not at runtime (when the decorated function is actually called).

At runtime, it is the wrapped function wrapper which is called and which itself calls the decorated function and returns its result.

So this is totally normal that the print line gets executed.

If, i.e, you decorate 10 functions, you will see 10 times the print output. No need to even call the decorated functions for this to happen.

Move the print inside wrapper and this won't happen anymore.

Decorators as well as metaclasses are part of what is called meta-programming (modify / create code, from existing code). This is a really fascinating aspect of programming which takes time to understand but offers amazing possibilities.

like image 95
DevLounge Avatar answered Oct 24 '22 11:10

DevLounge