Pylint: Using the undefined variable of the loop variable 'n'

Pilint will say

  W: 6: Using possibly undefined loop variable 'n'

using this code:

iterator = (i*i for i in range(100) if i % 3 == 0) for n, i in enumerate(iterator): do_something(i) print n 

because if the iterator is empty (for example, []) n is undefined, ok. But I like this trick. How to use it in a safe way?

I think using len (list (iterator)) is not the best choice because you need to make two loops. Using the counter and increasing it, I think that it is not very pythonic.

+4
source share
2 answers

Have you considered simply initializing n to None before starting the loop?

+6
source

Define the default value for n before the for statement:

 iterator = (i*i for i in range(100) if i % 3 == 0) n=None for n, i in enumerate(iterator): do_something(i) print n 
+3
source

Source: https://habr.com/ru/post/1302525/


All Articles