V
V
Vadim2020-04-13 21:46:47
Python
Vadim, 2020-04-13 21:46:47

Why such an order of output to the console when using decorators?

trace code:

from functools import wraps

def makebold(original_funct): # decorator
    @wraps(original_funct) # optional, only require to keep track of the original function name thru wrapping
    def wrapped_4_bold(*args, **kwargs):
        print("Bold wrapped function name: {} received arguments: args = {} and kwargs = {}".format(original_funct.__name__, *args,
                                                                                                **kwargs))
        result = original_funct(*args, **kwargs)
        print("Bold wrapped function completed")
        return "<b>" + result + "</b>"

    return wrapped_4_bold


def makeitalic(original_funct): # decorator
    @wraps(original_funct) # optional, only require to keep track of the original function name thru wrapping
    def wrapped_4_italic(*args, **kwargs):
        print("Italic wrapped function name: {} received arguments:: args = {} and kwargs = {}".format(original_funct.__name__, *args,
                                                                                                   **kwargs))
        result = original_funct(*args, **kwargs)
        print("Italic wrapped function completed")
        return "<i>" + result + "</i>"

    return wrapped_4_italic

@makebold #executed second
@makeitalic # executed first
def hello_function(stext, small_letters=True):
    if small_letters:
        return stext.lower()
    else:
        return stext.upper()

print(hello_function("давайте попробуем", False))

prints to the console:
Bold wrapped function name: hello_function received arguments: args = let's try and kwargs = False
Italic wrapped function name: hello_function received arguments:: args = let's try and kwargs = False
Italic wrapped function completed
Bold wrapped function completed
LET'S TRY

Question why it starts to print in this order - as if the Bold wrapper started first, then it was intercepted by Italic and finished again by Bold...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Krostelev, 2020-04-14
@twistfire92

Let's represent the makebold decorator with curly braces { }
And the makeitalic decorator with square brackets [ ]
The opening bracket is the code before the decorated function is called, the closing bracket is the code after the decorated function is executed.
Let the function you decorate be an ellipsis ...
Then the flow of your program can be described as follows: { [ ... ] }
Now read this from left to right.

D
Dr. Bacon, 2020-04-13
@bacon

makebold(makeitalic(hello_function))That's clearer?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question