Hi Stephen,

I think this is a legitimate complaint from pylint. Consider the case where `job.devices` is an empty iterable (a list with no members, perhaps). In that case, neither the name `device_id` nor the name `device` will have been bound to any object, and therefore, there's no way to satisfy the `del` statement.

Indeed, if you run a simple program like this:

collect = []
# collect = ["hello"]  # for comparison

for member in collect:
    value = member.upper()

del member
del value

You get the same pylint warning, but better yet, you get a `NameError` raised at the point of the `del`. Your suggestion of moving the loop to the function would alleviate the problem, since there would be no need for the explicit `del`. If that's unavoidable, you could add an explicit `device = device_id = None` before the start of the for loop.

Hope this helps!
tjs

On Fri, Sep 20, 2019 at 5:17 PM Stephen Satchell <list@satchell.net> wrote:
This is a minor thing, but it is puzzling.  Here is a code fragment from
a project I'm working on:

> for device_id in job.devices:
>       device = job.devices[device_id]
>       <loop>
> del device_id
> del device

When I run pylint (version 1.6.5, astroid 1.4.9) against this code, I
get one warning diagnostic:

> Using possibly undefined loop variable 'device_id' (undefined-loop-variable)

Experimenting with Python 2, the loop variable is indeed in the name
space of the function I'm running.  I get the same result with Python 3,
 the loop variable is indeed in the function namespace.

The reason I'm using 'del' is to avoid name collisions on other sections
of code being written at different times -- this project has gone two
months already.

My "workaround" is to remove the del statement for the loop variable,
and leaving the rest of the del statements in for variables inside the
loop that (being a ex PL/1 programmer) I would assume would be out of
scope, but aren't.

I may move this loop into a separate function, and remove the need for
the del statements.

Comments?
_______________________________________________
code-quality mailing list -- code-quality@python.org
To unsubscribe send an email to code-quality-leave@python.org
https://mail.python.org/mailman3/lists/code-quality.python.org/


--
Tim Stumbaugh
Trading Control
Hudson River Trading