Skip to content
Myr

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

9 files+92 added−89 removed

modified:jinja2/testsuite/filters.py+4 added-3 removed
10 unmodified lines
11import unittest12from jinja2.testsuite import JinjaTestCase1314from jinja2 import Markup, Environment15from jinja2._compat import text_type, UnicodeMixin15from jinja2._compat import text_type, implements_to_string1617env = Environment()1819
273 unmodified lines
293 tmpl = env.from_string('''{{ ['foo', 'Bar', 'blah']|sort }}''')294 assert tmpl.render() == "['Bar', 'blah', 'foo']"295296 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 lines
modified:jinja2/_compat.py+40 added-44 removed
19 unmodified lines
20 range_type = range21 text_type = str22 string_types = (str,)2324 _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())2728 import pickle29 from io import BytesIO, StringIO30 NativeStringIO = StringIO3131 ifilter = filter32 imap = map33 izip = zip3432 def reraise(tp, value, tb=None):33 if value.__traceback__ is not tb:34 raise value.with_traceback(tb)35 raise value3640 Iterator = object37 ifilter = filter38 imap = map39 izip = zip40 intern = sys.intern4142 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__45else:47 text_type = unicode46 unichr = unichr47 text_type = unicode48 range_type = xrange49 string_types = (str, unicode)5051 _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()5455 from itertools import imap, izip, ifilter56 range_type = xrange5758 from cStringIO import StringIO as BytesIO59 from StringIO import StringIO55 import cPickle as pickle56 from cStringIO import StringIO as BytesIO, StringIO57 NativeStringIO = BytesIO5859 exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')6064 class UnicodeMixin(object):65 __slots__ = ()66 def __str__(self):67 return self.__unicode__().encode('utf-8')61 from itertools import imap, izip, ifilter62 intern = intern6369 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 cls6869 def implements_to_string(cls):70 cls.__unicode__ = cls.__str__71 cls.__str__ = lambda x: x.__unicode__().encode('utf-8')72 return cls7374 get_next = lambda x: x.next757677try:78 next = next79except NameError:80 def next(it):81 return it.next()828384def 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, {})9385def iterkeys(d, **kw):86 return iter(getattr(d, _iterkeys)(**kw))9488def itervalues(d, **kw):89 return iter(getattr(d, _itervalues)(**kw))9091def iteritems(d, **kw):92 return iter(getattr(d, _iteritems)(**kw))9395try:95 import cPickle as pickle96except ImportError:97 import pickle9899try:96 from collections import Mapping as mapping_types97except ImportError:98 import UserDict99 mapping_types = (UserDict.UserDict, UserDict.DictMixin, dict)
19 unmodified lines
modified:jinja2/environment.py+9 added-6 removed
26 unmodified lines
27 TemplatesNotFound, TemplateRuntimeError28from jinja2.utils import import_string, LRUCache, Markup, missing, \29 concat, consume, internalcode, _encode_filename30from 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_next33from functools import reduce343536# for direct template usage we have up to ten living environments
1014 unmodified lines
1051 name = repr(self.name)1052 return '<%s %s>' % (self.__class__.__name__, name)105310541055@implements_to_string1054class TemplateModule(UnicodeMixin):1056class 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 lines
10661067 def __html__(self):1068 return Markup(concat(self._body_stream))10691068 def __unicode__(self):1070 def __str__(self):1071 return concat(self._body_stream)10721073 def __repr__(self):1074 if self.__name__ is None:
21 unmodified lines
1096 rv = None1097 return rv109810991100@implements_iterator1098class TemplateStream(Iterator):1101class 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 lines
1141 fp.close()11421143 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 = False11471148 def enable_buffering(self, size=5):1149 """Enable buffering. Buffer `size` items before yielding them."""
19 unmodified lines
1169 del buf[:]1170 c_size = 011711172 self.buffered = True1170 self._next = lambda: next(generator(lambda: next(self._gen)))1173 self._next = get_next(generator(get_next(self._gen)))11741175 def __iter__(self):1176 return self1177
7 unmodified lines
modified:jinja2/exceptions.py+7 added-5 removed
6 unmodified lines
78 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11from jinja2._compat import imap, text_type, PY2, UnicodeMixin11from jinja2._compat import imap, text_type, PY2, implements_to_string121314class TemplateError(Exception):15 """Baseclass for all template errors."""
19 unmodified lines
35 if message is not None:36 return message373839@implements_to_string39class TemplateNotFound(IOError, LookupError, TemplateError, UnicodeMixin):40class TemplateNotFound(IOError, LookupError, TemplateError):41 """Raised if a template does not exist."""4243 # looks weird, but removes the warning descriptor that just44 # bogusly warns us about message being deprecated
6 unmodified lines
51 self.message = message52 self.name = name53 self.templates = [name]5454 def __unicode__(self):55 def __str__(self):56 return self.message575859class TemplatesNotFound(TemplateNotFound):
11 unmodified lines
71 TemplateNotFound.__init__(self, names and names[-1] or None, message)72 self.templates = list(names)737475@implements_to_string74class TemplateSyntaxError(UnicodeMixin, TemplateError):76class TemplateSyntaxError(TemplateError):77 """Raised to tell the user that there is a problem with the template."""7879 def __init__(self, message, lineno, name=None, filename=None):80 TemplateError.__init__(self, message)
5 unmodified lines
86 # this is set to True if the debug.translate_syntax_error87 # function translated the syntax error into a new traceback88 self.translated = False8988 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 lines
modified:jinja2/lexer.py+6 added-9 removed
18 unmodified lines
19from operator import itemgetter20from collections import deque21from jinja2.exceptions import TemplateSyntaxError22from jinja2.utils import LRUCache23from jinja2._compat import next, iteritems, Iterator, text_type23from jinja2._compat import next, iteritems, implements_iterator, text_type, \24 intern252627# cache for the lexers. Exists in order to be able to have multiple28# environments with the same lexer
18 unmodified lines
4748float_re = re.compile(r'(?<!\.)\d+\.\d+')49newline_re = re.compile(r'(\r\n|\r|\n)')5050try:51 intern = intern # py252except NameError:53 import sys54 intern = sys.intern # py35551# internal the tokens and keep references to them52TOKEN_ADD = intern('add')53TOKEN_ASSIGN = intern('assign')54TOKEN_COLON = intern('colon')
209 unmodified lines
264 self.value265 )266267268@implements_iterator273class TokenStreamIterator(Iterator):269class TokenStreamIterator(object):270 """The iterator for tokenstreams. Iterate over the stream271 until the eof token is reached.272 """273
11 unmodified lines
285 next(self.stream)286 return token287288289@implements_iterator293class TokenStream(Iterator):290class 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 lines
modified:jinja2/runtime.py+13 added-13 removed
12 unmodified lines
13from jinja2.utils import Markup, soft_unicode, escape, missing, concat, \14 internalcode, object_type_repr15from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \16 TemplateNotFound17from jinja2._compat import next, imap, text_type, iteritems, Iterator, \18 string_types, PY2, UnicodeMixin17from jinja2._compat import next, imap, text_type, iteritems, \18 implements_iterator, implements_to_string, string_types192021# these variables are exported to the template runtime22__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',
1 unmodified line
24 'markup_join', 'unicode_join', 'to_string', 'identity',25 'TemplateNotFound']2627#: 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.30try:31 to_string = unicode32except NameError:33 to_string = str28#: a string. We can just use the text type here.29to_string = text_type3031#: the identity function. Useful for certain things in the environment32identity = lambda x: x33
317 unmodified lines
351 self.length352 )353354355@implements_iterator359class LoopContextIterator(Iterator):356class LoopContextIterator(object):357 """The iterator for a loop context."""358 __slots__ = ('context',)359360 def __init__(self, context):
75 unmodified lines
436 self.name is None and 'anonymous' or repr(self.name)437 )438439440@implements_to_string443class Undefined(UnicodeMixin):441class 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`:444445 >>> foo = Undefined(name='foo')
49 unmodified lines
495 __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \496 __float__ = __complex__ = __pow__ = __rpow__ = \497 _fail_with_undefined_error498501 def __unicode__(self):499 def __str__(self):500 return u''501502 def __len__(self):503 return 0
8 unmodified lines
512 def __repr__(self):513 return 'Undefined'514515516@implements_to_string517class DebugUndefined(Undefined):518 """An undefined that returns the debug info when printed.519520 >>> foo = DebugUndefined(name='foo')
7 unmodified lines
528 UndefinedError: 'foo' is undefined529 """530 __slots__ = ()531533 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 lines
539 )540 return u'{{ undefined value printed: %s }}' % self._undefined_hint541542543@implements_to_string544class 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 lines
560 ...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_error566567568# remove remaining slots attributes, after the metaclass did the magic they
2 unmodified lines
modified:jinja2/sandbox.py+9 added-2 removed
14 unmodified lines
15import operator16from jinja2.environment import Environment17from jinja2.exceptions import SecurityError18from 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, PY2202122#: maximum number of items a range may produce23MAX_RANGE = 100000
4 unmodified lines
2829#: unsafe method attributes. function attributes are unsafe for methods too30UNSAFE_METHOD_ATTRIBUTES = set(['im_class', 'im_func', 'im_self'])3132#: unsafe generator attirbutes.33UNSAFE_GENERATOR_ATTRIBUTES = set(['gi_frame', 'gi_code'])3435# On versions > python 2 the special attributes on functions are gone,36# but they remain on methods and generators for whatever reason.37if not PY2:38 UNSAFE_FUNCTION_ATTRIBUTES = set()3940import warnings4142# make sure we don't warn in python 2.6 about stuff we don't care about43warnings.filterwarnings('ignore', 'the sets module', DeprecationWarning,
99 unmodified lines
143 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('__')150151
217 unmodified lines
modified:jinja2/tests.py+1 added-5 removed
15 unmodified lines
16number_re = re.compile(r'^-?\d+(\.\d+)?$')17regex_type = type(number_re)181920try:21 test_callable = callable20test_callable = callable22except NameError:23 def test_callable(x):24 return hasattr(x, '__call__')212223def test_odd(value):24 """Return true if the variable is odd."""
125 unmodified lines
modified:jinja2/utils.py+3 added-2 removed
21 unmodified lines
22 from _thread import allocate_lock # py 323 except ImportError:24 from dummy_thread import allocate_lock25from collections import deque26from jinja2._compat import text_type, string_types, Iterator, PY226from jinja2._compat import text_type, string_types, implements_iterator, PY2272829_word_split_re = re.compile(r'(\s+)')30_punctuation_re = re.compile(
474 unmodified lines
505except ImportError:506 pass507508509@implements_iterator509class Cycler(Iterator):510class Cycler(object):511 """A cycle helper for templates."""512513 def __init__(self, *items):514 if not items:
36 unmodified lines