Making friends with Python 3

Available now on the interwebs!

www.waveform.org.uk/presentations/py3friends/

Vitalstatistix

Name
Dave Jones
Twitter
@waveform80
GitHub
github.com/waveform80

Why?

It's the future!

2 is the past

(well … eventually)

From 2.7 release notes:

“Python 2.7 is currently expected to remain supported by the core development team … until at least 2020”

How?

Why not 2to3?

If you're on <2.7

If you're on >=2.7

from __future__ import (
    unicode_literals,
    absolute_import,
    print_function,
    division,
    )
>>> from __future__ import unicode_literals
>>> type('')
<type 'unicode'>
>>> type(b'')
<type 'str'>
>>> from __future__ import unicode_literals
>>> type('')
<type 'str'>
>>> type(b'')
<type 'bytes'>
>>> from __future__ import absolute_import
>>> import foo # "foo.py" *must* be in sys.path
>>> import .foo # import "foo.py" from this module's dir
>>> import ..foo # import "foo.py" from parent module's dir
>>> from __future__ import print_function
>>> print "Hello world!"
  File "<stdin>", line 1
      print "Hello world!"
                         ^
SyntaxError: Missing parentheses in call to 'print'
>>> print("Hello world!")
Hello world!
>>> 1/2
0
>>> -1/2
-1
>>> from __future__ import division
>>> 1/2
0.5
>>> -1/2
-0.5
>>> 1//2
0
>>> -1//2
-1
from __future__ import (
    unicode_literals,
    absolute_import,
    print_function,
    division,
    )
str = type('')
>>> isinstance('foo', str)
True
>>> isinstance(b'foo', str)
False
>>> isinstance('foo', bytes)
False
>>> isinstance(b'foo', bytes)
True
from __future__ import (
    unicode_literals,
    absolute_import,
    print_function,
    division,
    )
nstr = str
str = type('')
>>> import struct
>>> struct.pack(nstr('>bbl'), 0, 0, -1)
'\x00\x00\xff\xff\xff\xff'
import io
text_file = io.open('foo.txt', 'w', encoding='utf-8')
text_file.write('Some text (note, this is unicode!)')

bin_file = io.open('bar.dat', 'rb')
bin_file.write(b'Some data including binary\x00')

stream = io.BytesIO()
stream.write(b'\xff\xff')
try:
    from itertools import izip as zip
except ImportError:
    pass

For big zips

try:
    range = xrange
except NameError:
    pass

For big ranges

from functools import reduce
try:
    from SocketServer import TCPServer, ForkingMixIn
except ImportError:
    from socketserver import TCPServer, ForkingMixIn
try:
    import SocketServer as socketserver
except ImportError:
    import socketserver
from __future__ import (
    unicode_literals,
    absolute_import,
    print_function,
    division,
    )
nstr = str
str = type('')
try:
    from itertools import izip as zip
except ImportError:
    pass
try:
    from SocketServer import TCPServer, ForkingMixIn
except ImportError:
    from socketserver import TCPServer, ForkingMixIn
from functools import reduce
try:
    range = xrange
except NameError:
    pass
from __future__ import (
    unicode_literals,
    absolute_import,
    print_function,
    division,
    )
nstr = str
str = type('')
try: # Py 2
    from itertools import izip as zip
    from SocketServer import TCPServer, ForkingMixIn
    range = xrange
except ImportError: # Py 3
    from socketserver import TCPServer, ForkingMixIn
from functools import reduce
open('myfile.txt', 'rb')
stream = StringIO.StringIO()
d = {1: 'a'}
d.iteritems()
io.open('myfile.txt', 'rb')
stream = io.BytesIO()
d = {1: 'a'}
d.items()
print 'Hello world!'
print >>sys.stderr, "Oh noes!"
print("Hello world!")
print("Oh noes!", file=sys.stderr)
class MyClass:
    def __init__(self, foo):
        super().__init__()
class MyClass(object):
    def __init__(self, foo):
        super(MyClass, self).__init__()
try:
    1 / 0
except ZeroDivisionError, e:
    print "Well, that was expected"
except ValueError, IOError:
    print "Weird"
try:
    1 / 0
except ZeroDivisionError as e:
    print("Well, that was expected")
except (ValueError, IOError):
    print("Weird")
raise "Something went wrong!"
raise Exception("Something went wrong!")
a, *b, c = [1, 2, 3, 4, 5]
def f(a, *, foo=2, bar=3):
    pass
io.open('myfile.txt', 'x')
from math import isclose
import statistics

a = b @ x

Vitalstatistix

Name
Dave Jones
Occupation
Perpetual Upgrader
Twitter
@waveform80
GitHub
github.com/waveform80

Thank You

Questions?