Python Forum

Full Version: Decorators
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I was going through a tutorial and encountered this code. Can anybody please make me understand the control flow of this code? Like which line is executed first and what is being passed as argument. I apologize if it is silly but i am mid newbie.

I know that when control encounters @decorator_function, it treat it as the beneath function being passed as argument to the decorator function but then it means that
original_function=display
or
original_function=display(): print('display function ran') 
or what else.
And also when wrapper function is returned, than does that mean or can we say that display defination is replaced by wrapper function

@decorator_function
def display():
    wrapper_function
OR

@decorator_function
wrapper_function
Please explain...

def decorator_function(original_function):
    def wrapper_function():
        print('wrapper executed this before {}'.format(original_function.__name__))
        return original_function()
    return wrapper_function

@decorator_function
def display():
    print('display function ran')

#display()

if __name__ == '__main__':
    display()
Output:
wrapper executed this before display display function ran
I understand that the above python code and the below code both are same. But need to understand the proper control flow.
def decorator_function(original_function):
    def wrapper_function():
        print('wrapper executed this before {}'.format(original_function.__name__))
        return original_function()
    return wrapper_function

#@decorator_function
def display():
    print('display function ran')

#display()

if __name__ == '__main__':
    display()
    dd=decorator_function(display)
    dd()
The only thing to understand is that
@spam
def eggs():
    print('ham')
is equivalent to
def eggs():
    print('ham')
eggs = spam(eggs)
(Aug-11-2018, 10:00 PM)Gribouillis Wrote: [ -> ]The only thing to understand is that
@spam
def eggs():
    print('ham')
is equivalent to
def eggs():
    print('ham')
eggs = spam(eggs)

Okay thanks Sir. I get it .