Python 3 compatibility

  • print is a function now : you can use the print statement as a function right now
  • coding: utf-8 is no longer necessary

Python future

apt-get install python-future

it enables us to use python libraries that are not present in python2.X:

from http.server import HTTPServer, SimpleHTTPRequestHandler

Using new features

from python2.X, using new python3.X libraries is possible:

from __future__ import something

Have a look at the future

String type

No longer use the type string:

>>> s = "sdfsdf"
>>> type(s)
<type 'str'>
>>>

Always use unicode:

>>> from __future__ import unicode_literals
>>> s = "sdfsdf"
>>> type(s)
<type 'unicode'>
>>>

Str and repr

In python 2.X, str() and repr() were two different things. Think about it as the same thing by now.

Backports

Argparse

Optparse is deprecated. Use Argparse instead. Agrparse has evolved, watch for the docs.

A lot of other librairies have evolved. Update your good practices. logging has evolved and can receive a dict object configuration.

Important

I’ve heard that some magic stuff enables us to use python3 libraries in python2.x

Renaming the libraries, for example:

import urllib2 as urllib

Anyway, keep in mind that the API is different and doesn’t exist in python2.x:

from urllib.request import urlopen
from urllib.error import HTTPError
  • os.system is finished, use
>>> subprocess.check_call(["ls", "-l"])
  • utf-8 : no declaration necessary
  • list(list_object)

list_object is an iterator now

  • change the she bang:

    #!/usr/bin/env python
    #!/usr/bin/env python3
    

Differences between python2 and python3

Compile optimisations

__pycache__ is a subfolder you will see in python3. Don’t be surprised.

The list type

>>> l = range(10)
>>> l
range(0, 10)
>>> for i in l:
...   print(i)
...
0
(...)
9
  • in python2:

    >>> l = range(10)
    >>> type(l)
    <type 'list'>
    >>>
    
  • in python3:

    >>> l2 = range(10)
    >>> type(l2)
    <class 'range'>
    

it is because it’s an iterator.