Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a function's return using a decorator?

Tags:

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}
like image 994
libaoyin Avatar asked Aug 26 '11 08:08

libaoyin


People also ask

Can decorators return values?

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.

What is the return type of a decorator Python?

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.

Can decorator take argument?

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.

What is the correct syntax for using a decorator?

Decorators use a special syntax in JavaScript, whereby they are prefixed with an @ symbol and placed immediately before the code being decorated.


1 Answers

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
like image 98
Felix Kling Avatar answered Sep 29 '22 20:09

Felix Kling