pyflakes: undefined name 'unicode' in "wrong" sys.version_info branch

Original report by cboltz (@cboltz?) on Launchpad:


pyflakes makes it hard to check code that works on python 2 and 3 because some names are only defined in one version.

For example, take this little module:

import sys

def type_is_str(var):
    ''' returns True if the given variable is a str (or unicode string when using python 2)'''
    if type(var) == str:
        return True
    elif sys.version_info[0] < 3 and type(var) == unicode:  # python 2 also uses the 'unicode' type
        return True
    else:
        return False

pyflakes3 errors out with undefined name ‘unicode’ while pyflakes2 validates this code successfully (because unicode is a valid name in py2).

Can you make pyflakes a bit more intelligent so that it skips branches for the “wrong” version? Or, if that is too hard, add a way to skip a line marked with a special comment like # PYFLAKES:IGNORE ?

(The py3 testing was done with python3-pyflakes-1.2.3.)

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 1
  • Comments: 15 (8 by maintainers)

Most upvoted comments

That seems like it would mask more bugs than false positives. When I take some code that was written for Python 2, pyflakes is a useful tool for seeing which parts won’t work in Python 3 (at least as a first pass).

if PY3: unicode = str silences the error, and guards against faulty version checking logic.