Make the runtime leak less of the version hacks
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 25a67d0 · Browse files · 9 files·+92 added−89 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+92 added−89 removed
- other:+92 added−89 removed
Provenance
- Commit
28c7488- Tree
fb21955- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
25a67d0
9 files changed+92 added−89 removed
modified:jinja2/testsuite/filters.py+4 added-3 removed
10 unmodified lines11 import unittest12 from jinja2.testsuite import JinjaTestCase13 14 from jinja2 import Markup, Environment15-from jinja2._compat import text_type, UnicodeMixin15+from jinja2._compat import text_type, implements_to_string16 17 env = Environment()18 19 273 unmodified lines293 tmpl = env.from_string('''{{ ['foo', 'Bar', 'blah']|sort }}''')294 assert tmpl.render() == "['Bar', 'blah', 'foo']"295 296 def test_sort4(self):297+ @implements_to_string297- class Magic(UnicodeMixin):298+ class Magic(object):299 def __init__(self, value):300 self.value = value300- def __unicode__(self):301+ def __str__(self):302 return text_type(self.value)303 tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')304 assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'305 196 unmodified linesmodified:jinja2/_compat.py+40 added-44 removed
19 unmodified lines20 range_type = range21 text_type = str22 string_types = (str,)23 24- _iterkeys = 'keys'25- _itervalues = 'values'26- _iteritems = 'items'24+ iterkeys = lambda d: iter(d.keys())25+ itervalues = lambda d: iter(d.values())26+ iteritems = lambda d: iter(d.items())27 28+ import pickle29 from io import BytesIO, StringIO30 NativeStringIO = StringIO31 31- ifilter = filter32- imap = map33- izip = zip34-32 def reraise(tp, value, tb=None):33 if value.__traceback__ is not tb:34 raise value.with_traceback(tb)35 raise value36 40- Iterator = object37+ ifilter = filter38+ imap = map39+ izip = zip40+ intern = sys.intern41 42- class UnicodeMixin(object):43- __slots__ = ()44- def __str__(self):45- return self.__unicode__()42+ implements_iterator = lambda x: x43+ implements_to_string = lambda x: x44+ get_next = lambda x: x.__next__45 else:47- text_type = unicode46 unichr = unichr47+ text_type = unicode48+ range_type = xrange49 string_types = (str, unicode)50 51- _iterkeys = 'iterkeys'52- _itervalues = 'itervalues'53- _iteritems = 'iteritems'51+ iterkeys = lambda d: d.iterkeys()52+ itervalues = lambda d: d.itervalues()53+ iteritems = lambda d: d.iteritems()54 55- from itertools import imap, izip, ifilter56- range_type = xrange57-58- from cStringIO import StringIO as BytesIO59- from StringIO import StringIO55+ import cPickle as pickle56+ from cStringIO import StringIO as BytesIO, StringIO57 NativeStringIO = BytesIO58 59 exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')60 64- class UnicodeMixin(object):65- __slots__ = ()66- def __str__(self):67- return self.__unicode__().encode('utf-8')61+ from itertools import imap, izip, ifilter62+ intern = intern63 69- class Iterator(object):70- __slots__ = ()71- def next(self):72- return self.__next__()64+ def implements_iterator(cls):65+ cls.next = cls.__next__66+ del cls.__next__67+ return cls68 69+ def implements_to_string(cls):70+ cls.__unicode__ = cls.__str__71+ cls.__str__ = lambda x: x.__unicode__().encode('utf-8')72+ return cls73+74+ get_next = lambda x: x.next75+76+77 try:78 next = next79 except NameError:80 def next(it):81 return it.next()82 83 84 def with_metaclass(meta, *bases):82- """Create a base class with a metaclass."""83- return meta('NewBase', bases, {})85+ class __metaclass__(meta):86+ __call__ = type.__call__87+ __init__ = type.__init__88+ def __new__(cls, name, this_bases, d):89+ if this_bases is None:90+ return type.__new__(cls, name, (), d)91+ return meta(name, bases, d)92+ return __metaclass__('<dummy_class>', None, {})93 85-def iterkeys(d, **kw):86- return iter(getattr(d, _iterkeys)(**kw))94 88-def itervalues(d, **kw):89- return iter(getattr(d, _itervalues)(**kw))90-91-def iteritems(d, **kw):92- return iter(getattr(d, _iteritems)(**kw))93-95 try:95- import cPickle as pickle96-except ImportError:97- import pickle98-99-try:96 from collections import Mapping as mapping_types97 except ImportError:98 import UserDict99 mapping_types = (UserDict.UserDict, UserDict.DictMixin, dict)19 unmodified linesmodified:jinja2/environment.py+9 added-6 removed
26 unmodified lines27 TemplatesNotFound, TemplateRuntimeError28 from jinja2.utils import import_string, LRUCache, Markup, missing, \29 concat, consume, internalcode, _encode_filename30 from jinja2._compat import imap, ifilter, string_types, iteritems, \31- text_type, reraise, Iterator, next, UnicodeMixin31+ text_type, reraise, implements_iterator, implements_to_string, \32+ get_next33 from functools import reduce34 35 36 # for direct template usage we have up to ten living environments1014 unmodified lines1051 name = repr(self.name)1052 return '<%s %s>' % (self.__class__.__name__, name)1053 1054 1055+@implements_to_string1054-class TemplateModule(UnicodeMixin):1056+class TemplateModule(object):1057 """Represents an imported template. All the exported names of the1058 template are available as attributes on this object. Additionally1059 converting it into an unicode- or bytestrings renders the contents.1060 """5 unmodified lines1066 1067 def __html__(self):1068 return Markup(concat(self._body_stream))1069 1068- def __unicode__(self):1070+ def __str__(self):1071 return concat(self._body_stream)1072 1073 def __repr__(self):1074 if self.__name__ is None:21 unmodified lines1096 rv = None1097 return rv1098 1099 1100+@implements_iterator1098-class TemplateStream(Iterator):1101+class TemplateStream(object):1102 """A template stream works pretty much like an ordinary python generator1103 but it can buffer multiple items to reduce the number of total iterations.1104 Per default the output is unbuffered which means that for every unbuffered1105 instruction in the template one unicode string is yielded.35 unmodified lines1141 fp.close()1142 1143 def disable_buffering(self):1144 """Disable the output buffering."""1142- self._next = lambda: next(self._gen)1145+ self._next = get_next(self._gen)1146 self.buffered = False1147 1148 def enable_buffering(self, size=5):1149 """Enable buffering. Buffer `size` items before yielding them."""19 unmodified lines1169 del buf[:]1170 c_size = 01171 1172 self.buffered = True1170- self._next = lambda: next(generator(lambda: next(self._gen)))1173+ self._next = get_next(generator(get_next(self._gen)))1174 1175 def __iter__(self):1176 return self1177 7 unmodified linesmodified:jinja2/exceptions.py+7 added-5 removed
6 unmodified lines7 8 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11-from jinja2._compat import imap, text_type, PY2, UnicodeMixin11+from jinja2._compat import imap, text_type, PY2, implements_to_string12 13 14 class TemplateError(Exception):15 """Baseclass for all template errors."""19 unmodified lines35 if message is not None:36 return message37 38 39+@implements_to_string39-class TemplateNotFound(IOError, LookupError, TemplateError, UnicodeMixin):40+class TemplateNotFound(IOError, LookupError, TemplateError):41 """Raised if a template does not exist."""42 43 # looks weird, but removes the warning descriptor that just44 # bogusly warns us about message being deprecated6 unmodified lines51 self.message = message52 self.name = name53 self.templates = [name]54 54- def __unicode__(self):55+ def __str__(self):56 return self.message57 58 59 class TemplatesNotFound(TemplateNotFound):11 unmodified lines71 TemplateNotFound.__init__(self, names and names[-1] or None, message)72 self.templates = list(names)73 74 75+@implements_to_string74-class TemplateSyntaxError(UnicodeMixin, TemplateError):76+class TemplateSyntaxError(TemplateError):77 """Raised to tell the user that there is a problem with the template."""78 79 def __init__(self, message, lineno, name=None, filename=None):80 TemplateError.__init__(self, message)5 unmodified lines86 # this is set to True if the debug.translate_syntax_error87 # function translated the syntax error into a new traceback88 self.translated = False89 88- def __unicode__(self):90+ def __str__(self):91 # for translated errors we only return the message92 if self.translated:93 return self.message94 47 unmodified linesmodified:jinja2/lexer.py+6 added-9 removed
18 unmodified lines19 from operator import itemgetter20 from collections import deque21 from jinja2.exceptions import TemplateSyntaxError22 from jinja2.utils import LRUCache23-from jinja2._compat import next, iteritems, Iterator, text_type23+from jinja2._compat import next, iteritems, implements_iterator, text_type, \24+ intern25 26 27 # cache for the lexers. Exists in order to be able to have multiple28 # environments with the same lexer18 unmodified lines47 48 float_re = re.compile(r'(?<!\.)\d+\.\d+')49 newline_re = re.compile(r'(\r\n|\r|\n)')50 50-try:51- intern = intern # py252-except NameError:53- import sys54- intern = sys.intern # py355-51 # internal the tokens and keep references to them52 TOKEN_ADD = intern('add')53 TOKEN_ASSIGN = intern('assign')54 TOKEN_COLON = intern('colon')209 unmodified lines264 self.value265 )266 267 268+@implements_iterator273-class TokenStreamIterator(Iterator):269+class TokenStreamIterator(object):270 """The iterator for tokenstreams. Iterate over the stream271 until the eof token is reached.272 """273 11 unmodified lines285 next(self.stream)286 return token287 288 289+@implements_iterator293-class TokenStream(Iterator):290+class TokenStream(object):291 """A token stream is an iterable that yields :class:`Token`\s. The292 parser however does not iterate over it but calls :meth:`next` to go293 one token ahead. The current active token is stored as :attr:`current`.294 """439 unmodified linesmodified:jinja2/runtime.py+13 added-13 removed
12 unmodified lines13 from jinja2.utils import Markup, soft_unicode, escape, missing, concat, \14 internalcode, object_type_repr15 from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \16 TemplateNotFound17-from jinja2._compat import next, imap, text_type, iteritems, Iterator, \18- string_types, PY2, UnicodeMixin17+from jinja2._compat import next, imap, text_type, iteritems, \18+ implements_iterator, implements_to_string, string_types19 20 21 # these variables are exported to the template runtime22 __all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',1 unmodified line24 'markup_join', 'unicode_join', 'to_string', 'identity',25 'TemplateNotFound']26 27 #: the name of the function that is used to convert something into28-#: a string. 2to3 will adopt that automatically and the generated29-#: code can take advantage of it.30-try:31- to_string = unicode32-except NameError:33- to_string = str28+#: a string. We can just use the text type here.29+to_string = text_type30 31 #: the identity function. Useful for certain things in the environment32 identity = lambda x: x33 317 unmodified lines351 self.length352 )353 354 355+@implements_iterator359-class LoopContextIterator(Iterator):356+class LoopContextIterator(object):357 """The iterator for a loop context."""358 __slots__ = ('context',)359 360 def __init__(self, context):75 unmodified lines436 self.name is None and 'anonymous' or repr(self.name)437 )438 439 440+@implements_to_string443-class Undefined(UnicodeMixin):441+class Undefined(object):442 """The default undefined type. This undefined type can be printed and443 iterated over, but every other access will raise an :exc:`UndefinedError`:444 445 >>> foo = Undefined(name='foo')49 unmodified lines495 __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \496 __float__ = __complex__ = __pow__ = __rpow__ = \497 _fail_with_undefined_error498 501- def __unicode__(self):499+ def __str__(self):500 return u''501 502 def __len__(self):503 return 08 unmodified lines512 def __repr__(self):513 return 'Undefined'514 515 516+@implements_to_string517 class DebugUndefined(Undefined):518 """An undefined that returns the debug info when printed.519 520 >>> foo = DebugUndefined(name='foo')7 unmodified lines528 UndefinedError: 'foo' is undefined529 """530 __slots__ = ()531 533- def __unicode__(self):532+ def __str__(self):533 if self._undefined_hint is None:534 if self._undefined_obj is missing:535 return u'{{ %s }}' % self._undefined_name536 return '{{ no such element: %s[%r] }}' % (2 unmodified lines539 )540 return u'{{ undefined value printed: %s }}' % self._undefined_hint541 542 543+@implements_to_string544 class StrictUndefined(Undefined):545 """An undefined that barks on print and iteration as well as boolean546 tests and all kinds of comparisons. In other words: you can do nothing547 with it except checking if it's defined using the `defined` test.12 unmodified lines560 ...561 UndefinedError: 'foo' is undefined562 """563 __slots__ = ()564- __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = \564+ __iter__ = __str__ = __len__ = __nonzero__ = __eq__ = \565 __ne__ = __bool__ = Undefined._fail_with_undefined_error566 567 568 # remove remaining slots attributes, after the metaclass did the magic they2 unmodified linesmodified:jinja2/sandbox.py+9 added-2 removed
14 unmodified lines15 import operator16 from jinja2.environment import Environment17 from jinja2.exceptions import SecurityError18 from jinja2._compat import string_types, function_type, method_type, \19- traceback_type, code_type, frame_type, generator_type19+ traceback_type, code_type, frame_type, generator_type, PY220 21 22 #: maximum number of items a range may produce23 MAX_RANGE = 1000004 unmodified lines28 29 #: unsafe method attributes. function attributes are unsafe for methods too30 UNSAFE_METHOD_ATTRIBUTES = set(['im_class', 'im_func', 'im_self'])31 32+#: unsafe generator attirbutes.33+UNSAFE_GENERATOR_ATTRIBUTES = set(['gi_frame', 'gi_code'])34 35+# On versions > python 2 the special attributes on functions are gone,36+# but they remain on methods and generators for whatever reason.37+if not PY2:38+ UNSAFE_FUNCTION_ATTRIBUTES = set()39+40 import warnings41 42 # make sure we don't warn in python 2.6 about stuff we don't care about43 warnings.filterwarnings('ignore', 'the sets module', DeprecationWarning,99 unmodified lines143 return True144 elif isinstance(obj, (code_type, traceback_type, frame_type)):145 return True146 elif isinstance(obj, generator_type):140- if attr == 'gi_frame':147+ if attr in UNSAFE_GENERATOR_ATTRIBUTES:148 return True149 return attr.startswith('__')150 151 217 unmodified linesmodified:jinja2/tests.py+1 added-5 removed
15 unmodified lines16 number_re = re.compile(r'^-?\d+(\.\d+)?$')17 regex_type = type(number_re)18 19 20-try:21- test_callable = callable20+test_callable = callable22-except NameError:23- def test_callable(x):24- return hasattr(x, '__call__')21 22 23 def test_odd(value):24 """Return true if the variable is odd."""125 unmodified linesmodified:jinja2/utils.py+3 added-2 removed
21 unmodified lines22 from _thread import allocate_lock # py 323 except ImportError:24 from dummy_thread import allocate_lock25 from collections import deque26-from jinja2._compat import text_type, string_types, Iterator, PY226+from jinja2._compat import text_type, string_types, implements_iterator, PY227 28 29 _word_split_re = re.compile(r'(\s+)')30 _punctuation_re = re.compile(474 unmodified lines505 except ImportError:506 pass507 508 509+@implements_iterator509-class Cycler(Iterator):510+class Cycler(object):511 """A cycle helper for templates."""512 513 def __init__(self, *items):514 if not items:36 unmodified lines