简体   繁体   English

局部变量“result”可能在赋值前被引用

[英]Local variable 'result' might be referenced before assignment

With a flow like this:像这样的流程:

def func():
    try:
        result = calculate()
    finally:
        try:
            cleanup()
        except Exception:
            pass
    return result

There is a warning about Local variable 'result' might be referenced before assignment :有一个关于局部变量'result'可能在赋值之前被引用的警告:

笏

But I can't really see how.但我真的看不出怎么做。 One of these must be true:其中之一必须为真:

  • calculate() raises an exception -> the return statement will never get reached calculate()引发异常 -> 永远不会到达 return 语句
  • calculate() does not raise an exception -> result returns a value calculate()不会引发异常 -> 结果返回一个值

How would you ever get result referenced before assignment?在分配之前,您将如何获得result引用?

Since there is no except (catch) block the detector assumes that the try block can fail, so the result will never be assigned.由于没有except (catch)块, detector假定try块可能失败,因此永远不会分配result
Moving forward, the finally block will be executed, and here cleanup() can success, so since there is no return for now, the detector assumes that the result can be reached without having an assigned value.继续前进, finally块将被执行,这里cleanup()可以成功,因此由于现在没有returndetector假设可以在没有分配值的情况下到达result

To be more explicit, this is the flow that can reach result without assigning any value to it:更明确地说,这是可以在不为其分配任何值的情况下达到result的流程:

First try fails -> It goes to finally block -> here the cleanup() works and do not interupt anything -> It goes further and returns result (which wasn't initialized yet).第一次try失败 -> 它进入finally块 -> 在这里cleanup()工作并且不中断任何东西 -> 它更进一步并返回result (尚未初始化)。

Even if you are sure that this cannot happen, the detector is warning you about this posibility.即使您确定这不会发生, detector也会警告您这种可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM