6

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?

1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh! Thanks! In the meantime I found this: bugs.python.org/issue35260, but still couldn't grasp what's wrong.
@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."
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

Comments

1

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.