django/docs/topics/python3.txt

50 lines
1.6 KiB
Plaintext
Raw Normal View History

======================
Python 3 compatibility
======================
Django 1.5 is the first version of Django to support Python 3.
The same code runs both on Python 2 (≥2.6.5) and Python 3 (≥3.2). To
achieve this:
- wherever possible, Django uses the six_ compatibility layer,
- all modules declare ``from __future__ import unicode_literals``.
.. _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.
.. _Python's official porting guide: http://docs.python.org/py3k/howto/pyporting.html
.. module: django.utils.six
django.utils.six
================
Read the documentation of six_. It's the canonical compatibility library for
supporting Python 2 and 3 in a single codebase.
``six`` is bundled with Django: you can import it as :mod:`django.utils.six`.
.. _string-handling:
String handling
===============
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__``::
from __future__ import unicode_literals
my_string = "This is an unicode literal"
my_bytestring = b"This is a bytestring"
Be cautious if you have to `slice bytestrings`_.
.. _slice bytestrings: http://docs.python.org/py3k/howto/pyporting.html#bytes-literals