简体   繁体   English

如何重写这段代码,这样 PyCharm 就不会警告 Local variable might be referenced before assignment?

[英]How to rewrite this code, such that PyCharm doesn't warn Local variable might be referenced before assignment?

Please consider请考虑

def foo():
    bs = (4, 5)
    for b in bs:
        c = b + 1
    return c

PyCharm marks the c in the return c with PyCharm 标记return c c的 c

Local variable 'c' might be referenced before assignment局部变量“c”可能在赋值前被引用

This is a good warning, usually, and I don't want to disable it.通常这是一个很好的警告,我不想禁用它。 ( #noqa is not an answer) #noqa不是答案)

In this case, however, it can be deduced before running that c always has a value.然而,在这种情况下,可以在运行之前推断出 c 始终具有值。


How to rewrite the code to help PyCharm understand this?如何重写代码来帮助PyCharm理解这个?

You can do what is done in most languages which is to instantiate c to a value of 0.你可以做大多数语言所做的事情,即将 c 实例化为 0 值。

def foo():
    bs = (4, 5)
    c = 0     
    for b in bs:
        c = b + 1
    return c

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

相关问题 Pycharm - 禁用'局部变量'xxx'可能在赋值之前被引用' - Pycharm - Disable 'Local variable 'xxx' might be referenced before assignment' 在赋值之前可能会引用局部变量 - Python - Local variable might be referenced before assignment - Python 局部变量“result”可能在赋值前被引用 - Local variable 'result' might be referenced before assignment 局部变量“put”可能在赋值之前被引用 - Local variable 'put' might be referenced before assignment 局部变量可能在赋值前被引用 - Local Variable might ne referenced before assignment 在 Python 中赋值之前可能会引用局部变量 - local variable might be referenced before assignment in Python 分配前可能会引用局部变量 - Local variable might be referenced before assignment Pylint 没有捕捉到“局部变量 'xyz' 可能在赋值之前被引用”但 PyCharm 使用 python 2.7 突出显示相同 - Pylint is not catching "Local variable 'xyz' might be referenced before assignment " but PyCharm is highlighing the same, using python 2.7 PyCharm:在分配之前可能会在finally块中引用变量吗? - PyCharm: Variable in finally block might be referenced before assignment? 在分配全局之前引用的局部变量不起作用 - Local variable referenced before assignment global doesn't work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM