Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use functional programming to make a generic method in python?

I would like to improve the way this code is written. Right now I have six methods that are almost copy-paste, only one line is changing. How can I make a generic method and depending on the property of the data input to change the calculations? I was thinking to use functional programming to achieve that, but I am not sure how to do it properly.

The method is getting a dict object. Then this object is transformed into JSON. The mid variable is storing a JSON with midrate for currency from external API, it must be before the for loop otherwise the API will be called in every iteration and this slows down the process a lot! Then in the for loop, I iterate through the data from the input. The only difference between methods is the calculation before inserting it in the list. .append(mid_current - bankMSell)

def margin_to_exchange_rate_sell(data):
    j = data.to_JSON()
    list_p = []
    mid = midrate.get_midrate(j["fromCurrency"][0])
    for idx, val in enumerate(j['toCurrency']):
        try:
            mid_current = 1/get_key(mid, j['toCurrency'][idx])
            bankMSell = float(j['sellMargin'][idx])
            list_p.append(mid_current - bankMSell)
        except Exception as e:
            list_p.append(0)
            print(str(e))

    return list_p

Another one of the methods:

def margin_to_exchange_rate_buy(data):
    j = data.to_JSON()
    list_p = []
    mid = midrate.get_midrate(j["fromCurrency"][0])
    for idx, val in enumerate(j['toCurrency']):
        try:
            mid_current = 1/get_key(mid, j['toCurrency'][idx])
            bankMSell = float(j['sellMargin'][idx])
            list_p.append(mid_current + bankMSell)
        except Exception as e:
            list_p.append(0)
            print(str(e))

    return list_p
like image 437
Demi Dimitrova Avatar asked Nov 04 '19 12:11

Demi Dimitrova


People also ask

Can you use functional programming in Python?

Many programming languages support some degree of functional programming. In some languages, virtually all code follows the functional paradigm. Haskell is one such example. Python, by contrast, does support functional programming but contains features of other programming models as well.

What is pure function how do we utilize the function in Python?

A function is called pure function if it always returns the same result for same argument values and it has no side effects like modifying an argument (or global variable) or outputting something. The only result of calling a pure function is the return value. Examples of pure functions are strlen(), pow(), sqrt() etc.

What is NumPy functional programming?

NumPy: Functional programming routinesTakes an arbitrary Python function and returns a NumPy ufunc. numpy.frompyfunc(func, nin, nout) piecewise() Evaluate a piecewise-defined function.


1 Answers

Indeed, there is a way to reduce code here with lambdas:

def margin_to_exchange_rate_sell(data):
    return margin_to_exchange_rate(data, lambda m, b: m - b)


def margin_to_exchange_rate_buy(data):
    return margin_to_exchange_rate(data, lambda m, b: m + b)


def margin_to_exchange_rate(data, operation):
    j = data.to_JSON()
    list_p = []
    mid = midrate.get_midrate(j["fromCurrency"][0])
    for idx, val in enumerate(j['toCurrency']):
        try:
            mid_current = 1/get_key(mid, j['toCurrency'][idx])
            bankMSell = float(j['sellMargin'][idx])
            list_p.append(operation(mid_current, bankMSell))
        except Exception as e:
            list_p.append(0)
            print(str(e))

    return list_p
like image 137
mario_sunny Avatar answered Oct 19 '22 04:10

mario_sunny