2012-06-08 00:36:26 +08:00
|
|
|
======================
|
|
|
|
Python 3 compatibility
|
|
|
|
======================
|
|
|
|
|
2012-07-20 17:32:38 +08:00
|
|
|
Django 1.5 is the first version of Django to support Python 3.
|
2012-06-08 00:36:26 +08:00
|
|
|
|
2012-07-20 17:32:38 +08:00
|
|
|
The same code runs both on Python 2 (≥2.6.5) and Python 3 (≥3.2). To
|
|
|
|
achieve this:
|
2012-06-08 00:36:26 +08:00
|
|
|
|
2012-07-20 17:32:38 +08:00
|
|
|
- wherever possible, Django uses the six_ compatibility layer,
|
|
|
|
- all modules declare ``from __future__ import unicode_literals``.
|
2012-06-08 00:36:26 +08:00
|
|
|
|
2012-07-20 17:32:38 +08:00
|
|
|
.. _six: http://packages.python.org/six/
|
|
|
|
|
|
|
|
This document is not meant as a Python 2 to Python 3 migration guide. There
|
|
|
|
are many existing resources, including `Python's official porting guide`_. But
|
|
|
|
it describes guidelines that apply to Django's code and are recommended for
|
|
|
|
pluggable apps that run with both Python 2 and 3.
|
2012-06-08 00:36:26 +08:00
|
|
|
|
2012-07-20 17:32:38 +08:00
|
|
|
.. _Python's official porting guide: http://docs.python.org/py3k/howto/pyporting.html
|
2012-06-08 00:36:26 +08:00
|
|
|
|
2012-07-20 17:32:38 +08:00
|
|
|
.. module: django.utils.six
|
2012-06-08 00:36:26 +08:00
|
|
|
|
2012-07-20 17:32:38 +08:00
|
|
|
django.utils.six
|
|
|
|
================
|
2012-06-08 00:36:26 +08:00
|
|
|
|
2012-07-20 17:32:38 +08:00
|
|
|
Read the documentation of six_. It's the canonical compatibility library for
|
|
|
|
supporting Python 2 and 3 in a single codebase.
|
2012-06-08 00:36:26 +08:00
|
|
|
|
2012-07-20 17:32:38 +08:00
|
|
|
``six`` is bundled with Django: you can import it as :mod:`django.utils.six`.
|
2012-06-08 00:36:26 +08:00
|
|
|
|
2012-07-20 17:32:38 +08:00
|
|
|
.. _string-handling:
|
2012-06-08 00:36:26 +08:00
|
|
|
|
|
|
|
String handling
|
|
|
|
===============
|
|
|
|
|
2012-07-20 17:32:38 +08:00
|
|
|
In Python 3, all strings are considered Unicode strings by default. Byte
|
|
|
|
strings must be prefixed with the letter ``b``. In order to enable the same
|
|
|
|
behavior in Python 2, every module must import ``unicode_literals`` from
|
|
|
|
``__future__``::
|
2012-06-08 00:36:26 +08:00
|
|
|
|
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
|
|
|
my_string = "This is an unicode literal"
|
|
|
|
my_bytestring = b"This is a bytestring"
|
|
|
|
|
2012-07-20 17:32:38 +08:00
|
|
|
Be cautious if you have to `slice bytestrings`_.
|
2012-06-08 00:36:26 +08:00
|
|
|
|
2012-07-20 17:32:38 +08:00
|
|
|
.. _slice bytestrings: http://docs.python.org/py3k/howto/pyporting.html#bytes-literals
|