开发者

pylint: Using possibly undefined loop variable 'n'

开发者 https://www.devze.com 2022-12-21 21:21 出处:网络
Pylint says W:6: Using possibly undefined loop variable \'n\' ... with this code: iterator = (i*i for i in range(100) if i % 3 == 0)

Pylint says

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

... with 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 that using len(list(iterator)) is not the best choice because you have to do two loops. I think that开发者_JAVA百科 using a counter and incrementing it is not very pythonic.


Have you considered merely initializing n to None before running the loop?


Define a 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
0

精彩评论

暂无评论...
验证码 换一张
取 消