7. 7
To port or not to port? How?
• No port
• Port to Python 3 and ditch support for 2
• Cowboy style
• 2to3 / modernizer
• Support both 2 and 3
8. 8
From 2 to 3
Porting Strategy: Cowboy style
• Read “What’s new?” and migrate by hand
9. 9
Strategy 2: automatically move on
• Port with a tool, e.g. 2to3 / modernizer
- Works better with clean and tested code
- Works only forward
10. 10
Why not just move on to Python 3?
• Python 2 only environment
• Python 2 only dependencies
• You must have backwards compatibility
• You want to fiddle/learn
11. 11
Using six:
Which python am I running? – 2.7
>>> import six!
>>> if six.PY2:!
... print('Still stuck there?')!
... elif six.PY3:!
... print('Nice,Python 3')!
...!
Still stuck there?!
12. 12
Which python am I running? – 3.4
>>> if six.PY2:!
... print('Still stuck there?')!
... elif six.PY3:!
... print('Nice, Python 3')!
...!
Nice, Python 3!
13. 13
six – string compatibility – 2.7
>>> six.b('payload')!
'payload'!
>>> six.u('foo')!
u'foo’!
Binary strings are still just strings in 2.7
20. 20
cStringIO – six
>>> try:
... from cStringIO import StringIO!
... except ImportError:!
... from six import StringIO!
...!
>>> output = StringIO()!
>>> output.write('First line.n')!
>>> output.getvalue()!
'First line.n'!
>>> output.close()!
21. 21
cStringIO with bytes - 2.7 and 3.4
from StringIO import StringIO!
from cStringIO import StringIO!
from io import StringIO!
!
from io import BytesIO!
22. 22
cStringIO with bytes – six on 2.7
>>> try:
... from cStringIO import StringIO as BufferIO!
... except ImportError:!
... from six import BytesIO as BufferIO!
...!
>>> buf = BufferIO(b"abcdef")!
>>> buf.read(6)!
'abcdef'!
*A prefix of 'b' or 'B' is ignored in Python 2
23. 23
cStringIO with bytes – 3.4
>>> try:
... from cStringIO import StringIO as BufferIO!
... except ImportError:!
... from six import BytesIO as BufferIO!
...!
>>> buf = BufferIO(b"abcdef")!
>>> buf.read(6)!
b'abcdef'!
29. 29
cPickle – pickle – 3.4
>>> import pickle!
>>> !
>>> pickle.dumps("value")!
b'x80x03Xx05x00x00x00valueqx00.'!
pickle is written in C anyway in Python 3
30. 30
cPickle – six in 2.7
>>> import six.moves.cPickle as cPickle!
>>>!
>>> cPickle.dumps("value")!
"S'value'np1n.”!
31. 31
cPickle – six in 3.4
>>> import six.moves.cPickle as cPickle!
>>> cPickle.dumps("value")!
b'x80x03Xx05x00x00x00valueqx00.’!
32. 32
itertools.ifilter – 2.7
>>> from itertools import ifilter!
>>> result = ifilter(the_filter, data)!
ifilter = filter with iterators