0

After having written this piece of code to execute queries on database separately, PyCharm highlighted the second i with the given comment.

for i in range(records):
    filler.apply_proc('AddCompany', gen_add_company())

for i in range(records):
    filler.apply_proc('AddConference', gen_add_conference())

Redeclared 'i' defined above without usage.

Could it be subject of any error? Should I achieve it in other way?

vestland
  • 55,229
  • 37
  • 187
  • 305
Bartłomiej Szałach
  • 2,393
  • 3
  • 30
  • 50

1 Answers1

1

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:

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:

i: 9

The reason why you're getting the warning is probably that this kind of thing could lead to brain-cracking bugs. Indirect solutions are included in the linked page; one you could consider is to encase your for in a function, which might be especially good for readability if this happens more than twice.

There's also a similar case of scoping surprise in list comprehensions, but not in Python 3 you're asking about.

Community
  • 1
  • 1
TNW
  • 716
  • 6
  • 15