5

I'm refactoring some python2 code and changing it to python3 using 2to3 module. I've received following parse error:

RefactoringTool: There was 1 error:
RefactoringTool: Can't parse ./helpers/repo.py: ParseError: bad input: type=22, value='=', context=(' ', (45, 25))

Here is a code that yields the error:

    except ImportError as error_msg:  # pragma: no cover                           
        print(' ',  file = sys.stderr) # this is a line that yields error                                          
        print("Could not locate modifyrepo.py", file=sys.stderr)                
        print("That is odd... should be with createrepo", file=sys.stderr)      
        raise ImportError(error_msg)

I have no clue what could be wrong. Can you please help?

cmd
  • 63
  • 1
  • 4
  • Possible duplicate of [2to3 ParseError in python file](https://stackoverflow.com/questions/56523611/2to3-parseerror-in-python-file) – ejderuby Aug 14 '19 at 12:22

4 Answers4

4

The problem is that the code that you're trying to convert is not valid Python 2 code.

When running your code using Python 2, you'll get the following error:

  File "repo.py", line 5
    print(' ',  file = sys.stderr) # this is a line that yields error
                     ^
SyntaxError: invalid syntax

It seems like this code already is Python 3 code. Using Python 3 your code does not yield a SyntaxError.

wovano
  • 4,543
  • 5
  • 22
  • 49
  • Oh! Thanks! In the meantime I found this: https://bugs.python.org/issue35260, but still couldn't grasp what's wrong. – cmd Aug 13 '19 at 10:34
  • 1
    @cmd, the first response on that bug report actually says the same: "2to3 expects a valid Python 2 file as input, and the file a.py isn't a valid Python 2 file: the `print` line is a SyntaxError in the absence of a `from __future__ import print_function`. So yes, this *is* being treated like Python 2 code, but that's what 2to3 is designed to do." – wovano Aug 13 '19 at 10:38
2

If you have already converted your print statements to functions (as you have done) you can use the -p parameter when invoking 2to3

-p, --print-function Modify the grammar so that print() is a function

E.g.

2to3 -p yourfile.py
joctee
  • 2,429
  • 1
  • 23
  • 19
0

I found that absolute import addressing sorted this for me. Syntax was all fine, but relative import with the following gave an error.

Failed:

from . import classes.utility as util

Works:

from classes import utility as util

This may just be my lack of understanding of imports in Python3 though.

Doug
  • 665
  • 2
  • 8
  • 22
0

I got a similar issue. My print statements were already converted to functions.

The issue was that the import of the print function was done as

from __future__ import (
    unicode_literals,
    print_function,
)

To fix it, I had to put the import on a separate, dedicated line line

from __future__ import print_function

Hope it helps

Adi Roiban
  • 1,293
  • 2
  • 13
  • 28