How to change function return using decorator?

I want to create a decorator to change the return value of a function as follows: How to do this, as shown 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} 
+11
source share
2 answers

Ok ... 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 
+32
source

I will try to be pretty general here, as this is probably an example of a toy, and you might need something parameterized:

 from collections import MutableMapping def map_set(k, v): def wrapper(func): def wrapped(*args, **kwds): result = func(*args, **kwds) if isinstance(result, MutableMapping): result[k] = v return result return wrapped return wrapper @map_set('c', 3) def foo(r=None): if r is None: return {'a':1, 'b':2} else: return r >>> foo() {'a': 1, 'c': 3, 'b': 2} >>> foo('bar') 'bar' 
+13
source

Source: https://habr.com/ru/post/895954/


All Articles