+ 2

Question about return statement in decorator function

Hello world! I've solved "Decorators" exercise where you need to code to make the text uppercase, but when I compared my code with Sololearn solution, there was only one difference at line #4 where I used "return text.upper()" instead of "return func(text).upper()" as suggested by SL solution. Anyway, the code passed tests, but I still wonder if the correct way was SL solution and why. Greatly appreciate for any help. text = input() def uppercase_decorator(func): ····def wrapper(text): ········return text.upper() # <-- HERE ····return wrapper @uppercase_decorator def display_text(text): ····return(text) print(display_text(text))

23rd Nov 2022, 11:08 PM
Alexander Davydov
Alexander Davydov - avatar
3 odpowiedzi
+ 7
The point of a decorator is to combine two functions, adding some extra behavior to an existing function. The concept is similar to function composition (function chaining), but implemented differently. With a function chain, you run the first function f on the input data, then take the result and run it on the second function. So it looks like: g(f(x)) But the decorator pattern changes the behavior of the original function itself. The decorator takes in another function, and returns a different function, but lets the input data flow through the whole thing. So we might express it like: g(f)(x) In your implementation you ignored this pattern and totally circumvented the inner function, so you only implemented a decorator shell that doesn't execute the decorated function, just returns the effect on the original argument. Coincidently, the display_text in the sample task doesn't do anything to its argument... so the result is not noticable. What you did is like: g(x) You are meant to execute func inside the wrapper, that's how both function behaviors can be realized.
24th Nov 2022, 2:49 AM
Tibor Santa
Tibor Santa - avatar
+ 6
I also solved this task. If we get direct access to the "text" argument, then it is silly to call an additional function. P. S: "And in general, I believe that it is not in vain that the SoloLearn hides test data from everyone, it allows users to show their individuality."
23rd Nov 2022, 11:43 PM
Solo
Solo - avatar
+ 3
Tibor Santa , I completely agree with you, this is another omission of SoloLearn. I once wrote code that more clearly demonstrates the capabilities of the decorator: https://code.sololearn.com/cpAJapSWADmf/?ref=app
24th Nov 2022, 11:59 AM
Solo
Solo - avatar