为什么pycharm警告“没有使用上面定义的Redeclared变量”?

时间:2017-05-09 08:55:17

标签: python pycharm

为什么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

2 个答案:

答案 0 :(得分:0)

我的猜测是使用整数作为标志使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

答案 1 :(得分:0)

为了解决一般情况:

您可能正在做什么

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)]