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

后端 未结 2 1765
野趣味
野趣味 2020-12-16 12:52

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...         


        
相关标签:
2条回答
  • 2020-12-16 13:11

    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
    
    0 讨论(0)
  • 2020-12-16 13:19

    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
    
    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'
    
    0 讨论(0)
提交回复
热议问题