Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using possibly undefined loop variable #440

Closed
chabotsi opened this issue Mar 8, 2019 · 4 comments
Closed

Using possibly undefined loop variable #440

chabotsi opened this issue Mar 8, 2019 · 4 comments

Comments

@chabotsi
Copy link

chabotsi commented Mar 8, 2019

In the code below, the variable value is possibly undefined. It would be nice to have a warning. For instance, Pylint gives the following one « W0631: Using possibly undefined loop variable 'value' (undefined-loop-variable) ».

#!/usr/bin/env python3
# coding: utf-8

"""
    the variable `value` is possibly undefined.
"""


def print_content(iterable):
    """
        print the content of the given iterable
    """
    for value in iterable:
        print(value)
    last_value = value
    print('The last_value is ', last_value)


print_content('abcd')
print_content([])
@sigmavirus24
Copy link
Member

So to be clear, if you run this on python 3 as is, you should get:

UnboundLocalError: local variable 'value' referenced before assignment

But this is not an issue with Python 2.

Also if you add something like:

    value = None

Prior to the

    for value in iterable:

Then this doesn't error. As long as the context for how a variable is created is preserved (created as part of a for-loop for example, or on Python 3.8 with :=) then this would be possible. I suspect, however, that Pyflakes method for finding/tracking bindings is too simplistic for this to work.

@chabotsi
Copy link
Author

chabotsi commented Mar 8, 2019

But this is not an issue with Python 2

I obtain the same error in python2.

Also if you add something like:
value = None

Sure, the whole point is that we should get a warning to add this declaration prior to the loop. No ?

@bitglue
Copy link
Member

bitglue commented Mar 8, 2019

Pyflakes should report this as an error in python3, but in my testing (2.1.1 Python 3.7.2 on Darwin) it does not. I think this may be a regression.

In python2 there won't be an error because value might be defined.

@asottile
Copy link
Member

collecting duplicates for "pyflakes doesn't do branch analysis" here: #715

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants