Merge remote-tracking branch 'refs/remotes/breton/bug/647'
[mediagoblin.git] / mediagoblin / _compat.py
index fd6172fdd78cf9473bcc4a6744cdc3a7207eb5ae..9164d5fcebb78e132675edfb3eea6723fe073659 100644 (file)
@@ -1,23 +1,32 @@
-import sys
+import functools
+import warnings
 
-from six import PY3, iteritems
+import six
 
-from mediagoblin import mg_globals
-
-if PY3:
+if six.PY3:
     from email.mime.text import MIMEText
-    from urllib import parse as urlparse
-    ugettext = mg_globals.thread_scope.translations.gettext
-    ungettext = mg_globals.thread_scope.translations.ngettext
 else:
     from email.MIMEText import MIMEText
-    import urlparse
-    ugettext = mg_globals.thread_scope.translations.ugettext
-    ungettext = mg_globals.thread_scope.translations.ungettext
 
 
+def encode_to_utf8(method):
+    def wrapper(self):
+        if six.PY2 and isinstance(method(self), six.text_type):
+            return method(self).encode('utf-8')
+        return method(self)
+    functools.update_wrapper(wrapper, method, ['__name__', '__doc__'])
+    return wrapper
+
+
+# based on django.utils.encoding.python_2_unicode_compatible
 def py2_unicode(klass):
-    if not PY3:
+    if six.PY2:
+        if '__str__' not in klass.__dict__:
+            warnings.warn("@py2_unicode 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')
+        klass.__str__ = encode_to_utf8(klass.__unicode__)
+        if '__repr__' in klass.__dict__:
+            klass.__repr__ = encode_to_utf8(klass.__repr__)
     return klass