2

That code is exactly the same, so I want to refactor it in a simple way to reduce the number of lines. One thing which is different is min/max function execution. Is it available pointer to function in python to call min/max as a pointer to function like in C?

def calculate_min(a, b, c, d, e, f):
    try:
        v = a[e][f]
        b[d] = v if np.isnan(b[d]) else min(b[d], v)    #min()
    except KeyError as exc:
        logger.error("keyerror")

def calculate_max(a, b, c, d, e, f):
    try:
        v = a[e][f]
        b[d] = v if np.isnan(b[d]) else max(b[d], v)    #max()
    except KeyError as exc:
        logger.error("keyerror")
selvakumar
  • 620
  • 1
  • 8
  • 30
  • 2
    Totally unrelated but you should use `logger.exception()` instead of `logger.error()` => this will add the full error message and traceback to the log, which is _very_ useful for debugging. – bruno desthuilliers Jun 29 '18 at 09:06

2 Answers2

8

An option to reduce duplication would be

def calculate_value(a, b, c, d, e, f, func=max):
    try:
        v = a[e][f]
        b[d] = v if np.isnan(b[d]) else func(b[d], v)    #min() or max()
    except KeyError as exc:
        logger.error("keyerror")

Depending on the func parameter, you can pass along the min or max function and get the wanted result. Here is an example on how to pass on functions as arguments : How do I pass a method as a parameter in Python

Chuk Ultima
  • 987
  • 1
  • 11
  • 21
1

Well you could just make one function and add an argument that specifies which function to call. For example:

def calculate_func(a, b, c, d, e, f, func):
    try:
        v = a[e][f]
        b[d] = v if np.isnan(b[d]) else func(b[d], v)    #replaced min/max by func
    except KeyError as exc:
        logger.error("keyerror")

calculate_min = lambda a, b, c, d, e, f: calculate_func(a, b, c, d, e, f, min)
Zuma
  • 806
  • 1
  • 7
  • 10