确定长 python 行的确切错误

Determine the exact error of a long python line

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

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,因为这是输出:

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

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

把这道意大利面分开:

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":

还是丑。但它会将错误缩小到一个数组...

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

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

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

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