2
for i in range(10):
    s = 5
    for j in range(10):
        s = min(s)

The above code gives the title of this question as warning in IntelliJ for the second line.

I'm pretty sure that the warning happens because in the CFG there are possibly two consecutive writes (without read in between) to s because of the nested loops. Until now I have been ignoring the warning but to be on the safe side I'd like to ask for confirmation of my hypothesis.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
ben
  • 5,671
  • 4
  • 27
  • 55
  • 1
    You keep assigning values to `s` while never using it. The IDE is pointing out that there's no reason to do this – Patrick Haugh Oct 01 '16 at 15:49
  • That seems like a reasonable assumption. Since you will always run the `for` loop after `s = 5`, that code is redundant. If you were enumerating something else like a list that could be empty, then there would be a justification for initializing s (even then, an `else` clause would be better) but not here. – tdelaney Oct 01 '16 at 15:50

2 Answers2

2

Your hypothesis is nearly correct. The name s was bounded to an integer whose value was never used nor changed in the enclosing loop and yet it is rebounded to another value (although that will raise an error) in the nested loop. Note that the first assignment does not change with any iteration of the outer for loop.

The IDE's warning suggests the first assignment inside the loop is unnecessary as s was never changed. The assignment might as well have been better placed outside the for loop which will prevent a redundant binding and rebinding:

s = 5
for i in range(10):
    ...
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • Why would rebinding `s` inside the loop raise an error? How would your code example be equivalent to the original since `s` could have any value other than 5 depending on the implementation of the `min` function? – Alex Spurling Dec 11 '22 at 20:00
  • @AlexSpurling Because calling `min` on a non-iterable object (integer here) raises an error. The implementation is only same with assigning `s` to a literal value and not similar to the case of a value that changes with each iteration. – Moses Koledoye Dec 22 '22 at 18:36
0

It is what it says. You remade something without using it or defining it. Like for me, example:

def car(e):
    color = "blue"
    print(color)

def car(r):

Run

Error, I redefine the function, can't do that as far as I know, I didn't make it do anything. Thought I was using the function, didn't realize I was re defining it.

correction

def car(e):
    color = "blue"
    print(color)

car(e)