Search code examples
pythonpython-3.xdecoratorpython-decorators

python decorator how to add parameters


I have a python decorator, it will round the return of function 2 decimals:

def round_decimal(func):
    def inner(*args, **kwargs):
        return round(func(*args, **kwargs),2)
    return inner

@round_decimal
def func(a,b,c):
    
    return a/b/c

func(1.33333,3.44444,4.555)

The output is:

0.08

My question is how can I make the round decimal a parameters:

Something like this:

def round_decimal(func,decimal):
    def inner(*args, **kwargs):
        return round(func(*args, **kwargs),decimal)
    return inner

@round_decimal(3)
def func(a,b,c):

    return a/b/c

func(1.33333,3.44444,4.555)

if the round decimal equals 3 the output should be:

0.085

Solution

  • You need a decorator factory, that is a function that returns the decorator:

    from functools import wraps
    
    
    def round_decimal(n):
        def decorator(fn):
            @wraps(fn)
            def inner(*args, **kwargs):
                return round(fn(*args, **kwargs), n)
    
            return inner
    
        return decorator
    
    
    @round_decimal(3)
    def func(a, b, c):
        return a / b / c
    
    
    print(func(1.33333, 3.44444, 4.555))
    

    output:

    0.085