[英]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
(致命错误除外),最后在try
或except
块之后被调用。
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.