From 31bb060cf15425eee88a43b1239c90c0d023186f Mon Sep 17 00:00:00 2001 From: Thomas Grainger Date: Thu, 11 Sep 2014 23:03:54 +0100 Subject: Add python_2_unicode_comaptible from Django --- six.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) 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. -- cgit v1.2.1