首页 > 解决方案 > 降低函数字典的代码复杂性

问题描述

需要你的帮助。我有以下方法:

def edit_data(self, **kwargs: dict) -> bool:
        func_map = {
            'supID': self.po_xml.change_supplier_id,
            'uniID': self.po_xml.change_university_id,
            'creds': self.po_xml.change_sender_credentials,
            'billAdd': self.po_xml.change_bill_address,
            'shipAdd': self.po_xml.change_ship_address,
            'conAdd': self.po_xml.change_contact_address,
            'lineItems': self.po_xml.change_line_items,
            'ordNo': self.po_xml.change_order_number,
        }
        try:
            dict_only = ['billAdd', 'shipAdd', 'conAdd', ]
            for key, value in kwargs.items():
                # run the function for that key
                if key not in func_map.keys():
                    raise LookupError(f'Error in {key}, not a valid function')
                if type(value) == dict and \
                        key not in dict_only and \
                        not func_map[key](**value):
                    raise LookupError(
                        'Something went wrong, check your variables.')
                elif key in dict_only and \
                        not func_map[key](value):
                    raise LookupError(
                        'Something went wrong, check your variables.')
                elif type(value) in [str, list] and \
                        not func_map[key](value):
                    raise LookupError(
                        'Somethin went wrong, check your variable')
            return True
        except LookupError as ie:
            log.error(ie)
            return False

本质上edit_data接收几种类型的输入(即str、list、dict),如果都成功则返回True。如果更新失败,上面定义的所有函数都会返回 False,从而触发LookupError.

我知道有一种方法可以进一步降低其复杂性,但我不太熟悉如何。我应该知道一些functools魔法来帮助解决这个问题吗?

标签: pythonpython-3.xclass

解决方案


推荐阅读