返回变量时出现 UnboundLocalError

UnboundLocalError when returning a variable

我有一个静态方法可以收集一些东西并 returns 它们。

@staticmethod
def testForMetrics(....):
    ...
    ...

    coverages = Metrics.findCoverageStats(....)

    ...
    return coverages, ....

findCoverageStats 看起来像

@staticmethod
def findCoverageStats(....)
    coverages = {}

    ...# fill coverages with calculations

    return coverages

运行 告诉我 UnboundLocalError: local variable 'coverages' referenced before assignment,但只是在极少数情况下。

什么样的边缘情况会导致这种行为?

您提到的错误类型 (UnboundLocalError: local variable 'xxx' referenced before assignment) 是典型的情况,因为通过函数的多个潜在执行路径未设置变量。

有关此类情况的(简化)示例,请参见下文:

def fun():
    if random.randint() < 1000:
        xxx = 1
    else:
        yyy = 1

    return xxx

一个出路是用默认值声明 xxx 或在 else 子句中赋值(下面的第一个解决方案)。

def fun():
    xxx = 0
    if random.randint() < 1000:
        xxx = 1
    else:
        yyy = 1

    return xxx