I want create a decorator to change a function's return value like that, How to do that like below?:
def dec(func):
def wrapper():
#some code...
#change return value append 'c':3
return wrapper
@dec
def foo():
return {'a':1, 'b':2}
result = foo()
print result
{'a':1, 'b':2, 'c':3}
Return values from decorated functions don't get returned by default unless the decorator allows it. In this lesson, you'll see how to get return values out of decorated functions by making a small change to the decorator.
Decorators in Python are very powerful which modify the behavior of a function without modifying it permanently. It basically wraps another function and since both functions are callable, it returns a callable.
The decorator arguments are accessible to the inner decorator through a closure, exactly like how the wrapped() inner function can access f . And since closures extend to all the levels of inner functions, arg is also accessible from within wrapped() if necessary.
Decorators use a special syntax in JavaScript, whereby they are prefixed with an @ symbol and placed immediately before the code being decorated.
Well.... you call the decorated function and change the return value:
def dec(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
result['c'] = 3
return result
return wrapper
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With