简体   繁体   English

PyCharm:在分配之前可能会在finally块中引用变量吗?

[英]PyCharm: Variable in finally block might be referenced before assignment?

PyCharm warns me that variable category can be referenced before assignment but I don't think so. PyCharm警告我说,可变category可以赋值之前被引用,但我不这么认为。

Except should catch every Exception (except fatal errors) and finally is called after try or except block. Exception应该捕获每个Exception (致命错误除外),最后在tryexcept块之后被调用。

    try:
        category = lst[2]
    except:
        category = None
    finally:
        if not category: #here
            category = self.default_category

在此处输入图片说明

What do you think? 你怎么看? Is it true or is it a bug? 是真的还是错误?

Perhaps PyCharm is seeing the assignment without considering, "assignment to what". 也许PyCharm在看到分配时没有考虑“分配给什么”。 That is, the None is what makes the difference, consider if you instead wrote: 就是说, None是什么与众不同,请考虑是否改写了以下内容:

try:
    category = lst[2]
except:
    category = Noone
finally:
    if not category:
        category = self.default_category

(Or None/1 , etc.) Then you'd get: (或None/1等),然后您将得到:

NameError: name 'category' is not defined

as there would be an exception in the exception if lst were empty: 如果lst为空,则在异常中会有一个异常:

When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in an except or else clause), it is re-raised after the finally clause has been executed. 当try子句中发生了异常且未由except子句处理(或在except或else子句中发生)时,将在执行finally子句后重新引发该异常。

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

相关问题 Pycharm - 禁用'局部变量'xxx'可能在赋值之前被引用' - Pycharm - Disable 'Local variable 'xxx' might be referenced before assignment' 赋值前引用的 Pycharm 变量 - Pycharm variable 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 就不会警告 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?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM