Changes between Version 3 and Version 4 of python2and3CompatiblityEN


Ignore:
Timestamp:
Jun 13, 2013, 1:04:52 AM (11 years ago)
Author:
Martin Kolman
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • python2and3CompatiblityEN

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