如何将Python普通函数add_transaction转换为lambda函数?
能否将该Python函数转换为lambda函数?
结论
不建议将这个函数转换为lambda函数,lambda的设计定位和原函数的逻辑不匹配,硬转只会写出难以维护的代码。
技术上的实现(不推荐)
如果非要用lambda实现相同逻辑,确实可以通过一些技巧把多步操作塞进一个表达式里,但代码会非常晦涩:
add_transaction = lambda list_of_items: ( all(item in item_dict or (raise ValueError("You cannot make a transaction containing items that are not present in the items dictionary because it means that the Store does not has those items available, please add the items to the items dictionary first"), False)[0] for item in list_of_items), transaction_data.append(list_of_items), list_of_items )[2]
这里用到的技巧:
- 用
all()结合生成器表达式遍历检查每个item,通过or后的元组操作触发异常(因为raise不是表达式,需要塞进元组里执行) - 用元组执行
transaction_data.append()(副作用操作),最后返回第三个元素list_of_items
为什么不推荐
- lambda是为简单的纯表达式逻辑设计的,原函数包含副作用(修改全局变量
transaction_data)、异常抛出、循环检查,完全超出了lambda的适用场景。 - 上述lambda代码可读性极差,其他开发者需要花大量时间拆解逻辑,后续调试和扩展都非常困难。
- 原有的
def函数结构清晰、逻辑明确,完全符合Python的代码风格规范,没有任何理由替换成lambda。
内容的提问来源于stack exchange,提问作者frank_99_
相关产品推荐
相关产品推荐

