Question

I am having a delicate problem with python exceptions. My software is currently running on multiple platforms and I still aim at being compatible with py2.5 because it's on a cluster where changing versions will become major effort.

One of the (debian) systems was recently updated from 2.6 to 2.7, and some pieces of code throw weird exceptions from the underlying C parts. However, this was never the case before and still is not the case on my mac 2.7 -> there's no bug in the code but rather with one of the new libraries.

I figured how to manage the exception for 2.7, but the exception handling is unfortunately incompatible with 2.5.

Is there a way to run something like "preprocessor commands - C style?"

if interpreter.version == 2.5:
foo() 
elif interpreter.version == 2.7:
bar()

?

Cheers, El

Example attached:

try:                                                                                                     
    foo()
except RuntimeError , (errorNumber,errorString):
    print 'a'
    #ok with 2.5, 2.7 however throws exceptions

try:                                                                                                     
    foo()
except RuntimeError as e:
    print 'a'
#ok with 2.7, 2.5 does not understand this
Was it helpful?

Solution

You can write two different try...except for two different versions basically for those mis match exception in two different versions.

import sys

if sys.version_info[:2] == (2, 7):
    try:
        pass
    except:
        # Use 2.7 compatible exception
        pass
elif sys.version_info[:2] == (2, 5):
    try:
        pass
    except:
        # Use 2.5 compatible exception
        pass

OTHER TIPS

You can write your exception handler to be compatible with both python versions instead:

try:                                                                                                     
    foo()
except RuntimeError, e:
    errorNumber, errorString = e.args
    print 'a'

Demo:

>>> def foo():
...     raise RuntimeError('bar!')
... 
>>> try:
...     foo()
... except RuntimeError, e:
...     print e.args
... 
('bar!',)

There is no need to do Python version detection here, unless you need this to work across Python versions 2.5 through to 2.7 and Python 3.x.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top