- Another redeclared variable without usage in PyCharm
- Another redeclared variable without usage in PyCharm
- Solution – 1
- Python redeclared variable defined before in PyCharm
- Answer by Carly Landry
- Answer by Alaric Li
- Answer by Orlando Warner
- Answer by Gracie Moreno
- Answer by Vance Villarreal
- Я не понимаю, почему мой код Python показывает предупреждение?
- 3 ответа
Another redeclared variable without usage in PyCharm
Another redeclared variable without usage in PyCharm
I’ve looked at several issues with this topic but I believe this is a new situation. I have this Python code in PyCharm 2022.2.2:
res = [] for i in range(10): j = i for k in range(4): res.append(j) j = j + 1
On the line j = 1 PyCharm complains about:
«Redeclared ‘j’ defined above without usage».
Obviously j is not declared above. Changing the line to j += 1 the warning disappears.
Is PyCharm confused or am I missing something?
Solution – 1
I think the warning is correct, if you look at scopes:
- the innermost scope, which is searched first, contains the local names
- the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
- (…)
There’s only 1 scope, the outer and inner for are both part of the innermost scope because they’re loops they’re not functions nor methods.
Obviously j is not declared above.
j is declared in the outer for which puts it in the same scope as i . See this concise answer in Scoping in Python ‘for’ loops.
«Redeclared ‘j’ defined above without usage».
Here’s the trick, the linter is warning you the variable wasn’t used in the outer for loop. What this is saying is that your code isn’t «pythonic»… A more pythonic way of writing it would be:
res = [] for i in range(10): for k in range(i, i+4): res.append(k)
Here you’ve gotten rid of the redundant j declaration (and the warning). The code becomes much easier to work with because you don’t have to consider the additional j variable and how its value is changed and shared between the 2 loops. That’s what the warning is trying to tell you.
End note about version:
but I believe this is a new situation. I have this Python code in PyCharm 2022.2.2:
Correct. I tried it in the older PyCharm 2022.1 and the linter does not emit the warning. So it’s a recent change (although I’ve encountered this warning in other versions under similar circumstances).
Python redeclared variable defined before in PyCharm
What happens is the different scoping than you would get in, say, C++/Java. There you’d expect i not to exist between fors. It’s not the case.,You could see that in work, assuming records == 10:,Could it be subject of any error? Should I achieve it in other way?,Making statements based on opinion; back them up with references or personal experience.
You could see that in work, assuming records == 10:
for i in range(records): filler.apply_proc('AddCompany', gen_add_company()) print("i: %d" % i) for i in range(records): filler.apply_proc('AddConference', gen_add_conference())
You’d get in your output — assuming no output from for :
Answer by Carly Landry
global variable variable = 'whatever'
Answer by Alaric Li
The above code gives the title of this question as warning in IntelliJ for the second line.,This is caused by hoisting the internal let or const to the top of the block (MDN), and create a Temporal Dead Zone.,In ECMAScript 2015, let will hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError. The variable is in a «temporal dead zone» from the start of the block until the declaration is processed.,In this example, a similar setting is giving the result as undefined because of the var hoisting. This is a silent error, and it might be very hard to debug.
for i in range(10): s = 5 for j in range(10): s = min(s)
Answer by Orlando Warner
In this exercise I am receiving a «Redeclared ‘TOTAL’ defined above without usage» error when compiling this code when am I using Pycharm but not when I compile it with Visual Studio.,How would you rewrite the TOTAL = A + int(B) + int(C) to get ride of the error I receive? Or am I just overthinking the whole thing, as the code is working fine despite the error.,I’m not sure what this is trying to achieve. Variables are not declared and can be assigned any type. This line doesn’t constrain what can go into TOTAL later. Since you reassign TOTAL without having used the 0 you put into it, pycharm flags it.,You aren’t overthinking the problem and you should get rid of this line. All it does is make one more assignment that a future reader would keep track of before realizing its not needed.
How would you rewrite the TOTAL = A + int(B) + int(C) to get ride of the error I receive? Or am I just overthinking the whole thing, as the code is working fine despite the error.
A, B, C = -5, '8', 7.6 # DO NOT MODIFY CONSTANT VALUES TOTAL = int() # DO NOT MODIFY DATA TYPE ''' PSEUDO CODE SUM given values of A, B and C as integers, CASTING where necessary. STORE result in variable 'TOTAL'. Expected output: -5 + 8 + 7.6 = 10 ''' TOTAL = A + int(B) + int(C) print("<> + <> + <> = <>".format(A, B, C, TOTAL)) # DO NOT MODIFY
Just get rid of the unneeded
TOTAL = int() # DO NOT MODIFY DATA TYPE
Python has unenforced type annotations. If you want a friendly reminder that linters like pycharm could help enforce, change it to
If you need to specify a data type, use type annotations:
Answer by Gracie Moreno
What does the slash(/) in the parameter list of a function mean?,Note that this behaviour is not peculiar to lambdas, but applies to regular functions too.,The slash at the end of the parameter list means that both parameters are positional-only. Thus, calling divmod() with keyword arguments would lead to an error:,What is the difference between arguments and parameters?
>>> x = 10 >>> def bar(): . print(x) >>> bar() 10
Answer by Vance Villarreal
Why does PyCharm warn me about Redeclared ‘do_once’ defined above without usage in the below code? (warning is at line 3),Since I want it to do it once for each file it seems appropriate to have it every time it opens a new file and it does work just like I want it to but since I have not studied python, just learned some stuff by doing and googling, I wanna know why it is giving me a warning and what I should do differently.,Edit: Tried with a boolean instead and still got the warning:,A better approach would be to jump simply stop once you have processed something in the file eg:
Why does PyCharm warn me about Redeclared ‘do_once’ defined above without usage in the below code? (warning is at line 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
Short code that reproduces the warning for me:
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
Я не понимаю, почему мой код Python показывает предупреждение?
Я изучаю кодирование на Python. Сегодня я столкнулся с проблемой. Мой код показывает вывод правильно, но показывает предупреждение. Я не знаю, в чем вина. Пожалуйста, помогите мне решить эту проблему.
class Info: Name = "" Roll = "" Section = "" Department = "" Session = "" University = "" def display(a, b, c, d, e, f): print(f"Name: ") print(f"ID: ") print(f"Section: ") print(f"Department: ") print(f"Session: ") print(f"University: ") Code = input("Enter Code: ") Code = Info() # Error in this line Code.Name = input("Enter Name: ") Code.Roll = input("Enter ID: ") Code.Section = input("Enter Section Name: ") Code.Department = input("Enter Department Name: ") Code.Session = input("Enter Session: ") Code.University = input("Enter University Name: ") display(Code.Name, Code.Roll, Code.Section, Code.Department, Code.Session, Code.University)
В этой строке отображается ошибка Code = Info()
Как я могу решить эту проблему?
3 ответа
Предупреждающее сообщение от линтера IDE сообщает вам:
Redeclared «Code» defined above without usage.
Code определяется вашим input() вызов функции. Но тогда вы определяете Code снова немедленно позвонив Info() , даже не используя результат вызова input() .
Потому что вы переназначаете одну и ту же переменную (Код) на 2 последовательные строки.
Вы можете удалить первую строку
Предупреждающее сообщение появляется, потому что вы определяете переменную с именем Code в котором вы сохраняете ввод в этой строке:
но тогда вы фактически никогда не используете его, поскольку вы переопределяете его в следующей строке:
Как вы заметили, это может не вызывать никаких ошибок, но многие современные редакторы кода предупреждают вас о неиспользуемых переменных. В вашем случае вы должны спросить себя, какова цель пользовательского ввода и почему вы его нигде не используете?