Disclaimer: This notebook is going to focus on reasons to use Python 3 more than on the details of porting code. See https://lhcb.github.io/developkit-lessons/first-development-steps/06b-python.html for a more complete description and help porting.
Unicode
This is the most impactful, biggest change. All strings now default to Unicode instead of bytes. Supporting both unicode and bytes was originally a library challenge, but has mostly been solved.
- Enables unicode in more places, better supported
- No longer dual builds of Python (wide vs. narrow)
- Encoding/decoding often more explicit
- Can use in Python 2 with
from __future__ import unicode_literals
(careful!)
</font>
- Was originally much slower/more memory
- Encoding/decoding often more explicit
</font>
Print as a function
Python 3 changed print to a function. This means even the "Hello World" program changed!
- Can use print as a function/method name
- Easier redirection, ending, separator, flush
- Can replace print if needed
- Can use in Python 2 with
from __future__ import print_function
</font>
- Have to type two more chars for every print
- Lost "soft space" feature
</font>
%%python2
print "Hello world!"
print("Hello world!")
%%python2
print 1/2
print(1 / 2)
Removals
Python 3 removes several things that were either deprecated or in need of replacement.
- Classic style classes
- Tuple unpacking in function arguments (rarely used, replaced by new features)
- Backticks for repr (will not be used again)
- Comma syntax for exceptions (replaced by
as
a long time ago) - Removed
input
, renamedraw_input
toinput
Smaller changes
- Import now looks for system packages first (
from __future__ import absolute_import
) exec
is a function now- Metaclasses have a new syntax, more options for overriding class construction
nonlocal
variables added- Extended tuple unpacking
first, *rest = iterable
- Unified
int
andlong
- Added function annotations (and variable annotations in 3.6)
New syntax: Matrix multiplication operator (3.5)
A matrix multiplication operator was added: @
(mATrix). Not used in the standard library; provided for libraries like Numpy.
Before:
S = np.dot((np.dot(H, beta) - r).T,
np.dot(inv(np.dot(np.dot(H, V), H.T)), np.dot(H, beta) - r))
After:
S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)
print(f"1 + 2 = {1+2}")
a = {"b": None, "a": None, "c": None}
print(list(a))
%%python2
a = {'b': None, 'a': None, 'c': None}
print(list(a))