- 我想避免写作
errorCount += 1
在不止一处。
- 我正在寻找比更好的方法
success = False
try:
...
else:
success = True
finally:
if success:
storage.store.commit()
else:
storage.store.rollback()
- 我试图避免
store.rollback()
在每个 except 子句中。
关于如何做到这一点有什么想法吗?
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)