gpt4 book ai didi

python - 试试……除了……除了……: how to avoid repeating code

转载 作者:太空宇宙 更新时间:2023-11-03 12:25:59 28 4
gpt4 key购买 nike

  • 我想避免在多个地方写入 error Count += 1
  • 我正在寻找比
  • 更好的方法
    success = False    try:        ...    else:        success = True    finally:        if success:            storage.store.commit()        else:            storage.store.rollback()
  • I'm trying to avoid store.rollback() in every except clause.

Any idea on how to do this?

count = 0
successCount = 0
errorCount = 0
for row in rows:
success = False
count += 1
newOrder = storage.RepeatedOrder()
storage.store.add(newOrder)
try:
try:
newOrder.customer = customers[row.customer_id]
except KeyError:
raise CustomerNotFoundError, (row.customer_id,)
newOrder.nextDate = dates[row.weekday]
_fillOrder(newOrder, row.id)
except CustomerNotFoundError as e:
errorCount += 1
print u"Error: Customer not found. order_id: {0}, customer_id: {1}".format(row.id, e.id)
except ProductNotFoundError as e:
errorCount += 1
print u"Error: Product not found. order_id: {0}, product_id: {1}".format(row.id, e.id)
else:
success = True
successCount += 1
finally:
if success:
storage.store.commit()
else:
storage.store.rollback()
print u"{0} of {1} repeated orders imported. {2} error(s).".format(successCount, count, errorCount)

最佳答案

这看起来像是 Python 的新 with 语句的可能应用。无论代码块产生什么结果,它都允许安全地展开操作和释放资源。

阅读 PEP 343

关于python - 试试……除了……除了……: how to avoid repeating code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/877440/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com