pylint: Using possibly undefined loop variable 'n'

Deadly 提交于 2019-12-14 03:45:16

问题


Pylint say

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. Using a counter, and incrementing it I think it's not very pythonic.


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/2344315/pylint-using-possibly-undefined-loop-variable-n

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!