Another redeclared variable without usage in PyCharm

Question:

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?

Asked By: wibek

||

Answers:

I think the warning is correct, if you look at scopes:

9.2. Python Scopes and Namespaces

(…)

Although scopes are determined statically, they are used dynamically. At any time during execution, there are 3 or 4 nested scopes whose namespaces are directly accessible:

  • 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).

Answered By: bad_coder
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.