]> git.ipfire.org Git - thirdparty/jinja.git/commitdiff
Added unicode mixin for unified string logic
authorArmin Ronacher <armin.ronacher@active-4.com>
Sun, 19 May 2013 13:43:18 +0000 (14:43 +0100)
committerArmin Ronacher <armin.ronacher@active-4.com>
Sun, 19 May 2013 13:43:18 +0000 (14:43 +0100)
jinja2/_compat.py
jinja2/environment.py
jinja2/exceptions.py
jinja2/runtime.py
jinja2/testsuite/filters.py

index d770f1a6b7bb9a2d01c9a1a826ddaaea025672ca..f72e99b60f972376b879cf8529bdb9a561f9fb73 100644 (file)
@@ -38,6 +38,11 @@ if not PY2:
         raise value
 
     Iterator = object
+
+    class UnicodeMixin(object):
+        __slots__ = ()
+        def __str__(self):
+            return self.__unicode__()
 else:
     text_type = unicode
     unichr = unichr
@@ -56,7 +61,13 @@ else:
 
     exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
 
+    class UnicodeMixin(object):
+        __slots__ = ()
+        def __str__(self):
+            return self.__unicode__().encode('utf-8')
+
     class Iterator(object):
+        __slots__ = ()
         def next(self):
             return self.__next__()
 
index cbac8c1c53f56fb88a86097eaa762befdb5b4c24..bf56d0fcdddc7e021448377b8adca2761364bc63 100644 (file)
@@ -28,7 +28,7 @@ from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \
 from jinja2.utils import import_string, LRUCache, Markup, missing, \
      concat, consume, internalcode, _encode_filename
 from jinja2._compat import imap, ifilter, string_types, iteritems, \
-     text_type, reraise, PY2, Iterator, next
+     text_type, reraise, Iterator, next, UnicodeMixin
 from functools import reduce
 
 
@@ -1051,7 +1051,7 @@ class Template(object):
         return '<%s %s>' % (self.__class__.__name__, name)
 
 
-class TemplateModule(object):
+class TemplateModule(UnicodeMixin):
     """Represents an imported template.  All the exported names of the
     template are available as attributes on this object.  Additionally
     converting it into an unicode- or bytestrings renders the contents.
@@ -1068,13 +1068,6 @@ class TemplateModule(object):
     def __unicode__(self):
         return concat(self._body_stream)
 
-    if PY2:
-        def __str__(self):
-            return self.__unicode__().encode('utf-8')
-    else:
-        __str__ = __unicode__
-        del __unicode__
-
     def __repr__(self):
         if self.__name__ is None:
             name = 'memory:%x' % id(self)
index 1bbceeea5aaf1dbfb74bd72ae48a48a339edee5c..4d12a4738cadce0569445538bffe9ae78d50c503 100644 (file)
@@ -8,7 +8,7 @@
     :copyright: (c) 2010 by the Jinja Team.
     :license: BSD, see LICENSE for more details.
 """
-from jinja2._compat import imap, text_type, PY2
+from jinja2._compat import imap, text_type, PY2, UnicodeMixin
 
 
 class TemplateError(Exception):
@@ -36,7 +36,7 @@ class TemplateError(Exception):
                     return message
 
 
-class TemplateNotFound(IOError, LookupError, TemplateError):
+class TemplateNotFound(IOError, LookupError, TemplateError, UnicodeMixin):
     """Raised if a template does not exist."""
 
     # looks weird, but removes the warning descriptor that just
@@ -51,13 +51,6 @@ class TemplateNotFound(IOError, LookupError, TemplateError):
         self.name = name
         self.templates = [name]
 
-    def __str__(self):
-        return self.message.encode('utf-8')
-
-    # unicode goes after __str__ because we configured 2to3 to rename
-    # __unicode__ to __str__.  because the 2to3 tree is not designed to
-    # remove nodes from it, we leave the above __str__ around and let
-    # it override at runtime.
     def __unicode__(self):
         return self.message
 
@@ -78,7 +71,7 @@ class TemplatesNotFound(TemplateNotFound):
         self.templates = list(names)
 
 
-class TemplateSyntaxError(TemplateError):
+class TemplateSyntaxError(UnicodeMixin, TemplateError):
     """Raised to tell the user that there is a problem with the template."""
 
     def __init__(self, message, lineno, name=None, filename=None):
@@ -115,13 +108,6 @@ class TemplateSyntaxError(TemplateError):
 
         return u'\n'.join(lines)
 
-    if PY2:
-        def __str__(self):
-            return self.__unicode__().encode('utf-8')
-    else:
-        __str__ = __unicode__
-        del __unicode__
-
 
 class TemplateAssertionError(TemplateSyntaxError):
     """Like a template syntax error, but covers cases where something in the
index b5e203ff6e5bc6403d94ba337e9dcf02a33255e1..605de6aca40f8b750f1374991eeba002a34d86af 100644 (file)
@@ -15,7 +15,7 @@ from jinja2.utils import Markup, soft_unicode, escape, missing, concat, \
 from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \
      TemplateNotFound
 from jinja2._compat import next, imap, text_type, iteritems, Iterator, \
-     string_types, PY2
+     string_types, PY2, UnicodeMixin
 
 
 # these variables are exported to the template runtime
@@ -440,7 +440,7 @@ class Macro(object):
         )
 
 
-class Undefined(object):
+class Undefined(UnicodeMixin):
     """The default undefined type.  This undefined type can be printed and
     iterated over, but every other access will raise an :exc:`UndefinedError`:
 
@@ -501,13 +501,6 @@ class Undefined(object):
     def __unicode__(self):
         return u''
 
-    if PY2:
-        def __str__(self):
-            return self.__unicode__().encode('utf-8')
-    else:
-        __str__ = __unicode__
-        del __unicode__
-
     def __len__(self):
         return 0
 
@@ -547,10 +540,6 @@ class DebugUndefined(Undefined):
             )
         return u'{{ undefined value printed: %s }}' % self._undefined_hint
 
-    if not PY2:
-        __str__ = __unicode__
-        del __unicode__
-
 
 class StrictUndefined(Undefined):
     """An undefined that barks on print and iteration as well as boolean
@@ -572,12 +561,9 @@ class StrictUndefined(Undefined):
     UndefinedError: 'foo' is undefined
     """
     __slots__ = ()
-    __iter__ = __str__ = __len__ = __nonzero__ = __eq__ = \
+    __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = \
         __ne__ = __bool__ = Undefined._fail_with_undefined_error
 
-    if PY2:
-        __unicode__ = Undefined._fail_with_undefined_error
-
 
 # remove remaining slots attributes, after the metaclass did the magic they
 # are unneeded and irritating as they contain wrong data for the subclasses.
index c1f32c3a0a2c523d557614a2ac23f4bee165b92e..b432c609d56e21b87bb7be71999b95ca19129914 100644 (file)
@@ -12,7 +12,7 @@ import unittest
 from jinja2.testsuite import JinjaTestCase
 
 from jinja2 import Markup, Environment
-from jinja2._compat import text_type, PY2
+from jinja2._compat import text_type, UnicodeMixin
 
 env = Environment()
 
@@ -294,17 +294,11 @@ class FilterTestCase(JinjaTestCase):
         assert tmpl.render() == "['Bar', 'blah', 'foo']"
 
     def test_sort4(self):
-        class Magic(object):
+        class Magic(UnicodeMixin):
             def __init__(self, value):
                 self.value = value
             def __unicode__(self):
                 return text_type(self.value)
-            if PY2:
-                def __str__(self):
-                    return self.__unicode__().encode('utf-8')
-            else:
-                __str__ = __unicode__
-                del __unicode__
         tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')
         assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'