Moved all six usages (ignoring testsuite) into jinja2._compat
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 cd7bf5b · Browse files · 16 files·+199 added−183 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+199 added−183 removed
- other:+199 added−183 removed
Provenance
- Commit
e909867- Tree
c1d9e48- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
cd7bf5b
16 files changed+199 added−183 removed
modified:jinja2/_compat.py+52 added
10 unmodified lines11 :copyright: Copyright 2013 by the Jinja team, see AUTHORS.12 :license: BSD, see LICENSE for details.13 """14 import six15+import sys16 17+PY3 = six.PY318+19 # https://bitbucket.org/gutworth/six/issue/25/add-unichr20 try:21 unichr = unichr # py222 except NameError:1 unmodified line24 25 range_type = six.moves.xrange26 next = six.advance_iterator27 imap = six.moves.map28+izip = six.moves.zip29+text_type = six.text_type30+string_types = six.string_types31+32+iteritems = six.iteritems33+34+if six.PY3:35+ from io import BytesIO, StringIO36+ NativeStringIO = StringIO37+else:38+ from cStringIO import StringIO as BytesIO39+ from StringIO import StringIO40+ NativeStringIO = BytesIO41+42+try:43+ import cPickle as pickle44+except ImportError:45+ import pickle46+47+ifilter = six.moves.filter48+reraise = six.reraise49+Iterator = six.Iterator50+with_metaclass = six.with_metaclass51+52+try:53+ from collections import Mapping as mapping_types54+except ImportError:55+ import UserDict56+ mapping_types = (UserDict.UserDict, UserDict.DictMixin, dict)57+58+59+# common types. These do exist in the special types module too which however60+# does not exist in IronPython out of the box. Also that way we don't have61+# to deal with implementation specific stuff here62+class _C(object):63+ def method(self): pass64+def _func():65+ yield None66+function_type = type(_func)67+generator_type = type(_func())68+method_type = type(_C().method)69+code_type = type(_C.method.__code__)70+try:71+ raise TypeError()72+except TypeError:73+ _tb = sys.exc_info()[2]74+ traceback_type = type(_tb)75+ frame_type = type(_tb.tb_frame)76+del _C, _tb, _funcmodified:jinja2/bccache.py+2 added-6 removed
16 unmodified lines17 from os import path, listdir18 import sys19 import marshal20 import tempfile21-from six.moves import cPickle as pickle22-from six import BytesIO21 import fnmatch24-try:25- from hashlib import sha122+from hashlib import sha126-except ImportError:27- from sha import new as sha123 from jinja2.utils import open_if_exists24+from jinja2._compat import BytesIO, pickle25 26 27 # marshal works better on 3.x, one hack less required28 if sys.version_info[0] >= 3:283 unmodified linesmodified:jinja2/compiler.py+14 added-16 removed
6 unmodified lines7 8 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11-import six12-11 from itertools import chain12 from copy import deepcopy13 from jinja2 import nodes14 from jinja2.nodes import EvalContext15 from jinja2.visitor import NodeVisitor16 from jinja2.exceptions import TemplateAssertionError17 from jinja2.utils import Markup, concat, escape, is_python_keyword20-from jinja2._compat import range_type, next21-from six.moves import cStringIO as StringIO, map18+from jinja2._compat import range_type, next, text_type, string_types, \19+ iteritems, NativeStringIO, imap20 21 22 operators = {23 'eq': '==',42 unmodified lines66 """Does the node have a safe representation?"""67 if value is None or value is NotImplemented or value is Ellipsis:68 return True69 if isinstance(value, (bool, int, float, complex, range_type,72- Markup) + six.string_types):70+ Markup) + string_types):71 return True72 if isinstance(value, (tuple, list, set, frozenset)):73 for item in value:74 if not has_safe_repr(item):75 return False76 return True77 elif isinstance(value, dict):80- for key, value in six.iteritems(value):78+ for key, value in iteritems(value):79 if not has_safe_repr(key):80 return False81 if not has_safe_repr(value):82 return False281 unmodified lines364 365 def __init__(self, environment, name, filename, stream=None,366 defer_init=False):367 if stream is None:370- stream = StringIO()368+ stream = NativeStringIO()369 self.environment = environment370 self.name = name371 self.filename = filename372 self.stream = stream165 unmodified lines538 for kwarg in node.kwargs:539 self.write(', ')540 self.visit(kwarg, frame)541 if extra_kwargs is not None:544- for key, value in six.iteritems(extra_kwargs):542+ for key, value in iteritems(extra_kwargs):543 self.write(', %s=%s' % (key, value))544 if node.dyn_args:545 self.write(', *')546 self.visit(node.dyn_args, frame)7 unmodified lines554 self.write('%r: ' % kwarg.key)555 self.visit(kwarg.value, frame)556 self.write(', ')557 if extra_kwargs is not None:560- for key, value in six.iteritems(extra_kwargs):558+ for key, value in iteritems(extra_kwargs):559 self.write('%r: %s, ' % (key, value))560 if node.dyn_kwargs is not None:561 self.write('}, **')562 self.visit(node.dyn_kwargs, frame)58 unmodified lines621 return aliases622 623 def pop_scope(self, aliases, frame):624 """Restore all aliases and delete unused variables."""627- for name, alias in six.iteritems(aliases):625+ for name, alias in iteritems(aliases):626 self.writeline('l_%s = %s' % (name, alias))627 to_delete = set()628 for name in frame.identifiers.declared_locally:629 if name not in aliases:193 unmodified lines823 self.writeline('yield event')824 self.outdent(2 + (not self.has_known_extends))825 826 # at this point we now have the blocks collected and can visit them too.829- for name, block in six.iteritems(self.blocks):827+ for name, block in iteritems(self.blocks):828 block_frame = Frame(eval_ctx)829 block_frame.inspect(block.body)830 block_frame.block = name831 self.writeline('def block_%s(context%s):' % (name, envenv),95 unmodified lines927 self.indent()928 929 func_name = 'get_or_select_template'930 if isinstance(node.template, nodes.Const):933- if isinstance(node.template.value, six.string_types):931+ if isinstance(node.template.value, string_types):932 func_name = 'get_template'933 elif isinstance(node.template.value, (tuple, list)):934 func_name = 'select_template'935 elif isinstance(node.template, (nodes.Tuple, nodes.List)):100 unmodified lines1036 self.writeline('context.exported_vars.discard(%r)' %1037 discarded_names[0])1038 else:1039 self.writeline('context.exported_vars.difference_'1042- 'update((%s))' % ', '.join(map(repr, discarded_names)))1040+ 'update((%s))' % ', '.join(imap(repr, discarded_names)))1041 1042 def visit_For(self, node, frame):1043 # when calculating the nodes for the inner frame we have to exclude1044 # the iterator contents from it176 unmodified lines1221 if self.has_known_extends and frame.require_output_check:1222 return1223 1224 if self.environment.finalize:1227- finalize = lambda x: six.text_type(self.environment.finalize(x))1225+ finalize = lambda x: text_type(self.environment.finalize(x))1226 else:1229- finalize = six.text_type1227+ finalize = text_type1228 1229 # if we are inside a frame that requires output checking, we do so1230 outdent_later = False1231 if frame.require_output_check:140 unmodified lines1372 self.writeline('context.exported_vars.add(%r)' %1373 public_names[0])1374 else:1375 self.writeline('context.exported_vars.update((%s))' %1378- ', '.join(map(repr, public_names)))1376+ ', '.join(imap(repr, public_names)))1377 1378 # -- Expression Visitors1379 1380 def visit_Name(self, node, frame):266 unmodified linesmodified:jinja2/debug.py+9 added-9 removed
11 unmodified lines12 """13 import sys14 import traceback15 from types import TracebackType16-from jinja2.utils import CodeType, missing, internal_code16+from jinja2.utils import missing, internal_code17 from jinja2.exceptions import TemplateSyntaxError18-import six18+from jinja2._compat import iteritems, reraise, code_type19 20 # on pypy we can take advantage of transparent proxies21 try:22 from __pypy__ import tproxy166 unmodified lines189 # if we don't have any exceptions in the frames left, we have to190 # reraise it unchanged.191 # XXX: can we backup here? when could this happen?192 if not frames:193- six.reraise(exc_info[0], exc_info[1], exc_info[2])193+ reraise(exc_info[0], exc_info[1], exc_info[2])194 195 return ProcessedTraceback(exc_info[0], exc_info[1], frames)196 197 8 unmodified lines206 if ctx:207 locals = ctx.get_all()208 else:209 locals = {}210- for name, value in six.iteritems(real_locals):210+ for name, value in iteritems(real_locals):211 if name.startswith('l_') and value is not missing:212 locals[name[2:]] = value213 214 # if there is a local called __jinja_exception__, we get29 unmodified lines244 elif function.startswith('block_'):245 location = 'block "%s"' % function[6:]246 else:247 location = 'template'248- code = CodeType(0, code.co_nlocals, code.co_stacksize,249- code.co_flags, code.co_code, code.co_consts,250- code.co_names, code.co_varnames, filename,251- location, code.co_firstlineno,252- code.co_lnotab, (), ())248+ code = code_type(0, code.co_nlocals, code.co_stacksize,249+ code.co_flags, code.co_code, code.co_consts,250+ code.co_names, code.co_varnames, filename,251+ location, code.co_firstlineno,252+ code.co_lnotab, (), ())253 except:254 pass255 256 # execute the code and catch the new traceback81 unmodified linesmodified:jinja2/environment.py+19 added-19 removed
25 unmodified lines26 from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \27 TemplatesNotFound, TemplateRuntimeError28 from jinja2.utils import import_string, LRUCache, Markup, missing, \29 concat, consume, internalcode, _encode_filename30-import six30+from jinja2._compat import imap, ifilter, string_types, iteritems, \31+ text_type, reraise, PY3, Iterator, next32 from functools import reduce32-from six.moves import filter, map33 34 35 # for direct template usage we have up to ten living environments36 _spontaneous_environments = LRUCache(10)42 unmodified lines79 Returns a dict of instantiated environments.80 """81 result = {}82 for extension in extensions:83- if isinstance(extension, six.string_types):83+ if isinstance(extension, string_types):84 extension = import_string(extension)85 result[extension.identifier] = extension(environment)86 return result87 226 unmodified lines314 """Add the items to the instance of the environment if they do not exist315 yet. This is used by :ref:`extensions <writing-extensions>` to register316 callbacks and configuration values without breaking inheritance.317 """318- for key, value in six.iteritems(attributes):318+ for key, value in iteritems(attributes):319 if not hasattr(self, key):320 setattr(self, key, value)321 322 def overlay(self, block_start_string=missing, block_end_string=missing,23 unmodified lines346 rv.__dict__.update(self.__dict__)347 rv.overlayed = True348 rv.linked_to = self349 350- for key, value in six.iteritems(args):350+ for key, value in iteritems(args):351 if value is not missing:352 setattr(rv, key, value)353 354 if cache_size is not missing:1 unmodified line356 else:357 rv.cache = copy_cache(self.cache)358 359 rv.extensions = {}360- for key, value in six.iteritems(self.extensions):360+ for key, value in iteritems(self.extensions):361 rv.extensions[key] = value.bind(rv)362 if extensions is not missing:363 rv.extensions.update(load_extensions(rv, extensions))364 10 unmodified lines375 """Get an item or attribute of an object but prefer the item."""376 try:377 return obj[argument]378 except (TypeError, LookupError):379- if isinstance(argument, six.string_types):379+ if isinstance(argument, string_types):380 try:381 attr = str(argument)382 except Exception:383 pass82 unmodified lines466 This does not perform preprocessing. If you want the preprocessing467 of the extensions to be applied you have to filter source through468 the :meth:`preprocess` method.469 """470- source = six.text_type(source)470+ source = text_type(source)471 try:472 return self.lexer.tokeniter(source, name, filename)473 except TemplateSyntaxError:474 exc_info = sys.exc_info()4 unmodified lines479 called for all parsing and compiling methods but *not* for :meth:`lex`480 because there you usually only want the actual source tokenized.481 """482 return reduce(lambda s, e: e.preprocess(s, name, filename),483- self.iter_extensions(), six.text_type(source))483+ self.iter_extensions(), text_type(source))484 485 def _tokenize(self, source, name, filename=None, state=None):486 """Called by the parser to do the preprocessing and filtering487 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.45 unmodified lines533 `defer_init` parameter added.534 """535 source_hint = None536 try:537- if isinstance(source, six.string_types):537+ if isinstance(source, string_types):538 source_hint = source539 source = self._parse(source, name, filename)540 if self.optimized:541 source = optimize(source, self)165 unmodified lines707 'can be passed, but not both')708 filter_func = lambda x: '.' in x and \709 x.rsplit('.', 1)[1] in extensions710 if filter_func is not None:711- x = filter(filter_func, x)711+ x = ifilter(filter_func, x)712 return x713 714 def handle_exception(self, exc_info=None, rendered=False, source_hint=None):715 """Exception handling helper. This is used internally to either raise14 unmodified lines730 return self.exception_formatter(traceback)731 if self.exception_handler is not None:732 self.exception_handler(traceback)733 exc_type, exc_value, tb = traceback.standard_exc_info734- six.reraise(exc_type, exc_value, tb)734+ reraise(exc_type, exc_value, tb)735 736 def join_path(self, template, parent):737 """Join a template with the parent. By default all the lookups are738 relative to the loader root so this method returns the `template`78 unmodified lines817 :meth:`get_template`.818 819 .. versionadded:: 2.3820 """821- if isinstance(template_name_or_list, six.string_types):821+ if isinstance(template_name_or_list, string_types):822 return self.get_template(template_name_or_list, parent, globals)823 elif isinstance(template_name_or_list, Template):824 return template_name_or_list825 return self.select_template(template_name_or_list, parent, globals)213 unmodified lines1039 1040 @property1041 def debug_info(self):1042 """The debug info mapping."""1043- return [tuple(map(int, x.split('='))) for x in1043+ return [tuple(imap(int, x.split('='))) for x in1044 self._debug_info.split('&')]1045 1046 def __repr__(self):1047 if self.name is None:18 unmodified lines1066 return Markup(concat(self._body_stream))1067 1068 def __str__(self):1069 s = self.__unicode__()1070- return s if six.PY3 else s.encode('utf-8')1070+ return s if PY3 else s.encode('utf-8')1071 1072 def __unicode__(self):1073 return concat(self._body_stream)1074 23 unmodified lines1098 rv = None1099 return rv1100 1101 1102-class TemplateStream(six.Iterator):1102+class TemplateStream(Iterator):1103 """A template stream works pretty much like an ordinary python generator1104 but it can buffer multiple items to reduce the number of total iterations.1105 Per default the output is unbuffered which means that for every unbuffered1106 instruction in the template one unicode string is yielded.16 unmodified lines1123 1124 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1125 """1126 close = False1127- if isinstance(fp, six.string_types):1127+ if isinstance(fp, string_types):1128 fp = open(fp, encoding is None and 'w' or 'wb')1129 close = True1130 try:1131 if encoding is not None:10 unmodified lines1142 fp.close()1143 1144 def disable_buffering(self):1145 """Disable the output buffering."""1146- self._next = lambda: six.next(self._gen)1146+ self._next = lambda: next(self._gen)1147 self.buffered = False1148 1149 def enable_buffering(self, size=5):1150 """Enable buffering. Buffer `size` items before yielding them."""19 unmodified lines1170 del buf[:]1171 c_size = 01172 1173 self.buffered = True1174- self._next = lambda: six.next(generator(lambda: six.next(self._gen)))1174+ self._next = lambda: next(generator(lambda: next(self._gen)))1175 1176 def __iter__(self):1177 return self1178 7 unmodified linesmodified:jinja2/exceptions.py+10 added-8 removed
7 unmodified lines8 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11 import sys12-import six13-from six.moves import map12+from jinja2._compat import imap, text_type, PY313 14 15 class TemplateError(Exception):16 """Baseclass for all template errors."""17 18 if sys.version_info[0] < 3:19 def __init__(self, message=None):20 if message is not None:22- message = six.text_type(message).encode('utf-8')21+ message = text_type(message).encode('utf-8')22 Exception.__init__(self, message)23 24 @property25 def message(self):47 unmodified lines73 74 def __init__(self, names=(), message=None):75 if message is None:76 message = u'none of the templates given were found: ' + \78- u', '.join(map(six.text_type, names))77+ u', '.join(imap(text_type, names))78 TemplateNotFound.__init__(self, names and names[-1] or None, message)79 self.templates = list(names)80 81 10 unmodified lines92 # this is set to True if the debug.translate_syntax_error93 # function translated the syntax error into a new traceback94 self.translated = False95 97- def __str__(self):98- s = self.__unicode__()99- return s if six.PY3 else s.encode('utf-8')100-96 def __unicode__(self):97 # for translated errors we only return the message98 if self.translated:99 return self.message15 unmodified lines115 lines.append(' ' + line.strip())116 117 return u'\n'.join(lines)118 119+ if PY3:120+ __str__ = __unicode__121+ del __unicode__122+ else:123+ def __str__(self):124+ return self.__unicode__().encode('utf-8')125 126+127 class TemplateAssertionError(TemplateSyntaxError):128 """Like a template syntax error, but covers cases where something in the129 template caused an error at compile time that wasn't necessarily caused130 by a syntax error. However it's a direct subclass of24 unmodified linesmodified:jinja2/ext.py+5 added-6 removed
18 unmodified lines19 from jinja2.environment import Environment20 from jinja2.runtime import concat21 from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError22 from jinja2.utils import contextfunction, import_string, Markup23-from jinja2._compat import next24-import six23+from jinja2._compat import next, with_metaclass, string_types, iteritems24 25 26 # the only real useful gettext functions for a Jinja template. Note27 # that ugettext must be assigned to gettext as Jinja doesn't support9 unmodified lines37 rv.identifier = rv.__module__ + '.' + rv.__name__38 return rv39 40 42-class Extension(six.with_metaclass(ExtensionRegistry, object)):41+class Extension(with_metaclass(ExtensionRegistry, object)):42 """Extensions can be used to add extra functionality to the Jinja template43 system at the parser level. Custom extensions are bound to an environment44 but may not store environment specific data on `self`. The reason for45 this is that an extension can be bound to another environment (for162 unmodified lines208 for key in 'gettext', 'ngettext':209 self.environment.globals.pop(key, None)210 211 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):213- if isinstance(source, six.string_types):212+ if isinstance(source, string_types):213 source = self.environment.parse(source)214 return extract_from_ast(source, gettext_functions)215 216 def parse(self, parser):150 unmodified lines367 # in case newstyle gettext is used, the method is powerful368 # enough to handle the variable expansion and autoescape369 # handling itself370 if self.environment.newstyle_gettext:372- for key, value in six.iteritems(variables):371+ for key, value in iteritems(variables):372 # the function adds that later anyways in case num was373 # called num, so just skip it.374 if num_called_num and key == 'num':375 continue113 unmodified lines489 490 strings = []491 for arg in node.args:492 if isinstance(arg, nodes.Const) and \494- isinstance(arg.value, six.string_types):493+ isinstance(arg.value, string_types):494 strings.append(arg.value)495 else:496 strings.append(None)497 140 unmodified linesmodified:jinja2/filters.py+19 added-21 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import re12 import math13-import six13 14 from random import choice15 from operator import itemgetter16 from itertools import groupby17 from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode, \18 unicode_urlencode19 from jinja2.runtime import Undefined20 from jinja2.exceptions import FilterArgumentError22-from jinja2._compat import next23-from six.moves import map21+from jinja2._compat import next, imap, string_types, text_type, iteritems22 23 24 _word_re = re.compile(r'\w+(?u)')25 29 unmodified lines55 """Returns a callable that looks up the given attribute from a56 passed object with the rules of the environment. Dots are allowed57 to access attributes of attributes.58 """61- if not isinstance(attribute, six.string_types) or '.' not in attribute:59+ if not isinstance(attribute, string_types) or '.' not in attribute:60 return lambda x: environment.getitem(x, attribute)61 attribute = attribute.split('.')62 def attrgetter(item):63 for part in attribute:5 unmodified lines69 def do_forceescape(value):70 """Enforce HTML escaping. This will probably double escape variables."""71 if hasattr(value, '__html__'):72 value = value.__html__()75- return escape(six.text_type(value))73+ return escape(text_type(value))74 75 76 def do_urlencode(value):77 """Escape strings for use in URLs (uses UTF-8 encoding). It accepts both2 unmodified lines80 .. versionadded:: 2.781 """82 itemiter = None83 if isinstance(value, dict):86- itemiter = six.iteritems(value)87- elif not isinstance(value, six.string_types):84+ itemiter = iteritems(value)85+ elif not isinstance(value, string_types):86 try:87 itemiter = iter(value)88 except TypeError:89 pass21 unmodified lines111 """112 if count is None:113 count = -1114 if not eval_ctx.autoescape:117- return six.text_type(s).replace(six.text_type(old), six.text_type(new), count)115+ return text_type(s).replace(text_type(old), text_type(new), count)116 if hasattr(old, '__html__') or hasattr(new, '__html__') and \117 not hasattr(s, '__html__'):118 s = escape(s)119 else:36 unmodified lines156 if the filter returned something unless the second parameter is false.157 """158 rv = u' '.join(159 u'%s="%s"' % (escape(key), escape(value))162- for key, value in six.iteritems(d)160+ for key, value in iteritems(d)161 if value is not None and not isinstance(value, Undefined)162 )163 if autospace and rv:164 rv = u' ' + rv46 unmodified lines211 raise FilterArgumentError('You can only sort by either '212 '"key" or "value"')213 def sort_func(item):214 value = item[pos]217- if isinstance(value, six.string_types) and not case_sensitive:215+ if isinstance(value, string_types) and not case_sensitive:216 value = value.lower()217 return value218 219 return sorted(value.items(), key=sort_func)28 unmodified lines248 The `attribute` parameter was added.249 """250 if not case_sensitive:251 def sort_func(item):254- if isinstance(item, six.string_types):252+ if isinstance(item, string_types):253 item = item.lower()254 return item255 else:256 sort_func = None49 unmodified lines306 .. versionadded:: 2.6307 The `attribute` parameter was added.308 """309 if attribute is not None:312- value = map(make_attrgetter(eval_ctx.environment, attribute), value)310+ value = imap(make_attrgetter(eval_ctx.environment, attribute), value)311 312 # no automatic escaping? joining is a lot eaiser then313 if not eval_ctx.autoescape:316- return six.text_type(d).join(map(six.text_type, value))314+ return text_type(d).join(imap(text_type, value))315 316 # if the delimiter doesn't have an html representation we check317 # if any of the items has. If yes we do a coercion to Markup318 if not hasattr(d, '__html__'):2 unmodified lines321 for idx, item in enumerate(value):322 if hasattr(item, '__html__'):323 do_escape = True324 else:327- value[idx] = six.text_type(item)325+ value[idx] = text_type(item)326 if do_escape:327 d = escape(d)328 else:331- d = six.text_type(d)329+ d = text_type(d)330 return d.join(value)331 332 # no html involved, to normal joining335- return soft_unicode(d).join(map(soft_unicode, value))333+ return soft_unicode(d).join(imap(soft_unicode, value))334 335 336 def do_center(value, width=80):337 """Centers the value in a field of a given width."""340- return six.text_type(value).center(width)338+ return text_type(value).center(width)339 340 341 @environmentfilter342 def do_first(environment, seq):206 unmodified lines549 """Strip SGML/XML tags and replace adjacent whitespace by one space.550 """551 if hasattr(value, '__html__'):552 value = value.__html__()555- return Markup(six.text_type(value)).striptags()553+ return Markup(text_type(value)).striptags()554 555 556 def do_slice(value, slices, fill_with=None):557 """Slice an iterator and return a list of lists containing166 unmodified lines724 The `attribute` parameter was added to allow suming up over725 attributes. Also the `start` parameter was moved on to the right.726 """727 if attribute is not None:730- iterable = map(make_attrgetter(environment, attribute), iterable)728+ iterable = imap(make_attrgetter(environment, attribute), iterable)729 return sum(iterable, start)730 731 732 def do_list(value):11 unmodified lines744 745 746 def do_mark_unsafe(value):747 """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""750- return six.text_type(value)748+ return text_type(value)749 750 751 def do_reverse(value):752 """Reverse the object or return an iterator the iterates over it the other753 way round.754 """757- if isinstance(value, six.string_types):755+ if isinstance(value, string_types):756 return value[::-1]757 try:758 return reversed(value)759 except TypeError:224 unmodified linesmodified:jinja2/lexer.py+7 added-8 removed
13 unmodified lines14 :copyright: (c) 2010 by the Jinja Team.15 :license: BSD, see LICENSE for more details.16 """17 import re18-import six18 19 from operator import itemgetter20 from collections import deque21 from jinja2.exceptions import TemplateSyntaxError22 from jinja2.utils import LRUCache24-from jinja2._compat import next23+from jinja2._compat import next, iteritems, Iterator, text_type24 25 26 # cache for the lexers. Exists in order to be able to have multiple27 # environments with the same lexer105 unmodified lines133 ',': TOKEN_COMMA,134 ';': TOKEN_SEMICOLON135 }136 138-reverse_operators = dict([(v, k) for k, v in six.iteritems(operators)])137+reverse_operators = dict([(v, k) for k, v in iteritems(operators)])138 assert len(operators) == len(reverse_operators), 'operators dropped'139 operator_re = re.compile('(%s)' % '|'.join(re.escape(x) for x in140 sorted(operators, key=lambda x: -len(x))))141 127 unmodified lines269 self.value270 )271 272 274-class TokenStreamIterator(six.Iterator):273+class TokenStreamIterator(Iterator):274 """The iterator for tokenstreams. Iterate over the stream275 until the eof token is reached.276 """277 11 unmodified lines289 next(self.stream)290 return token291 292 294-class TokenStream(six.Iterator):293+class TokenStream(Iterator):294 """A token stream is an iterable that yields :class:`Token`\s. The295 parser however does not iterate over it but calls :meth:`next` to go296 one token ahead. The current active token is stored as :attr:`current`.297 """298 unmodified lines596 def tokeniter(self, source, name, filename=None, state=None):597 """This method tokenizes the text and returns the tokens in a598 generator. Use this method if you just want to tokenize a template.599 """601- source = six.text_type(source)600+ source = text_type(source)601 lines = source.splitlines()602 if self.keep_trailing_newline and source:603 for newline in ('\r\n', '\r', '\n'):604 if source.endswith(newline):39 unmodified lines644 # bygroup is a bit more complex, in that case we645 # yield for the current token the first named646 # group that matched647 elif token == '#bygroup':649- for key, value in six.iteritems(m.groupdict()):648+ for key, value in iteritems(m.groupdict()):649 if value is not None:650 yield lineno, key, value651 lineno += value.count('\n')652 break48 unmodified lines701 if new_state == '#pop':702 stack.pop()703 # resolve the new state by group checking704 elif new_state == '#bygroup':706- for key, value in six.iteritems(m.groupdict()):705+ for key, value in iteritems(m.groupdict()):706 if value is not None:707 stack.append(key)708 break709 else:27 unmodified linesmodified:jinja2/loaders.py+6 added-9 removed
11 unmodified lines12 import sys13 import weakref14 from types import ModuleType15 from os import path16-import six17-try:18- from hashlib import sha116+from hashlib import sha119-except ImportError:20- from sha import new as sha117 from jinja2.exceptions import TemplateNotFound18 from jinja2.utils import open_if_exists, internalcode19+from jinja2._compat import string_types, iteritems20 21 22 def split_template_path(template):23 """Split a path into segments and perform a sanity check. If it detects126 unmodified lines150 by setting the `encoding` parameter to something else.151 """152 153 def __init__(self, searchpath, encoding='utf-8'):157- if isinstance(searchpath, six.string_types):154+ if isinstance(searchpath, string_types):155 searchpath = [searchpath]156 self.searchpath = list(searchpath)157 self.encoding = encoding158 144 unmodified lines303 def get_source(self, environment, template):304 rv = self.load_func(template)305 if rv is None:306 raise TemplateNotFound(template)310- elif isinstance(rv, six.string_types):307+ elif isinstance(rv, string_types):308 return rv, None, None309 return rv310 311 44 unmodified lines356 raise TemplateNotFound(name)357 358 def list_templates(self):359 result = []363- for prefix, loader in six.iteritems(self.mapping):360+ for prefix, loader in iteritems(self.mapping):361 for template in loader.list_templates():362 result.append(prefix + self.delimiter + template)363 return result364 63 unmodified lines428 429 # create a fake module that looks for the templates in the430 # path given.431 mod = _TemplateModule(package_name)435- if isinstance(path, six.string_types):432+ if isinstance(path, string_types):433 path = [path]434 else:435 path = list(path)436 mod.__path__ = path35 unmodified linesmodified:jinja2/meta.py+5 added-4 removed
9 unmodified lines10 :license: BSD, see LICENSE for more details.11 """12 from jinja2 import nodes13 from jinja2.compiler import CodeGenerator14-import six14+from jinja2._compat import string_types15 16+17 class TrackingCodeGenerator(CodeGenerator):18 """We abuse the code generator for introspection."""19 20 def __init__(self, environment):56 unmodified lines77 for template_name in node.template.items:78 # something const, only yield the strings and ignore79 # non-string consts that really just make no sense80 if isinstance(template_name, nodes.Const):80- if isinstance(template_name.value, six.string_types):81+ if isinstance(template_name.value, string_types):82 yield template_name.value83 # something dynamic in there84 else:85 yield None1 unmodified line87 else:88 yield None89 continue90 # constant is a basestring, direct template name90- if isinstance(node.template.value, six.string_types):91+ if isinstance(node.template.value, string_types):92 yield node.template.value93 # a tuple or list (latter *should* not happen) made of consts,94 # yield the consts that are strings. We could warn here for95 # non string values96 elif isinstance(node, nodes.Include) and \97 isinstance(node.template.value, (tuple, list)):98 for template_name in node.template.value:98- if isinstance(template_name, six.string_types):99+ if isinstance(template_name, string_types):100 yield template_name101 # something else we don't care about, we could warn here102 else:103 yield Nonemodified:jinja2/nodes.py+7 added-8 removed
10 unmodified lines11 12 :copyright: (c) 2010 by the Jinja Team.13 :license: BSD, see LICENSE for more details.14 """15-import six15 import operator16 17 from collections import deque19-from jinja2.utils import Markup, MethodType, FunctionType20-from jinja2._compat import next21-from six.moves import zip18+from jinja2.utils import Markup19+from jinja2._compat import next, izip, with_metaclass, text_type, \20+ method_type, function_type21 22 23 #: the types we support for context functions25-_context_function_types = (FunctionType, MethodType)24+_context_function_types = (function_type, method_type)25 26 27 _binop_to_func = {28 '*': operator.mul,74 unmodified lines103 return EvalContext(node.environment)104 return ctx105 106 108-class Node(six.with_metaclass(NodeType, object)):107+class Node(with_metaclass(NodeType, object)):108 """Baseclass for all Jinja2 nodes. There are a number of nodes available109 of different types. There are four major types:110 111 - :class:`Stmt`: statements25 unmodified lines137 self.__class__.__name__,138 len(self.fields),139 len(self.fields) != 1 and 's' or ''140 ))142- for name, arg in zip(self.fields, fields):141+ for name, arg in izip(self.fields, fields):142 setattr(self, name, arg)143 for attr in self.attributes:144 setattr(self, attr, attributes.pop(attr, None))145 if attributes:542 unmodified lines688 fields = ('nodes',)689 690 def as_const(self, eval_ctx=None):691 eval_ctx = get_eval_context(self, eval_ctx)693- return ''.join(six.text_type(x.as_const(eval_ctx)) for x in self.nodes)692+ return ''.join(text_type(x.as_const(eval_ctx)) for x in self.nodes)693 694 695 class Compare(Expr):696 """Compares an expression with some other expressions. `ops` must be a216 unmodified linesmodified:jinja2/runtime.py+24 added-19 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 next18-import six19-from six.moves import map17+from jinja2._compat import next, imap, text_type, iteritems, Iterator, \18+ string_types, PY319 20 21 # these variables are exported to the template runtime22 __all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',17 unmodified lines40 41 def markup_join(seq):42 """Concatenation that escapes if necessary and converts to unicode."""43 buf = []45- iterator = map(soft_unicode, seq)44+ iterator = imap(soft_unicode, seq)45 for arg in iterator:46 buf.append(arg)47 if hasattr(arg, '__html__'):48 return Markup(u'').join(chain(buf, iterator))1 unmodified line50 51 52 def unicode_join(seq):53 """Simple args to unicode conversion and concatenation."""55- return concat(map(six.text_type, seq))54+ return concat(imap(text_type, seq))55 56 57 def new_context(environment, template_name, blocks, vars=None,58 shared=None, globals=None, locals=None):8 unmodified lines67 # if the parent is shared a copy should be created because68 # we don't want to modify the dict passed69 if shared:70 parent = dict(parent)72- for key, value in six.iteritems(locals):71+ for key, value in iteritems(locals):72 if key[:2] == 'l_' and value is not missing:73 parent[key[2:]] = value74 return Context(environment, parent, template_name, blocks)75 47 unmodified lines123 124 # create the initial mapping of blocks. Whenever template inheritance125 # takes place the runtime will update this mapping with the new blocks126 # from the template.128- self.blocks = dict((k, [v]) for k, v in six.iteritems(blocks))127+ self.blocks = dict((k, [v]) for k, v in iteritems(blocks))128 129 def super(self, name, current):130 """Render a parent block."""131 try:74 unmodified lines206 context = new_context(self.environment, self.name, {},207 self.parent, True, None, locals)208 context.vars.update(self.vars)209 context.eval_ctx = self.eval_ctx211- context.blocks.update((k, list(v)) for k, v in six.iteritems(self.blocks))210+ context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))211 return context212 213 def _all(meth):214 proxy = lambda self: getattr(self.get_all(), meth)()140 unmodified lines355 self.length356 )357 358 360-class LoopContextIterator(six.Iterator):359+class LoopContextIterator(Iterator):360 """The iterator for a loop context."""361 __slots__ = ('context',)362 363 def __init__(self, context):106 unmodified lines470 """471 if self._undefined_hint is None:472 if self._undefined_obj is missing:473 hint = '%r is undefined' % self._undefined_name475- elif not isinstance(self._undefined_name, six.string_types):474+ elif not isinstance(self._undefined_name, string_types):475 hint = '%s has no element %r' % (476 object_type_repr(self._undefined_obj),477 self._undefined_name478 )18 unmodified lines497 __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \498 __float__ = __complex__ = __pow__ = __rpow__ = \499 _fail_with_undefined_error500 502- def __str__(self):503- s = self.__unicode__()504- return s if six.PY3 else s.encode('utf-8')505-501 def __unicode__(self):502 return u''503 504+ if PY3:505+ __str__ = __unicode__506+ del __unicode__507+ else:508+ def __str__(self):509+ return self.__unicode__().encode('utf-8')510+511 def __len__(self):512 return 0513 514 def __iter__(self):21 unmodified lines536 UndefinedError: 'foo' is undefined537 """538 __slots__ = ()539 538- def __str__(self):539- s = self.__unicode__()540- return s if six.PY3 else s.encode('utf-8')541-540 def __unicode__(self):541 if self._undefined_hint is None:542 if self._undefined_obj is missing:543 return u'{{ %s }}' % self._undefined_name2 unmodified lines546 self._undefined_name547 )548 return u'{{ undefined value printed: %s }}' % self._undefined_hint549 550+ if PY3:551+ __str__ = __unicode__552+ del __unicode__553 554+555 class StrictUndefined(Undefined):556 """An undefined that barks on print and iteration as well as boolean557 tests and all kinds of comparisons. In other words: you can do nothing558 with it except checking if it's defined using the `defined` test.12 unmodified lines571 ...572 UndefinedError: 'foo' is undefined573 """574 __slots__ = ()573- __iter__ = __unicode__ = __str__ = __len__ = __nonzero__ = __eq__ = \575+ __iter__ = __str__ = __len__ = __nonzero__ = __eq__ = \576 __ne__ = __bool__ = Undefined._fail_with_undefined_error577 578+ if not PY3:579+ __unicode__ = Undefined._fail_with_undefined_error580 581+582 # remove remaining slots attributes, after the metaclass did the magic they583 # are unneeded and irritating as they contain wrong data for the subclasses.584 del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__modified:jinja2/sandbox.py+7 added-8 removed
11 unmodified lines12 :copyright: (c) 2010 by the Jinja Team.13 :license: BSD.14 """15 import operator16-import six16 from jinja2.environment import Environment17 from jinja2.exceptions import SecurityError19-from jinja2.utils import FunctionType, MethodType, TracebackType, CodeType, \20- FrameType, GeneratorType18+from jinja2._compat import string_types, function_type, method_type, \19+ traceback_type, code_type, frame_type, generator_type20 21 22 #: maximum number of items a range may produce23 MAX_RANGE = 10000099 unmodified lines123 True124 >>> is_internal_attribute(str, "upper")125 False126 """128- if isinstance(obj, FunctionType):127+ if isinstance(obj, function_type):128 if attr in UNSAFE_FUNCTION_ATTRIBUTES:129 return True131- elif isinstance(obj, MethodType):130+ elif isinstance(obj, method_type):131 if attr in UNSAFE_FUNCTION_ATTRIBUTES or \132 attr in UNSAFE_METHOD_ATTRIBUTES:133 return True134 elif isinstance(obj, type):135 if attr == 'mro':136 return True138- elif isinstance(obj, (CodeType, TracebackType, FrameType)):137+ elif isinstance(obj, (code_type, traceback_type, frame_type)):138 return True140- elif isinstance(obj, GeneratorType):139+ elif isinstance(obj, generator_type):140 if attr == 'gi_frame':141 return True142 return attr.startswith('__')143 154 unmodified lines298 """Subscribe an object from sandboxed code."""299 try:300 return obj[argument]301 except (TypeError, LookupError):303- if isinstance(argument, six.string_types):302+ if isinstance(argument, string_types):303 try:304 attr = str(argument)305 except Exception:306 pass55 unmodified linesmodified:jinja2/tests.py+5 added-14 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import re12 from jinja2.runtime import Undefined13-import six13+from jinja2._compat import text_type, string_types, mapping_types14 15-try:16- from collections import Mapping as MappingType17-except ImportError:18- import UserDict19- MappingType = (UserDict.UserDict, UserDict.DictMixin, dict)15 21-# nose, nothing here to test22-__test__ = False23-24-16 number_re = re.compile(r'^-?\d+(\.\d+)?$')17 regex_type = type(number_re)18 19 47 unmodified lines67 68 69 def test_lower(value):70 """Return true if the variable is lowercased."""80- return six.text_type(value).islower()71+ return text_type(value).islower()72 73 74 def test_upper(value):75 """Return true if the variable is uppercased."""85- return six.text_type(value).isupper()76+ return text_type(value).isupper()77 78 79 def test_string(value):80 """Return true if the object is a string."""90- return isinstance(value, six.string_types)81+ return isinstance(value, string_types)82 83 84 def test_mapping(value):85 """Return true if the object is a mapping (dict etc.).86 87 .. versionadded:: 2.688 """98- return isinstance(value, MappingType)89+ return isinstance(value, mapping_types)90 91 92 def test_number(value):93 """Return true if the variable is a number."""60 unmodified linesmodified:jinja2/utils.py+8 added-28 removed
9 unmodified lines10 """11 import re12 import sys13 import errno14-import six15-from six.moves import map14 try:15 from urllib.parse import quote_from_bytes as url_quote16 except ImportError:17 from urllib import quote as url_quote4 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, Iterator27 28+29 _word_split_re = re.compile(r'(\s+)')30 _punctuation_re = re.compile(31 '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (32 '|'.join(map(re.escape, ('(', '<', '<'))),33 unmodified lines66 67 from keyword import iskeyword as is_python_keyword68 69 70-# common types. These do exist in the special types module too which however71-# does not exist in IronPython out of the box. Also that way we don't have72-# to deal with implementation specific stuff here73-class _C(object):74- def method(self): pass75-def _func():76- yield None77-FunctionType = type(_func)78-GeneratorType = type(_func())79-MethodType = type(_C().method)80-CodeType = type(_C.method.__code__)81-try:82- raise TypeError()83-except TypeError:84- _tb = sys.exc_info()[2]85- TracebackType = type(_tb)86- FrameType = type(_tb.tb_frame)87-del _C, _tb, _func88-89-70 def contextfunction(f):71 """This decorator can be used to mark a function or method context callable.72 A context callable is passed the active :class:`Context` as first argument when73 called from the template. This is useful if a function wants to get access152 unmodified lines226 """227 trim_url = lambda x, limit=trim_url_limit: limit is not None \228 and (x[:limit] + (len(x) >=limit and '...'229 or '')) or x250- words = _word_split_re.split(six.text_type(escape(text)))230+ words = _word_split_re.split(text_type(escape(text)))231 nofollow_attr = nofollow and ' rel="nofollow"' or ''232 for i, word in enumerate(words):233 match = _punctuation_re.match(word)234 if match:78 unmodified lines313 314 If non strings are provided they are converted to their unicode315 representation first.316 """337- if not isinstance(obj, six.string_types):338- obj = six.text_type(obj)339- if isinstance(obj, six.text_type):317+ if not isinstance(obj, string_types):318+ obj = text_type(obj)319+ if isinstance(obj, text_type):320 obj = obj.encode(charset)341- return six.text_type(url_quote(obj))321+ return text_type(url_quote(obj))322 323 324 class LRUCache(object):325 """A simple LRU Cache implementation."""179 unmodified lines505 except ImportError:506 pass507 508 529-class Cycler(six.Iterator):509+class Cycler(Iterator):510 """A cycle helper for templates."""511 512 def __init__(self, *items):513 if not items:36 unmodified lines