[code-quality] This seems like a good warning candidate...

Phil Frost indigo at bitglue.com
Mon Dec 8 22:44:46 CET 2014


On Mon, Dec 8, 2014 at 3:21 PM, Ian Cordasco <graffatcolmingov at gmail.com>
wrote:

> I'm not sure in what case code like what Skip shared wouldn't result
> in an error:
>
>     for i in range(1, 10):
>         for i in ['foo', 'frob', 'bob', 'bogus', 'smogus']:
>             do_stuff(i)
>         do_other_stuff(i)
>

A slight variation that is probably correct:

for i in range(1, 10)
  do_other_stuff(i)
  for i in ['foo', 'frob', 'bob', 'bogus', 'smogus']:
    do_stuff(i)

The difference here being that the outer `i` is used before it's reassigned
by the inner loop. We could only emit a warning if the loop variable is
re-defined if it's not yet used, but then what about this:

# https://www.youtube.com/watch?v=jrzUsHNGZHc
for _ in xrange(3):
    for _ in xrange(3):  # `_` is unused and redefined, but who cares?
        knock()
    say "Penny"

We might consider re-using a loop variable outside the loop as the problem,
but then what about:

for thing in some_things():
    if is_the_one_im_seeking(thing):
        break
else:
    raise CouldntFindTheThingException
frob(thing)

I agree, it would be good to catch this error, but I haven't thought of a
way to do it that doesn't run afoul of false positives.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/code-quality/attachments/20141208/9586b78c/attachment.html>


More information about the code-quality mailing list