You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The way I've done it for existing Python 2 code is (requires Python>=2.6):
(i) Fix the unicode vs. bytes situation beforehand and decide how it
should work. Use explicit bytes literals, and use .encode() and
.decode() rather than unicode(). If you need unicode literals, Python 3
needs to be >= 3.3. For Python 3.1/3.2 you can use the u() function from
the `six` package.
Also replace StringIO -> io.BytesIO or io.StringIO as appropriate, for
bytes and unicode data. Also, don't rely on automatic encoding when
writing unicode string to byte streams.
(ii) Run 2to3 -w on the code.
(iii) Add on top of each file:
from __future__ import division, print_function, absolute_import
This makes /, print(), and imports behave the same on Python >= 2.6. The
thing to be careful is use of / versus // --- note that 2to3 cannot fix
these automatically.
(iv) If you use passing exceptions on, some magic with traceback module
needs to be done.
(v) Optional: go through the changes by 2to3, and use the `six` module
to clean things up:
isinstance(foo, collections.Callable) -> callable(foo)
range -> xrange where appropriate
list(somedict.keys()) -> somedict.keys() where appropriate
***
For new code: I'd write it in Python 3 and add to the top
from __future__ import division, print_function, absolute_import
Most Python 3 code runs then just fine on Python 2. Python 3 forces you
to write your unicode/bytes separation more carefully. However, extra
care is needed with string literals, and with print(), as Python 2 uses
ascii encoding as the default output encoding when writing to a pipe
rather than a terminal...
Adding 'unicode_literals' to the __future__ stanza makes string literals
unicode also on Python 2. This may be useful.
I don't have so much experience with this yet, so we'll see how well
this will go.
The text was updated successfully, but these errors were encountered:
Work happens on the "2013" branch.
From Pauli Virtanen:
The text was updated successfully, but these errors were encountered: