Reputation: 3163
Trying to parse a malformed XML content with xml.etree.ElementTree.parse() raises different exception in Python 2.6.6 and Python 2.7.5
Python 2.6: xml.parsers.expat.ExpatError
Python 2.7: xml.etree.ElementTree.ParseError
I'm writing code which must run in Python 2.6 and 2.7. afaik there is no way to define code which runs only in a Python version in Python (analogous to what we could do with #ifdef in C/C++). The only way I see to handle both exceptions is to catch a common parent exception of both (eg Exception). However, that is not ideal because other exceptions will be handled in the same catch block. Is there any other way?
Upvotes: 1
Views: 5460
Reputation: 3163
Based on mgilson's answer:
from xml.etree import ElementTree
try:
# python 2.7+
# pylint: disable=no-member
ParseError = ElementTree.ParseError
except ImportError:
# python 2.6-
# pylint: disable=no-member
from xml.parsers import expat
ParseError = expat.ExpatError
try:
doc = ElementTree.parse(<file_path>)
except ParseError:
<handle error here>
Upvotes: 0
Reputation: 309929
This isn't pretty, but it should be workable ...
ParseError = xml.parsers.expat.ExpatError if sys.version < (2, 7) else xml.etree.ElementTree.ParseError
try:
...
except ParseError:
...
You might need to modify what you import based on versions (or catch ImportError
while importing the various submodules from xml
if they don't exist on python2.6 -- I don't have that version installed, so I can't do a robust test at the moment...)
Upvotes: 3