
PYTHON — Returning Values from Decorated Functions in Python
The most profound technologies are those that disappear. They weave themselves into the fabric of everyday life until they are indistinguishable from it. — Mark Weiser
Insights in this article were refined using prompt engineering methods.

PYTHON — k-NN Data Fitting and Prediction in Python
Decorators in Python are a powerful and useful tool for modifying the behavior of functions. In this tutorial, we’ll focus on returning values from decorated functions. By default, return values from decorated functions are not returned unless the decorator specifically allows it. Let’s see how we can enable decorated functions to return values by making a small change to the decorator.
Consider the following example:
def do_twice(func):
def wrapper_do_twice(*args, **kwargs):
func(*args, **kwargs)
return func(*args, **kwargs)
return wrapper_do_twice
@do_twice
def return_greeting(name):
print(f"Creating greeting")
return f"Hello, {name}"
hi_adam = return_greeting("Adam")
print(hi_adam)In the above example, the return_greeting function is decorated with @do_twice. The decorator do_twice allows the decorated function to return a value. When the return_greeting function is called with the argument "Adam", it prints "Creating greeting" and returns the greeting message. The assigned value hi_adam will then contain the returned greeting message.
Before making any changes to the decorator, running the above code will result in the output:
Creating greeting
Creating greeting
NoneAs you can see, the None is printed after the greeting message, indicating that the return value was not handled properly by the decorator.
To enable the decorated function to return values, we need to ensure that the decorator returns what the decorated function returns. This can be achieved by modifying the do_twice decorator as follows:
def do_twice(func):
def wrapper_do_twice(*args, **kwargs):
result = func(*args, **kwargs)
print("This is printed after the previous return")
return result
return wrapper_do_twice
@do_twice
def return_greeting(name):
print(f"Creating greeting")
return f"Hello, {name}"
hi_adam = return_greeting("Adam")
print(hi_adam)With this modification, the output of the code will be:
Creating greeting
This is printed after the previous return
Creating greeting
This is printed after the previous return
Hello, AdamIn the modified decorator, the wrapper_do_twice function stores the return value of the decorated function in the result variable. It then prints a message and returns the stored result. As a result, the value returned by the decorated function is handled correctly.
The modified code now correctly returns the greeting message from the decorated function.
In summary, when working with decorators in Python, it’s important to ensure that the decorator allows decorated functions to return values by properly handling the return statements within the decorator.







