Jump to: navigation, search

Difference between revisions of "Python3"

(OpenStack clients: neutronclient now supports Python3!)
(Common Libraries (Oslo Projects))
Line 262: Line 262:
| [https://pypi.python.org/pypi/oslo.config oslo.config] || style="background-color: lightgreen;" | Yes ||
| [https://pypi.python.org/pypi/oslo.config oslo.config] || style="background-color: lightgreen;" | Yes ||
| [https://pypi.python.org/pypi/oslo.db oslo.db] || style="background-color: red;" | No || Many unit tests are failing
| [https://pypi.python.org/pypi/oslo.db oslo.db] || style="background-color: orange;" | Partial || No unit tests with MySQL because of DB driver
| [https://pypi.python.org/pypi/oslo.i18n oslo.i18n] || style="background-color: lightgreen;" | Yes ||
| [https://pypi.python.org/pypi/oslo.i18n oslo.i18n] || style="background-color: lightgreen;" | Yes ||

Revision as of 15:29, 14 January 2015

This page tracks the progress of Python 3 effort porting for OpenStack.

Python 3

Why should OpenStack move to Python 3 right now?

Python 3 is usually seen as the new Python version which breaks compatibility and raises new Unicode issues. Python 3 is much more than that. It’s a new clean language which has a more consistent syntax. It has many new features, not less than 15 new modules. Python 3 is already well supported by major Linux distributions, whereas Python 2.7 reached its end-of-life. Slowly, some bugs cannot be fixed in Python 2.7 anymore and are only fixed in the latest Python 3 release. Python 3 is now 5 years old and considered as a mature programming language.

Port Python 2 code to Python 3

OpenStack project chose to use the same code base for Python 2 and Python 3. The Six: Python 2 and 3 Compatibility Library helps to write code working on both versions. OpenStack supported Python 2.6 for RHEL up to Juno, but not Python 2.5 and older. Debian Stable provides Python 3 but only Python 3.2, so u'unicode' syntax should be avoided (use six.u('unicode') instead).

Common patterns

  • Replace dict.iteritems() with six.iteritems(dict)
  • Replace iterator.next() with next(iterator)
  • Replace basestring with six.string_types
  • Replace unicode with six.text_type

bytes.decode and unicode.encode

Python has a notion of "default encoding": sys.getdefaultencoding(). On Python 2, the default encoding is ASCII, whereas it is UTF-8 on Python 3.

Don't write data.decode() or text.encode() without parameter, because you will use a different encoding on Python 2 and Python 3.

Use an explicit encoding instead. Example: data.decode('utf-8') or text.encode('utf-8'). The right encoding depends on the use case, but UTF-8 is usually a good candidate (it is a superset of ASCII).


Olso Incubator has a function safe_decode() which can be used to decode a bytes string and pass text strings unchanged.

The default encoding is sys.stdin.encoding or sys.getdefaultencoding():

  • Python 3: the locale encoding, or UTF-8 if sys.stdin is "mocked" (io.StringIO instance)
  • Python 2: the locale encoding, or ASCII if stdin is not a TTY or if sys.stdin is "mocked" (StringIO.StringIO instance)

It's safer to explicit the encoding to not rely on the locale encoding and have the same behaviour even if sys.stdin is "mocked".

Safe usage:

  • safe_decode(data, 'utf-8'): decode bytes from UTF-8 or returns data unchanged if it's already a text string

Unsafe usage:

  • safe_decode(data)

By default, the decoder is strict. You can specify a different error handler using the optional errors parameter. Example: safe_decode(b'[\xff]', 'ascii', 'ignore') returns '[]'.


Olso Incubator has a function safe_encode() which can be used to encode a string. Its usage is tricky and you should understand how it works and which encodings are used.

  • safe_encode(text) encodes text to the output encoding
  • safe_encode(bytes) may decode the string and then reencode to a different encoding if input and output encodings are different

The default input encoding (incomding parameter) is sys.stdin.encoding or sys.getdefaultencoding():

  • Python 3: the locale encoding, or UTF-8 if sys.stdin is "mocked" (io.StringIO instance)
  • Python 2: the locale encoding, or ASCII if stdin is not a TTY or if sys.stdin is "mocked" (StringIO.StringIO instance)

The default output encoding (encoding parameter) is UTF-8.

It's safer to explicit the input encoding to not rely on the locale encoding and have the same behaviour even if sys.stdin is "mocked".

Safe usage:

  • safe_encode(data, incoming='utf-8'): encode text to UTF-8 or returns data unchanged if it's already a bytes string (since the input and output encoding are UTF-8)

Unsafe usage:

  • safe_encode(data)


  • safe_encode(b'\xe9', incoming='latin-1') returns b'\xc3\xa9'.

By default, the encoder and the decoder are strict. You can specify a different error handler using the optional errors parameter. Example: safe_encode(b'[\xff]', incoming='ascii', errors='ignore') returns b'[]'.

logging module and format exceptions

On Python 2, the logging module accepts bytes and text strings. On Python 3, it only accepts text strings. For example, logging.error(b'hello') logs b'hello' instead of 'hello'.

There is no clear rule for format exceptions yet. There are different choices depending on the project:

  • str(exc): native string, so use bytes on Python 2
  • six.text_type(exc): always use Unicode. It may raise unicode error depending on the exception, be careful. Example of such error in python 2: unicode(Exception("nonascii:\xe9")).
  • six.u(str(exc)): unsafe on Python 2 if str(exc) contains non-ASCII bytes, ex: unicode(str(Exception("\xff")))
  • LOG.exception(_LE("... %(exc)s ..."), {"exc": exc, ...})

Since logging functions expect text strings on Python 3, logged exceptions should be formatted using str(exc). Example: LOG.debug(str(exc)).


The HTTP protocol is based on bytes:

  • HTTP body contains bytes. For example, use io.BytesIO for a stream storing an HTTP body.
  • HTTPConnection.getresponse().read() returns bytes (in Python 3, str which is bytes in Python 2)
  • On Python 3, the http.client accepts text for HTTP headers: keys are encoded to ASCII and values to ISO 8859-1 (which is only a small subset of the Unicode charset)
  • It looks like Swift encodes internally HTTP headers to UTF-8 (directly using the UTF-8 encoding, not using a MIME encoding like =?UTF-8?Q?...?=. See the HTTP [RFC 2047 http://www.ietf.org/rfc/rfc2047.txt] and HTTP header should use what character encoding?

References to port Python 2 code to Python 3

Common pitfalls

What is a string ?

You should definitely not talk about "strings" in your commit logs/reviews. In Python 2, a 'string' is bytes; in Python 3, it's a Unicode text string. The following code snippet may help in understanding the difference:

Python 2:

   >>> type('foo')
   <type 'str'>
   >>> type(u'foo')
   <type 'unicode'>
   >>> type(b'foo')
   <type 'str'>
   >>> isinstance('foo', six.text_type)
   >>> isinstance(u'foo', six.text_type)
   >>> bytes is str
   >>> b'foo'[0]

Python 3:

   >>> type('foo')
   <class 'str'>
   >>> type(u'foo')
   <class 'str'>
   >>> type(b'foo')
   <class 'bytes'>
   >>> isinstance('foo', six.text_type)
   >>> isinstance(b'foo', six.text_type)
   >>> bytes is str
   >>> b'foo'[0]

tox/testr error: db type could not be determined

The "db type could not be determined" error comes from .testrepository/times.dbm used by testr.

Workaround: "rm -rf .testrepository/".

Python 3 Status of OpenStack projects

Oslo Incubator

BLOCKER BUG: Tests using testscenarios fail on Python 3 with nosetests because of this bug: https://bugs.launchpad.net/testscenarios/+bug/872887

Recently merged reviews:

Test (full path) Patches Comment
tests/unit/config/test_generator.py https://review.openstack.org/#/c/88087/
tests/unit/crypto/test_utils.py https://review.openstack.org/87413
tests/unit/db/sqlalchemy/test_migration_common.py https://review.openstack.org/#/c/107752/
tests/unit/db/sqlalchemy/test_migrate.py https://review.openstack.org/#/c/107921/
tests/unit/db/sqlalchemy/test_models.py https://review.openstack.org/#/c/80307/
tests/unit/db/sqlalchemy/test_options.py https://review.openstack.org/#/c/80627/
tests/unit/db/sqlalchemy/test_migrate_cli.py https://review.openstack.org/107988
tests/unit/fixture/test_logging.py https://review.openstack.org/#/c/90318/
tests/unit/middleware/test_request_id.py https://review.openstack.org/#/c/80336/
tests/unit/middleware/test_sizelimit.py https://review.openstack.org/#/c/80450/
tests/unit/middleware/test_audit.py depends on pycadf
tests/unit/reports/test_guru_meditation_report.py https://review.openstack.org/#/c/87404/
tests/unit/reports/test_base_report.py https://review.openstack.org/#/c/87973/
tests/unit/reports/test_openstack_generators.py https://review.openstack.org/#/c/88124/
tests/unit/reports/test_views.py https://review.openstack.org/87376
tests/unit/rpc/test_common.py https://review.openstack.org/#/c/80533/ The RPC code in the incubator is deprecated in favor of oslo.messaging. --doug-hellmann (talk) 15:40, 14 April 2014 (UTC)
tests/unit/scheduler/test_base_filter.py https://review.openstack.org/#/c/80321/
tests/unit/scheduler/test_weights.py https://review.openstack.org/#/c/87336/
tests/unit/test_cliutils https://review.openstack.org/#/c/74433/
tests/unit/test_fileutils https://review.openstack.org/#/c/74728/
tests/unit/test_gettext.py https://review.openstack.org/#/c/80534/
tests/unit/test_imageutils.py https://review.openstack.org/#/c/90532/
tests/unit/test_jsonutils.py https://review.openstack.org/#/c/80370/
tests/unit/test_log.py https://review.openstack.org/104890
tests/unit/test_processutils.py processutils was moved to the new oslo.concurrency project
tests/unit/test_quota.py https://review.openstack.org/#/c/80564/

Common Libraries (Oslo Projects)

For the list of Common Libraries, see http://git.openstack.org/cgit/openstack/governance/tree/reference/programs.yaml#n160

Project Python 3 compatibility Comment
cliff Yes
oslo.concurrency Partial https://review.openstack.org/141206
oslo.config Yes
oslo.db Partial No unit tests with MySQL because of DB driver
oslo.i18n Yes
oslo.log Yes
oslo.messaging Yes eventlet executor and qpid driver are not supported on Python 3, greenio

executor may help

oslo.middleware Yes
oslo.rootwrap Yes
oslo.serialization Yes
oslosphinx  ? The project only contains two short .py files, it looks to be Python 3 compatible. Is Sphinx Python 3 compatible?
oslotest Yes
oslo.vmware No Blocked suds dependency
oslo.utils Yes
oslo.version Yes not released on PyPI yet
pylockfile Yes related to https://pypi.python.org/pypi/lockfile ?
stevedore Yes
taskflow Yes

Development tools:

Project Python 3 compatibility Comment
cookiecutter  ?
oslo-cookiecutter  ?
hacking  ?
pbr  ?

OpenStack clients

Project Python 3 compatibility CI tests running? Python 3 classifiers ? Blocked by Comment
python-barbicanclient Yes Voting In the git repo, not on PyPI
python-ceilometerclient Yes Voting On PyPI
python-cinderclient Yes Voting On PyPI
python-ganttclient  ?  ?  ?  ?
python-glanceclient Yes Voting On PyPI
python-heatclient Yes Voting On PyPI
python-ironicclient Yes Voting On PyPI
python-keystoneclient Yes Voting On PyPI
python-marconiclient Yes Voting Yes
python-melangeclient  ?  ?  ?
python-novaclient Yes Voting On PyPII
python-neutronclient Yes Non-voting Yes
python-openstackclient OK Voting Yes As of 0.9
python-saharaclient In progress Non-voting https://review.openstack.org/#/c/73128/
python-swiftclient Yes Voting On PyPI
python-tuskarclient Yes Voting On PyPI
python-troveclient Yes Voting On PyPI

Core OpenStack projects

Completely updated on Monday, September the 29th.

Project Python 3 compatibility CI tests running? Trove classifiers Blocked by Comment
ceilometer No No No


  • croniter
  • eventlet
  • thrift (which is blocking happybase)
  • oslo.db
  • oslo.messaging
  • python-neutronclient
  • sqlalchemy-migrate

Requirements for tests

  • mysql-python
  • sphinxcontrib-docbookrestapi
  • sphinxcontrib-httpdomain
  • sphinxcontrib-pecanwsme
cinder No No No


  • eventlet
  • oslo.db
  • oslo.messaging
  • paste
  • python-barbicanclient
  • rtslib-fb
  • sqlalchemy-migrate
  • suds
  • taskflow

Requirements for tests

  • mysql-python
glance No No No


  • eventlet
  • glance_store
  • oslo.db
  • oslo.messaging
  • paste
  • sqlalchemy-migrate

Requirements for tests

  • mysql-python
  • qpid-python
heat No No No


  • eventlet
  • oslo.db
  • oslo.messaging
  • python-neutronclient
  • python-saharaclient
  • qpid-python
  • sqlalchemy-migrate

Requirements for tests

  • mysql-python
horizon No No No


  • django-pyscss
  • eventlet
  • python-neutronclient
  • python-saharaclient
  • xstatic
  • xstatic-angular
  • xstatic-angular-cookies
  • xstatic-angular-mock
  • xstatic-bootstrap-datepicker
  • xstatic-d3
  • xstatic-font-awesome
  • xstatic-hogan
  • xstatic-jasmine
  • xstatic-jquery
  • xstatic-jquery-migrate
  • xstatic-jquery.quicksearch
  • xstatic-jquery.tablesorter
  • xstatic-jsencrypt
  • xstatic-qunit
  • xstatic-rickshaw
  • xstatic-spin

Requirements for tests

  • nodeenv
  • nose-exclude
  • nosehtmloutput
  • openstack.nose_plugin
keystone No No No
  • eventlet
  • oslo.db
  • oslo.messaging
  • paste
  • pycadf
  • sqlalchemy-migrate

Requirements for tests

  • ldappool
  • paste (which is blocking pysaml2)
  • python-ldap
neutron No No No


  • eventlet
  • jsonrpclib
  • oslo.db
  • oslo.messaging
  • paste
  • python-neutronclient
nova No No No
  • eventlet
  • oslo.db
  • oslo.messaging
  • paste
  • pycadf
  • python-neutronclient
  • sqlalchemy-migrate
  • suds
  • websockify

Requirements for tests

  • libvirt-python
  • mysql-python
swift No No No


  • eventlet

Requirements for tests

  • nosehtmloutput
  • openstack.nose_plugin

Number of core OpenStack projetcs blocked by each dependency:

     9 eventlet
     7 oslo.messaging
     7 oslo.db
     6 sqlalchemy-migrate
     6 paste
     5 python-neutronclient
     5 mysql-python
     2 suds
     2 qpid-python
     2 python-saharaclient
     2 pycadf
     2 openstack.nose_plugin
     2 nosehtmloutput
     1 xstatic-spin
     1 xstatic-rickshaw
     1 xstatic-qunit
     1 xstatic-jsencrypt
     1 xstatic-jquery.tablesorter
     1 xstatic-jquery.quicksearch
     1 xstatic-jquery-migrate
     1 xstatic-jquery
     1 xstatic-jasmine
     1 xstatic-hogan
     1 xstatic-font-awesome
     1 xstatic-d3
     1 xstatic-bootstrap-datepicker
     1 xstatic-angular-mock
     1 xstatic-angular-cookies
     1 xstatic-angular
     1 xstatic
     1 websockify
     1 thrift
     1 taskflow
     1 sphinxcontrib-pecanwsme
     1 sphinxcontrib-httpdomain
     1 sphinxcontrib-docbookrestapi
     1 rtslib-fb
     1 python-ldap
     1 python-barbicanclient
     1 nose-exclude
     1 nodeenv
     1 libvirt-python
     1 ldappool
     1 jsonrpclib
     1 glance_store
     1 django-pyscss
     1 croniter


Porting status for global-requirement.txt.

It's now possible to specify different dependencies for Python 2 and Python 3 using:

  • requirements-py2.txt: all dependencies for Python 2 (not only dependencies specific to Python 2)
  • requirements-py3.txt: all dependencies for Python 3 (not only dependencies specific to Python 3)
  • (same for test-requirements.txt)

You have to edit tox.ini to specify the right requirements file. Extract of a tox.ini file:

deps = -r{toxinidir}/requirements-py3.txt

See also a patch to support markers in requirements (in pip): pip issue: Support markers in setup(install_requires)?; Victor Stinner's pull request: "parse requirements in markers"

OpenStack Dependencies:

Project Python 3 compatibility CI tests running? Python 3 classifiers ? Blocked by Comment
boto Yes N/A Yes See https://github.com/boto/boto3 (experimental) <- This seems dead, and https://github.com/boto/boto works with Python 3.x (since 2.32).
django-compressor Yes N/A Yes Requirements upgraded: https://review.openstack.org/94357
django-openstack-auth Yes N/A Yes

As of 1.1.6

dnspython Yes N/A Yes Must use the Python 3 version, see https://github.com/rthalley/dnspython/issues/60
ecdsa Yes N/A In the Git repo Py3 support merge before the 0.10 release (see https://github.com/warner/python-ecdsa/commits/master)
eventlet No No No eventlet portage to Python 3 in progress: eventlet issue #6: Support Python 3.3 and Pull request #99: Fix several issues with python3 thread patching. Victor Stinner is working on Trollius (asyncio for Python 2) which may replace eventlet: Use the new asyncio module and Trollius in OpenStack
hacking No No No Cyril Roelandt patch: Make hacking Python 3 compatible
jsonrpclib No N/A No The project seems dead :(
mysql-python No No No 2 pull requests for Python 3 (https://github.com/farcepest/MySQLdb1/pulls). The projects is being renamed to moist (https://github.com/farcepest/moist), Python 3 support might happen there.
netifaces Yes N/A Yes Patch sent by Victor Stinner (in private): netifaces_python3.patch, Debian has patches too. Python 3 support as of 0.10.4. Pushed to requirements: https://review.openstack.org/94358 .
nose-exclude No No No https://bitbucket.org/kgrandis/nose-exclude/issue/10/test-failures-with-python-3
nosehtmloutput No No No
  • nose-exclude (tests only)
  • openstack.nose-plugin
nosexcover No N/A On PyPI Python 3 support since 1.0.9
openstack.nose-plugin No No No
oslo.vmware No Voting Yes suds
oslo.config Yes Voting On PyPI
oslo.messaging No No No Portage in Progress by Victor Stinner (dashboard)
oslo.rootwrap Yes Yes In the Git repo, not on PyPI (1.1.0)
oslosphinx Yes No tests :) In the git repo, not on PyPI https://review.openstack.org/#/c/79311/
oslo.sphinx No No No Must be replaced by oslosphinx (without the dot)
pam No No No The fork simplepam works on Python 2 and 3
paramiko Yes N/A On PyPI   Requirements upgraded: https://review.openstack.org/#/c/81132/
paste No No No https://bitbucket.org/ianb/paste/pull-request/9/python-3-support/diff
pycadf No No No Classifiers added https://review.openstack.org/#/c/133088/
python-ldap No No No The project seems dead.
python-memcached Not released, but last commit on git has it No No Issue #52: Python 3.3 support? , Pull request #26: Python 3.3 Support -- Julien Danjou ported pymemcache to Python 3, another memcached client, he suggests to use this one instead
qpid-python No No No
rtslib-fb No No No
sphinxcontrib-docbookrestapi No No No
sphinxcontrib-httpdomain No No No
sphinxcontrib-pecanwsme No No No
sqlalchemy-migrate No No No
  • hacking
  • ibm-db-sa
  • scripttest
suds No No No "Lightweight SOAP client". Last commit 2 years ago: https://fedorahosted.org/suds/browser See also this fork which is promising: https://bitbucket.org/jurko/suds
taskflow Yes Yes Yes
thrift No No No
websockify No No No

Other OpenStack projects

Python 3 compatible:

Reports at OpenStack Summits

Pycon Montreal 2014: Sprint Port OpenStack to Python 3

Enovance organizes a sprint to Port OpenStack to Python 3 during 4 days: between April, 14 (Monday) and April, 17 (Thursday). See the page Python3/SprintPycon2014.