-3

Hi can someone please help me in reducing the complexity of the below mentioned code as I am new to this I need it to reduce the amount of code and improve the code and to improve simplicity and reduce duplications in the overall coding any any help in this regard can be of great help and thanks in advance for your time and consideration in helping me in this regard.

class SynonymSerializer(serializers.ModelSerializer):
    class Meta:
        model = synonym
        fields = '__all__'

    
    def update(self, instance, validated_data):

        instance.insured_synonym = validated_data.get('insured_synonym', instance.insured_synonym)
        instance.obligor_borrower_counterparty_synonym = validated_data.get('obligor_borrower_counterparty_synonym',
                                                                            instance.obligor_borrower_counterparty_synonym)
        instance.guarantor_synonym = validated_data.get('guarantor_synonym', instance.guarantor_synonym)
        instance.credit_rating_synonym = validated_data.get('credit_rating_synonym', instance.credit_rating_synonym)
        instance.country_of_risk_synonym = validated_data.get('country_of_risk_synonym',
                                                              instance.country_of_risk_synonym)
        instance.tenor_synonym = validated_data.get('tenor_synonym', instance.tenor_synonym)
        instance.coverage_synonym = validated_data.get('coverage_synonym', instance.coverage_synonym)
        instance.insured_transaction_synonym = validated_data.get('insured_transaction_synonym',
                                                                  instance.insured_transaction_synonym)
        instance.any_third_parties_synonym = validated_data.get('any_third_parties_synonym',
                                                                instance.any_third_parties_synonym)
        instance.premium_rate_synonym = validated_data.get('premium_rate_synonym', instance.premium_rate_synonym)
        instance.margin_synonym = validated_data.get('margin_synonym', instance.margin_synonym)
        instance.utilization_expected_utilization_synonym = validated_data.get(
            'utilization_expected_utilization_synonym', instance.utilization_expected_utilization_synonym)
        instance.purpose_synonym = validated_data.get('purpose_synonym', instance.purpose_synonym)
        instance.retained_amount_synonym = validated_data.get('retained_amount_synonym',
                                                              instance.retained_amount_synonym)
        instance.insured_percentage_synonym = validated_data.get('insured_percentage_synonym',
                                                                 instance.insured_percentage_synonym)
        instance.payment_terms_synonym = validated_data.get('payment_terms_synonym', instance.payment_terms_synonym)
        instance.secured_security_synonym = validated_data.get('secured_security_synonym',
                                                               instance.secured_security_synonym)
        instance.waiting_period_synonym = validated_data.get('waiting_period_synonym', instance.waiting_period_synonym)
        instance.brokerage_synonym = validated_data.get('brokerage_synonym', instance.brokerage_synonym)
        instance.broker_synonym = validated_data.get('broker_synonym', instance.broker_synonym)
        instance.ipt_synonym = validated_data.get('ipt_synonym', instance.ipt_synonym)
        instance.enquiry_code_synonym = validated_data.get('enquiry_code_synonym', instance.enquiry_code_synonym)
        instance.law_synonym = validated_data.get('law_synonym', instance.law_synonym)
        instance.terms_of_repayment_synonym = validated_data.get('terms_of_repayment_synonym',
                                                                 instance.terms_of_repayment_synonym)
        instance.financials_limit_synonym = validated_data.get('financials_limit_synonym',
                                                               instance.financials_limit_synonym)

        fields_25_synonym_key = [
            'insured_synonym', 'obligor_borrower_counterparty_synonym', 'guarantor_synonym', 'credit_rating_synonym',
            'country_of_risk_synonym',
            'tenor_synonym', 'coverage_synonym', 'insured_transaction_synonym', 'any_third_parties_synonym',
            'premium_rate_synonym', 'margin_synonym',
            'utilization_expected_utilization_synonym', 'purpose_synonym', 'retained_amount_synonym',
            'insured_percentage_synonym', 'payment_terms_synonym', 'secured_security_synonym',
            'waiting_period_synonym', 'brokerage_synonym', 'broker_synonym', 'ipt_synonym', 'enquiry_code_synonym',
            'law_synonym', 'terms_of_repayment_synonym', 'financials_limit_synonym'
        ]

        dict_obj = temp_dict()

        # Logic to store data
        for index, key in enumerate(fields_25_synonym_key):
            dict_obj.add(key, validated_data.get(key))

        # path to where synonym excel sheet should be present

        path = "C:\\Users\\batman\\mycode\\dataingest\\data\\"

        # change directory to desired location , making sure we are at the correct location
        os.chdir(path)

        # code to delete existing excel sheet
        for file in os.listdir(path):
            print("file neme is :", file)

            # SynonymList.xlsx
            import pandas as pd
            if 'SynonymList.xlsx' in file:
                excel_path = path + file
                g = pd.read_excel(excel_path)
                excel_new_path = path + "\\SynonymList_old.xlsx"
                g.to_excel(excel_new_path, index=False)
                os.remove(file)
        # code to create new excel sheet on synonym table update

        try:

            tuple_list = []
            # create Workbook object
            wb = Workbook()
            # select demo.xlsx
            sheet = wb.active

            initial = dict_obj
            tuple_list.append(("s_field", "s_synonym"))
            for key, value in initial.items():
                dict_values = initial[key]
                values_list = dict_values.split(",")
                for n in range(len(values_list)):
                    if key == "insured_synonym":
                        tuple_list.append(("insured", values_list[n].lower().strip()))
                    if key == "obligor_borrower_counterparty_synonym":
                        tuple_list.append(("obligor", values_list[n].lower().strip()))
                    if key == "guarantor_synonym":
                        tuple_list.append(("guarantor", values_list[n].lower().strip()))
                    if key == "credit_rating_synonym":
                        tuple_list.append(("credit rating", values_list[n].lower().strip()))
                    if key == "country_of_risk_synonym":
                        tuple_list.append(("obligor country", values_list[n].lower().strip()))
                    if key == "tenor_synonym":
                        tuple_list.append(("tenor", values_list[n].lower().strip()))
                    if key == "coverage_synonym":
                        tuple_list.append(("coverage", values_list[n].lower().strip()))
                    if key == "insured_transaction_synonym":
                        tuple_list.append(("insured transaction", values_list[n].lower().strip()))
                    if key == "any_third_parties_synonym":
                        tuple_list.append(("third parties", values_list[n].lower().strip()))
                    if key == "premium_rate_synonym":
                        tuple_list.append(("premium rate", values_list[n].lower().strip()))
                    if key == "margin_synonym":
                        tuple_list.append(("margin", values_list[n].lower().strip()))
                    if key == "utilization_expected_utilization_synonym":
                        tuple_list.append(("utilization", values_list[n].lower().strip()))
                    if key == "purpose_synonym":
                        tuple_list.append(("purpose", values_list[n].lower().strip()))
                    if key == "retained_amount_synonym":
                        tuple_list.append(("retained amount", values_list[n].lower().strip()))
                    if key == "insured_percentage_synonym":
                        tuple_list.append(("insured %", values_list[n].lower().strip()))
                    if key == "payment_terms_synonym":
                        tuple_list.append(("payment terms", values_list[n].lower().strip()))
                    if key == "secured_security_synonym":
                        tuple_list.append(("secured", values_list[n].lower().strip()))
                    if key == "waiting_period_synonym":
                        tuple_list.append(("waiting period", values_list[n].lower().strip()))
                    if key == "brokerage_synonym":
                        tuple_list.append(("brokerage", values_list[n].lower().strip()))
                    if key == "broker_synonym":
                        tuple_list.append(("broker", values_list[n].lower().strip()))
                    if key == "ipt_synonym":
                        tuple_list.append(("ipt", values_list[n].lower().strip()))
                    if key == "enquiry_code_synonym":
                        tuple_list.append(("enquiry code", values_list[n].lower().strip()))
                    if key == "law_synonym":
                        tuple_list.append(("law", values_list[n].lower().strip()))
                    if key == "terms_of_repayment_synonym":
                        tuple_list.append(("terms of repayment", values_list[n].lower().strip()))
                    if key == "financials_limit_synonym":
                        tuple_list.append(("limit", values_list[n].lower().strip()))
                    # if key == "ef_created":
                    #     tuple_list.append(("created at", values_list[n].lower().strip()))
                    # if key == "ef_last_updated":
                    #     tuple_list.append(("last update", values_list[n].lower().strip()))
            # append all rows
            for row in tuple_list:
                sheet.append(row)
            # save file
            wb.save(path + "\\SynonymList.xlsx")
            print("File saved at..", path)
        except Exception as e:
            print("Not able to create synonym excel sheet", e)

        instance.save()
        return instance
Murthy P
  • 15
  • 1
  • 3
  • 8

1 Answers1

1
  • Did not check all related lines of code but perhaps you can use getattr and setattr to reduce dulpication of information
properties = [
    'insured_synonym',
    'obligor_borrower_counterparty_synonym',
    'guarantor_synonym',
    'credit_rating_synonym',
    # and so on
]
for prop in properties:
    setattr(instance, prop, validated_data.get(prop, getattr(instance, prop)))
  • You never use index so you do not need enumerate
for key in fields_25_synonym_key:
    dict_obj.add(key, validated_data.get(key))
  • A lookup table to get rid of all those ifs
  • You can iterate over the items in a list directly so you do not need n, range, and len
labels = {
    "insured_synonym":                          "insured",
    "obligor_borrower_counterparty_synonym":    "obligor",
    "guarantor_synonym":                        "guarantor",
    "credit_rating_synonym":                    "credit rating",
    # and so on
}
for val in values_list:
    tuple_list.append((labels[key], val.lower().strip()))
  • Thank you Justin I will make the changes and run – Murthy P May 26 '21 at 19:24
  • There are most likely other places where you can do better but I got lazy and gave up. Oh and perhaps next time you may want to post this in https://codereview.stackexchange.com/ –  May 26 '21 at 19:26