Skip to content Skip to sidebar Skip to footer

How To Change A Function's Return Using A Decorator?

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

Solution 1:

Well.... you call the decorated function and change the return value:

defdec(func):
    defwrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        result['c'] = 3return result
    return wrapper

Solution 2:

I'll try to be fairly general here since this is probably a toy example, and you might need something parameterized:

from collections import MutableMapping

defmap_set(k, v):
    defwrapper(func):
        defwrapped(*args, **kwds):
            result = func(*args, **kwds)
            ifisinstance(result, MutableMapping):
                result[k] = v 
            return result
        return wrapped
    return wrapper

@map_set('c', 3)deffoo(r=None):
    if r isNone:
        return {'a':1, 'b':2}
    else:
        return r

>>> foo()
{'a': 1, 'c': 3, 'b': 2}

>>> foo('bar')
'bar'

Post a Comment for "How To Change A Function's Return Using A Decorator?"