python - 确定长 python 行的确切错误

我的代码中有很长的行,例如:

if (currentExcelDep[excelPackageName]== depDataCollection[depDataCollectionSet][depDataCollectionSetElement][excelPath] and currentExcelDep[excelPath].split("/")[1] == depDataCollection[depDataCollectionSet][depDataCollectionSetElement][0].split("/")[1] and depDataCollection[depDataCollectionSet][depDataCollectionSetElement][excelVersion]and currentExcelDep[3] == "Approved"):

我的问题是我在这一行有一个 IndexError SOMEWHERE,因为这是输出:

Traceback (most recent call last):
  File "main_collection.py", line 96, in <module>
    if (currentExcelDep[excelPackageName]== depDataCollection[depDataCollectionSet][depDataCollectionSetElement][excelPath] and currentExcelDep[excelPath].split("/")[1] == depDataCollection[depDataCollectionSet][depDataCollectionSetElement][0].split("/")[1] and depDataCollection[depDataCollectionSet][depDataCollectionSetElement][excelVersion]and currentExcelDep[3] == "Approved"):
IndexError: list index out of range

我到底怎么知道代码中的问题出在哪里?

我的意思是,我可以在我的意大利面条代码中查找它并通过将这个大表达式拆分为较小的表达式来自己弄清楚,但我想学习如何更有效地处理这个问题,在这种情况下,而且在未来。

回答1

把这个意大利面从地狱里分出来:

if currentExcelDep[excelPackageName] == \
    depDataCollection[depDataCollectionSet][depDataCollectionSetElement][excelPath] and \
    currentExcelDep[excelPath].split("/")[1] == \
    depDataCollection[depDataCollectionSet][depDataCollectionSetElement][0].split("/")[1] and \
    depDataCollection[depDataCollectionSet][depDataCollectionSetElement][excelVersion] and \
    currentExcelDep[3] == "Approved":

它仍然很丑。但它会将错误缩小到一个数组......

回答2

为了便于调试,您可能希望在检查各个条件之前添加一系列断言。

assert excelPackageName in currentExcelDep
assert depDataCollectionSet in depDataCollection
assert depDataCollectionSetElement in depDataCollection[depDataCollectionSet]
assert excelPath in depDataCollection[depDataCollectionSet][depDataCollectionSetElement]
assert excelPath in currentExcelDep
assert "/" in currentExcelDep[excelPath]
assert depDataCollection[depDataCollectionSet][depDataCollectionSetElement]
assert "/" in depDataCollection[depDataCollectionSet]
assert len(currentExcelDep) > 3

(不确定我是否能全部抓住,但你可以在这里看到模式。另外,我必须猜测哪些变量是列表,哪些是字典,我可能猜错了。)

如果出于性能原因需要,可以在生产代码中关闭断言,但通常让它们保持启用状态是有意义的,这样当你的假设不成立时,你就可以准确地看到出了什么问题。

相似文章

随机推荐

最新文章