| | 7 | The main difficulty in writing code that is both Python 2 and 3 compatible is getting to the exception object. |
| | 8 | |
| | 9 | The ''old'' syntax that works in all recent Python 2 (at least 2.5-2.7) versions looks like this: |
| | 10 | {{{ |
| | 11 | except Exception, e: |
| | 12 | }}} |
| | 13 | The variable ''e'' contains the exception that occurred. This syntax is not supported by Python 3. |
| | 14 | |
| | 15 | An alternative syntax is supported in Python 2.6, 2.7 and all Python 3 versions: |
| | 16 | {{{ |
| | 17 | except Exception as e: |
| | 18 | }}} |
| | 19 | Again, ''e'' contains the exception object. |
| | 20 | |
| | 21 | As long as Python 2.5 needs to be supported, this is a problem, as Python 2.5 does not support the new ''as'' notation and Python 3 on the other hand does not support the old ''comma'' notation. |
| | 22 | |
| | 23 | Fortunately, there is a workaround: |
| | 24 | |
| | 25 | {{{ |
| | 26 | except Exception: |
| | 27 | e = sys.exc_info()[1] |
| | 28 | }}} |
| | 29 | |
| | 30 | or alternatively for easy find & replace a standalone version independent on external imports: |
| | 31 | |
| | 32 | {{{ |
| | 33 | except Exception: |
| | 34 | import sys |
| | 35 | e = sys.exc_info()[1] |
| | 36 | }}} |
| | 37 | |
| | 38 | This piece of code might look weird, but works in Python 2.5 - 3.3+ |
| | 39 | |
| | 40 | If Python 2.5 doesn't have to be supported, just using the ''as'' syntax is enough for the exception handling code to be Python 2.6-3.3+ compatible. |