Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

[py3] Added python_2_unicode_compatible decorator.

  • Loading branch information...
commit a0a0203a392f67832ba7a8a2f099e70d7db2d19e 1 parent e7e08fd
Aymeric Augustin aaugustin authored
Showing with 21 additions and 0 deletions.
  1. +13 −0 django/utils/encoding.py
  2. +8 −0 docs/ref/utils.txt
13 django/utils/encoding.py
View
@@ -39,6 +39,19 @@ def __str__(self):
def __str__(self):
return self.__unicode__().encode('utf-8')
+def python_2_unicode_compatible(klass):
+ """
+ A decorator that defines __unicode__ and __str__ methods under Python 2.
+ Under Python 3 it does nothing.
+
+ To support Python 2 and 3 with a single code base, define a __str__ method
+ returning text and apply this decorator to the class.
+ """
+ if not six.PY3:
+ klass.__unicode__ = klass.__str__
+ klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
+ return klass
+
def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a text object representing 's' -- unicode on Python 2 and str on
8 docs/ref/utils.txt
View
@@ -187,6 +187,14 @@ The functions defined in this module share the following properties:
Useful as a mix-in. If you support Python 2 and 3 with a single code base,
you can inherit this mix-in and just define ``__unicode__``.
+.. function:: python_2_unicode_compatible
+
+ A decorator that defines ``__unicode__`` and ``__str__`` methods under
+ Python 2. Under Python 3 it does nothing.
+
+ To support Python 2 and 3 with a single code base, define a ``__str__``
+ method returning text and apply this decorator to the class.
+
.. function:: smart_text(s, encoding='utf-8', strings_only=False, errors='strict')
.. versionadded:: 1.5
Please sign in to comment.
Something went wrong with that request. Please try again.