1

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
S.B
  • 13,077
  • 10
  • 22
  • 49
William
  • 3,724
  • 9
  • 43
  • 76
  • I'm going to take a side trip into philosophy here. In general, you shouldn't be using rounding during your calculations. With the possible exception of certain financial transactions, your computations should be done with full precision, and ONLY when you get to the point of presenting for human consumption should you do the rounding. – Tim Roberts Feb 23 '22 at 18:34
  • You need to go one level deeper and define a function that returns a decorator. – timgeb Feb 23 '22 at 18:34

1 Answers1

2

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
S.B
  • 13,077
  • 10
  • 22
  • 49