Home > database >  Correct raise translation for python 3.7 w two arguments
Correct raise translation for python 3.7 w two arguments

Time:08-13

How do I convert this code from Python 2 to to Python 3:

except ET.XMLSyntaxError, log:
    #This exception raised if the file has parse errors in it
    logging.error("XSD: "   log.message)        
    raise SyntaxError, log.message

I'm not actually sure what the raise line is doing. I've already replaced

except ET.XMLSyntaxError, log:

with

except ET.XMLSyntaxError as log:

Background: I upgraded my system to python 3.7 and our build is not working with a number of Python scripts though it might be faster to update our scripts to Python 3 than revert my ubuntu environment.

CodePudding user response:

The immediate fix for you is this:

raise SyntaxError(log.message)

If you have a lot of Python 2.x scripts, I'd recommend using the 2to3 tool to have it translate from python 2.x to 3.x. The documentation even calls out the raise change you're asking for here:

raise

Converts raise E, V to raise E(V), and raise E, V, T to raise E(V).with_traceback(T). If E is a tuple, the translation will be incorrect because substituting tuples for exceptions has been removed in 3.0.

Here's a snippet with a piece of code that's in Python 2.x exception format that we'll run 2to3 on:

import logging

try:
    print "hello"
except Exception, log:
    #This exception raised if the file has parse errors in it
    logging.error("XSD: "   log.message)
    raise Exception, log.message

Running 2to3

# As needed: pip install 2to3
> 2to3 code.py
RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: Refactored code.py
--- code.py (original)
    code.py (refactored)
@@ -1,8  1,8 @@
 import logging

 try:
-   print "hello"
-except Exception, log:
    print("hello")
 except Exception as log:
    #This exception raised if the file has parse errors in it
    logging.error("XSD: "   log.message)
-   raise Exception, log.message
    raise Exception(log.message)
RefactoringTool: Files that need to be modified:
RefactoringTool: code.py
  • Related