Support Python 2 and 3 single codebase

Many of us are currently migrating our projects from Python 2 to Python 3. While using 2to3 is the suggested possibility, many of us are finding that using a single if statement to define a only few things is enough in many simple projects. This is particularly useful when iterating between coding and testing as avoids the use of 2to3.

It would be nice if Pycharm introspection supports from this type of programming without wrongly labling an error. For this purpose Pycharm would need to understand this construct (or something similar):

if sys.version < '3':

   # version 2 code


   # version 3 code



Comment actions Permalink

What issues exactly are incorrectly highlighted by PyCharm?

You can configure PyCharm's code compatiblility inspection to tell it that your codebase must be compatible with both Python 2 and Python 3.

Comment actions Permalink

I was not aware about the configuration setting that you mentioned. Thanks for the tip. However does not seem to help in this case. For example with a Python 3 interpreter configured, I get the following introspection (shown as comments in the code)

if sys.version < '3':

    string_types = basestring  # <----- "basestring type is not available in py3"
    from io import open
    from StringIO import StringIO # <----- "Unresolved reference 'StringIO'
    _tokenize = lambda input: tokenize.generate_tokens(StringIO(input).readline)
    string_types = str
    _tokenize = lambda input: tokenize.tokenize(BytesIO(input.encode('utf-8')).readline)



Please sign in to leave a comment.