尝试...除外...除外...:如何避免重复代码

问题描述:


  • 我想避免在多个地方写入 errorCount + = 1

  • 我正在寻找比


    success = False
    try:
        ...
    else:
        success = True
    finally:
        if success:
            storage.store.commit()
        else:
            storage.store.rollback()




  • 我正在尝试避免 store.rollback()在每个except子句中。

    • 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 语句的可能应用程序,它允许撤消操作并安全释放资源,无论结果是什么代码块

This look like a possible application of Python's new with statement. It allows to to unwind operations and release resources securely no matter what outcome a block of code had.

PEP 343