Demi Dimitrova
Demi Dimitrova

Reputation: 369

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

Upvotes: 10

Views: 621

Answers (1)

mario_sunny
mario_sunny

Reputation: 1432

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

Upvotes: 14

Related Questions