为什么PyCharm报告局部变量的“未使用”警告?

2024-04-28 10:31:11 发布

您现在位置:Python中文网/ 问答频道 /正文

weather_str = None
if isinstance(weather, list):
     weather_str = "\n\n".join(weather)
 else:
     weather_str = weather
 dispatcher.utter_message(
        "{}'s weather on {}:\n {}\n ".format(location, date, 
     weather_str)
 )

PyCharm将“weather\u str”显示为灰色,并警告:

Local variable 'weather_str' not used

为什么?这是一个明显但恼人的假警报?你知道吗


Tags: noneformatmessagedateifonlocationelse
1条回答
网友
1楼 · 发布于 2024-04-28 10:31:11

从中可以看出这一点

if isinstance(weather, list):
    weather_str = "\n\n".join(weather)
else:
    weather_str = weather

weather_str总是被分配给某个对象,因此之前分配给它的None值永远不会被使用。你知道吗

去掉第一行没关系。根据Python's execution model,“如果一个局部变量是在一个块中定义的,那么它的作用域包括那个块”。此外,“以下是块:模块、函数体和类定义。”。所以条件语句不会创建新的作用域。你知道吗

更多讨论请参见this question

相关问题 更多 >