summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorThomas Grainger <tagrain@gmail.com>2014-09-11 23:03:54 +0100
committerThomas Grainger <tagrain@gmail.com>2014-09-11 23:03:54 +0100
commit31bb060cf15425eee88a43b1239c90c0d023186f (patch)
tree107953615c175f468ad2a8f9640c70b5b7c7c528
parenta3394da14890d2f445052bde47a5352d16d888e3 (diff)
downloadsix-31bb060cf15425eee88a43b1239c90c0d023186f.tar.gz
Add python_2_unicode_comaptible from Django
-rw-r--r--six.py19
1 files changed, 19 insertions, 0 deletions
diff --git a/six.py b/six.py
index 21b0e80..35530a3 100644
--- a/six.py
+++ b/six.py
@@ -737,6 +737,25 @@ def add_metaclass(metaclass):
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper
+
+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 six.PY2:
+ if '__str__' not in klass.__dict__:
+ raise ValueError("@python_2_unicode_compatible cannot be applied "
+ "to %s because it doesn't define __str__()." %
+ klass.__name__)
+ klass.__unicode__ = klass.__str__
+ klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
+ return klass
+
+
# Complete the moves implementation.
# This code is at the end of this module to speed up module loading.
# Turn this module into a package.