【问题标题】:Why does pycharm warn about "Redeclared variable defined above without usage"?为什么pycharm会警告“上面定义的重新声明的变量没有使用”?
【发布时间】:2018-03-29 19:43:52
【问题描述】:

为什么 PyCharm 在下面的代码中警告我 Redeclared 'do_once' defined above without usage? (警告在第 3 行)

for filename in glob.glob(os.path.join(path, '*.'+filetype)):
    with open(filename, "r", encoding="utf-8") as file:
        do_once = 0
        for line in file:
            if 'this_text' in line:
                if do_once == 0:
                    //do stuff
                    do_once = 1
                //some other stuff because of 'this text'
            elif 'that_text' in line and do_once == 0:
                //do stuff
                do_once = 1

由于我希望它对每个文件执行一次,因此每次打开一个新文件时都使用它似乎是合适的,并且它确实像我想要的那样工作,但由于我没有研究过 python,只是通过学习一些东西做和谷歌搜索,我想知道为什么它会给我一个警告以及我应该做些什么不同的事情。

编辑: 尝试使用布尔值,但仍然收到警告:

为我重现警告的短代码:

import os
import glob

path = 'path'

for filename in glob.glob(os.path.join(path, '*.txt')):
    with open(filename, "r", encoding="utf-8") as ins:
        do_once = False
        for line in ins:
            if "this" in line:
                print("this")
            elif "something_else" in line and do_once == False:
                do_once = True

【问题讨论】:

  • 我试过了,无法重现。您使用的是什么 PyCharm 版本?请发布最少的完整代码,将其复制并粘贴到新的 PyCharm 脚本中会导致问题。
  • 添加了导致警告的最小完整代码,可能是我正在使用 PyCharm 2016 v3.3,还没有时间/原因进行更新,但会尝试检查是否删除了警告.

标签: python pycharm


【解决方案1】:

我的猜测是 PyCharm 被整数作为标志的使用弄糊涂了,在您的用例中可以使用多种替代方案。

使用布尔标志而不是整数

file_processed = False
for line in file:
    if 'this' in line and not file_processed:
        # do stuff
        file_processed = True
    ...

更好的方法是在您处理完文件中的某些内容后直接停止跳转,例如:

for filename in [...list...]:
    while open(filename) as f:
        for line in f:
            if 'this_text' in line:
                # Do stuff
                break  # Break out of this for loop and go to the next file

【讨论】:

  • 你能重现警告吗?
  • 抱歉这么久才回复,我试过了,还是收到警告。
【解决方案2】:

为了解决一般情况:

你可能在做什么

v1 = []
for i in range(n):
    v1.append([randrange(10)])

v2 = []
for i in range(n):      # <<< Redeclared i without usage
    v2.append([randrange(10)])

你能做什么

v1 = [[randrange(10)] for _ in range(5)]   # use dummy variable "_"
v2 = [[randrange(10)] for _ in range(5)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 2018-03-16
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    相关资源
    最近更新 更多