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

Geo*_*lly 3 python dry try-catch

  • 我想避免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)
Run Code Online (Sandbox Code Playgroud)

Ber*_*Ber 8

这看起来像是Python新with语句的可能应用.它允许解除操作并安全地释放资源,无论代码块有什么结果.

PEP 343中了解它