python - 降低函数字典的代码复杂性
问题描述
需要你的帮助。我有以下方法:
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
魔法来帮助解决这个问题吗?
解决方案
推荐阅读
- c# - 在解决方案资源管理器中更改项目文件夹后命名空间未更新
- android - Android RecyclerView 加载时崩溃
- python - 如何使用 python pandas 获取列中缺失的日期
- sql - 从字符串 T-SQL 中删除日期名称
- vitess - Vitess 表等价配置
- c# - 从 C# 列表显示简单的 Google 图表
- arrays - 从 Ruby 中的哈希数组中收集唯一元素
- jenkins - Jenkins - 在 groovy 中为每个构建禁用插件
- node.js - 在 curl 和 axios 中接收不同的 id
- c# - 我想根据用户控件 c# 更改标签颜色