summaryrefslogtreecommitdiff
path: root/docs/topics/python3.txt
blob: e4bfc1bd9ccc64c6ab937fd75a9c179da5871a0a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
======================
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