python 3 port: manual fixes, remove 2to3 from setup.py, remove fixers
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Thomas Waldmann · committed by Thomas Waldmann · parent e000355 · Browse files · 28 files·+235 added−269 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
28 files+235 added−269 removed
- other:+235 added−269 removed
Provenance
- Commit
7d29562- Tree
abfb29d- Author
Thomas Waldmann <tw@waldmann-edv.de>- Committer
Thomas Waldmann <tw@waldmann-edv.de>- Parent
e000355
28 files changed+235 added−269 removed
deleted:custom_fixers/__init__.py
deleted:custom_fixers/fix_alt_unicode.py-13 removed
1-from lib2to3 import fixer_base2-from lib2to3.fixer_util import Name, BlankLine3-4-5-class FixAltUnicode(fixer_base.BaseFix):6- PATTERN = """7- func=funcdef< 'def' name='__unicode__'8- parameters< '(' NAME ')' > any+ >9- """10-11- def transform(self, node, results):12- name = results['name']13- name.replace(Name('__str__', prefix=name.prefix))deleted:custom_fixers/fix_broken_reraising.py-21 removed
1-from lib2to3 import fixer_base, pytree2-from lib2to3.fixer_util import Name, BlankLine, Name, Attr, ArgList3-4-5-class FixBrokenReraising(fixer_base.BaseFix):6- PATTERN = """7- raise_stmt< 'raise' any ',' val=any ',' tb=any >8- """9-10- # run before the broken 2to3 checker with the same goal11- # tries to rewrite it with a rule that does not work out for jinja12- run_order = 113-14- def transform(self, node, results):15- tb = results['tb'].clone()16- tb.prefix = ''17- with_tb = Attr(results['val'].clone(), Name('with_traceback')) + \18- [ArgList([tb])]19- new = pytree.Node(self.syms.simple_stmt, [Name("raise")] + with_tb)20- new.prefix = node.prefix21- return newdeleted:custom_fixers/fix_xrange2.py-11 removed
1-from lib2to3 import fixer_base2-from lib2to3.fixer_util import Name, BlankLine3-4-5-# whyever this is necessary..6-7-class FixXrange2(fixer_base.BaseFix):8- PATTERN = "'xrange'"9-10- def transform(self, node, results):11- node.replace(Name('range', prefix=node.prefix))modified:jinja2/_markupsafe/__init__.py+26 added-24 removed
7 unmodified lines8 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 import re12-from itertools import imap12 import six13 from six.moves import map14 from six.moves import zip15+try:16+ unichr = unichr # py217+except NameError:18+ unichr = chr # py319 17-20 __all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent']21 22 23 _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')24 _entity_re = re.compile(r'&([^;]+);')25 26 25-class Markup(unicode):27+class Markup(six.text_type):28 r"""Marks a string as being safe for inclusion in HTML/XML output without29 needing to be escaped. This implements the `__html__` interface a couple30 of frameworks and web applications use. :class:`Markup` is a direct31 subclass of `unicode` and provides all the methods of `unicode` just that40 unmodified lines72 def __new__(cls, base=u'', encoding=None, errors='strict'):73 if hasattr(base, '__html__'):74 base = base.__html__()75 if encoding is None:74- return unicode.__new__(cls, base)75- return unicode.__new__(cls, base, encoding, errors)76+ return six.text_type.__new__(cls, base)77+ return six.text_type.__new__(cls, base, encoding, errors)78 79 def __html__(self):80 return self81 82 def __add__(self, other):81- if hasattr(other, '__html__') or isinstance(other, basestring):83+ if hasattr(other, '__html__') or isinstance(other, six.string_types):84 return self.__class__(six.text_type(self) + six.text_type(escape(other)))85 return NotImplemented86 87 def __radd__(self, other):86- if hasattr(other, '__html__') or isinstance(other, basestring):88+ if hasattr(other, '__html__') or isinstance(other, six.string_types):89 return self.__class__(six.text_type(escape(other)) + six.text_type(self))90 return NotImplemented91 92 def __mul__(self, num):93 if isinstance(num, (int, long)):92- return self.__class__(unicode.__mul__(self, num))94+ return self.__class__(six.text_type.__mul__(self, num))95 return NotImplemented96 __rmul__ = __mul__97 98 def __mod__(self, arg):99 if isinstance(arg, tuple):98- arg = tuple(imap(_MarkupEscapeHelper, arg))100+ arg = tuple(map(_MarkupEscapeHelper, arg))101 else:102 arg = _MarkupEscapeHelper(arg)101- return self.__class__(unicode.__mod__(self, arg))103+ return self.__class__(six.text_type.__mod__(self, arg))104 105 def __repr__(self):106 return '%s(%s)' % (107 self.__class__.__name__,106- unicode.__repr__(self)108+ six.text_type.__repr__(self)109 )110 111 def join(self, seq):110- return self.__class__(unicode.join(self, imap(escape, seq)))111- join.__doc__ = unicode.join.__doc__112+ return self.__class__(six.text_type.join(self, map(escape, seq)))113+ join.__doc__ = six.text_type.join.__doc__114 115 def split(self, *args, **kwargs):114- return map(self.__class__, unicode.split(self, *args, **kwargs))115- split.__doc__ = unicode.split.__doc__116+ return map(self.__class__, six.text_type.split(self, *args, **kwargs))117+ split.__doc__ = six.text_type.split.__doc__118 119 def rsplit(self, *args, **kwargs):118- return map(self.__class__, unicode.rsplit(self, *args, **kwargs))119- rsplit.__doc__ = unicode.rsplit.__doc__120+ return map(self.__class__, six.text_type.rsplit(self, *args, **kwargs))121+ rsplit.__doc__ = six.text_type.rsplit.__doc__122 123 def splitlines(self, *args, **kwargs):122- return map(self.__class__, unicode.splitlines(self, *args, **kwargs))123- splitlines.__doc__ = unicode.splitlines.__doc__124+ return map(self.__class__, six.text_type.splitlines(self, *args, **kwargs))125+ splitlines.__doc__ = six.text_type.splitlines.__doc__126 127 def unescape(self):128 r"""Unescape markup again into an unicode string. This also resolves129 known HTML4 and XHTML entities:38 unmodified lines168 return cls(rv)169 return rv170 171 def make_wrapper(name):170- orig = getattr(unicode, name)172+ orig = getattr(six.text_type, name)173 def func(self, *args, **kwargs):174 args = _escape_argspec(list(args), enumerate(args))175 _escape_argspec(kwargs, six.iteritems(kwargs))176 return self.__class__(orig(self, *args, **kwargs))7 unmodified lines184 'translate', 'expandtabs', 'swapcase', 'zfill':185 locals()[method] = make_wrapper(method)186 187 # new in python 2.5186- if hasattr(unicode, 'partition'):188+ if hasattr(six.text_type, 'partition'):189 partition = make_wrapper('partition'),190 rpartition = make_wrapper('rpartition')191 192 # new in python 2.6191- if hasattr(unicode, 'format'):193+ if hasattr(six.text_type, 'format'):194 format = make_wrapper('format')195 196 # not in python 3195- if hasattr(unicode, '__getslice__'):197+ if hasattr(six.text_type, '__getslice__'):198 __getslice__ = make_wrapper('__getslice__')199 200 del method, make_wrapper201 202 203 def _escape_argspec(obj, iterable):204 """Helper for various string-wrapped functions."""205 for key, value in iterable:204- if hasattr(value, '__html__') or isinstance(value, basestring):206+ if hasattr(value, '__html__') or isinstance(value, six.string_types):207 obj[key] = escape(value)208 return obj209 210 20 unmodified linesmodified:jinja2/_markupsafe/_native.py+1 added-1 removed
39 unmodified lines40 def soft_unicode(s):41 """Make a string unicode if it isn't already. That way a markup42 string is not converted back to unicode.43 """44- if not isinstance(s, unicode):44+ if not isinstance(s, six.text_type):45 s = six.text_type(s)46 return smodified:jinja2/testsuite/ext.py+3 added-10 removed
15 unmodified lines16 from jinja2 import Environment, DictLoader, contextfunction, nodes17 from jinja2.exceptions import TemplateAssertionError18 from jinja2.ext import Extension19 from jinja2.lexer import Token, count_newlines20-from jinja2.utils import next20 import six21+from six import BytesIO22 23-# 2.x / 3.x24-try:25- from io import BytesIO26-except ImportError:27- from StringIO import StringIO as BytesIO28-29-23 importable_object = 2324 25 _gettext_re = re.compile(r'_\((.*?)\)(?s)')26 81 unmodified lines108 nodes.EnvironmentAttribute('sandboxed'),109 self.attr('ext_attr'),110 nodes.ImportedName(__name__ + '.importable_object'),111 nodes.ContextReference()119- ])]).set_lineno(next(parser.stream).lineno)112+ ])]).set_lineno(six.advance_iterator(parser.stream).lineno)113 114 def _dump(self, sandboxed, ext_attr, imported_object, context):115 return '%s|%s|%s|%s' % (116 sandboxed,308 unmodified lines425 {{ '<testing>' }}426 '''427 tmpl = env.from_string(tmplsource)428 assert tmpl.render(val=True).split()[0] == 'Markup'436- assert tmpl.render(val=False).split()[0] == unicode.__name__429+ assert tmpl.render(val=False).split()[0] == six.text_type.__name__430 431 # looking at the source we should see <testing> there in raw432 # (and then escaped as well)433 env = Environment(extensions=['jinja2.ext.autoescape'])16 unmodified linesmodified:jinja2/testsuite/filters.py+2 added-2 removed
11 unmodified lines12 from jinja2.testsuite import JinjaTestCase13 14 from jinja2 import Markup, Environment15 import six16-from six.moves import map17-from six.moves import zip16+from six.moves import map, zip17 18 env = Environment()19 20 278 unmodified lines299 def __init__(self, value):300 self.value = value301 def __unicode__(self):302 return six.text_type(self.value)303+ __str__ = __unicode__304 tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')305 assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'306 307 def test_groupby(self):92 unmodified linesmodified:jinja2/testsuite/lexnparse.py+26 added
13 unmodified lines14 from jinja2.testsuite import JinjaTestCase15 16 from jinja2 import Environment, Template, TemplateSyntaxError, \17 UndefinedError, nodes18+from jinja2.lexer import Token, TokenStream, TOKEN_EOF, TOKEN_BLOCK_BEGIN, TOKEN_BLOCK_END19 import six20 21 env = Environment()22 5 unmodified lines28 else:29 jinja_string_repr = repr30 31 32+class TokenStreamTestCase(JinjaTestCase):33+ test_tokens = [Token(1, TOKEN_BLOCK_BEGIN, ''),34+ Token(2, TOKEN_BLOCK_END, ''),35+ ]36+37+ def test_simple(self):38+ ts = TokenStream(self.test_tokens, "foo", "bar")39+ assert ts.current.type is TOKEN_BLOCK_BEGIN40+ assert bool(ts)41+ assert not bool(ts.eos)42+ six.advance_iterator(ts)43+ assert ts.current.type is TOKEN_BLOCK_END44+ assert bool(ts)45+ assert not bool(ts.eos)46+ six.advance_iterator(ts)47+ assert ts.current.type is TOKEN_EOF48+ assert not bool(ts)49+ assert bool(ts.eos)50+51+ def test_iter(self):52+ token_types = [t.type for t in TokenStream(self.test_tokens, "foo", "bar")]53+ assert token_types == ['block_begin', 'block_end', ]54+55+56 class LexerTestCase(JinjaTestCase):57 58 def test_raw1(self):59 tmpl = env.from_string('{% raw %}foo{% endraw %}|'346 unmodified lines406 407 408 def suite():409 suite = unittest.TestSuite()410+ suite.addTest(unittest.makeSuite(TokenStreamTestCase))411 suite.addTest(unittest.makeSuite(LexerTestCase))412 suite.addTest(unittest.makeSuite(ParserTestCase))413 suite.addTest(unittest.makeSuite(SyntaxTestCase))414 return suitemodified:jinja2/testsuite/regression.py+2 added-1 removed
12 unmodified lines13 from jinja2.testsuite import JinjaTestCase14 15 from jinja2 import Template, Environment, DictLoader, TemplateSyntaxError, \16 TemplateNotFound, PrefixLoader17+import six18 from six.moves import map19 from six.moves import zip20 21 env = Environment()98 unmodified lines120 {% endfor %}121 122 ''')123 123- assert tmpl.render().split() == map(unicode, list(range(1, 11))) * 5124+ assert tmpl.render().split() == [six.text_type(x) for x in range(1, 11)] * 5125 126 def test_weird_inline_comment(self):127 env = Environment(line_statement_prefix='%')128 self.assert_raises(TemplateSyntaxError, env.from_string,130 unmodified linesmodified:jinja2/bccache.py+1 added-1 removed
16 unmodified lines17 from os import path, listdir18 import sys19 import marshal20 import tempfile21-import cPickle as pickle21+from six.moves import cPickle as pickle22 import fnmatch23 try:24 from hashlib import sha125 except ImportError:276 unmodified linesmodified:jinja2/compiler.py+11 added-9 removed
6 unmodified lines7 8 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11-from cStringIO import StringIO11 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 TemplateAssertionError18-from jinja2.utils import Markup, concat, escape, is_python_keyword, next17+from jinja2.utils import Markup, concat, escape, is_python_keyword18 import six20-from six.moves import map21-from six.moves import zip19+from six.moves import cStringIO as StringIO20+from six.moves import map, zip21 22 23 operators = {24 'eq': '==',45 unmodified lines70 def has_safe_repr(value):71 """Does the node have a safe representation?"""72 if value is None or value is NotImplemented or value is Ellipsis:73 return True75- if isinstance(value, (bool, int, long, float, complex, basestring,76- xrange, Markup)):74+ try:75+ range_type = xrange76+ except NameError:77+ range_type = range78+ if isinstance(value, (bool, int, float, complex, range_type, Markup) + six.string_types):79 return True80 if isinstance(value, (tuple, list, set, frozenset)):81 for item in value:82 if not has_safe_repr(item):851 unmodified lines934 self.indent()935 936 func_name = 'get_or_select_template'937 if isinstance(node.template, nodes.Const):936- if isinstance(node.template.value, basestring):938+ if isinstance(node.template.value, six.string_types):939 func_name = 'get_template'940 elif isinstance(node.template.value, (tuple, list)):941 func_name = 'select_template'942 elif isinstance(node.template, (nodes.Tuple, nodes.List)):279 unmodified lines1222 1223 if self.environment.finalize:1224 finalize = lambda x: six.text_type(self.environment.finalize(x))1225 else:1224- finalize = unicode1226+ finalize = six.text_type1227 1228 # if we are inside a frame that requires output checking, we do so1229 outdent_later = False1230 if frame.require_output_check:125 unmodified lines1356 if frame.toplevel:1357 public_names = [x for x in assignment_frame.toplevel_assignments1358 if not x.startswith('_')]1359 if len(assignment_frame.toplevel_assignments) == 1:1358- name = next(iter(assignment_frame.toplevel_assignments))1360+ name = six.advance_iterator(iter(assignment_frame.toplevel_assignments))1361 self.writeline('context.vars[%r] = l_%s' % (name, name))1362 else:1363 self.writeline('context.vars.update({')1364 for idx, name in enumerate(assignment_frame.toplevel_assignments):290 unmodified linesmodified:jinja2/debug.py+1 added-1 removed
188 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- raise exc_info[0], exc_info[1], exc_info[2]193+ six.reraise(exc_info[0], exc_info[1], exc_info[2])194 195 return ProcessedTraceback(exc_info[0], exc_info[1], frames)196 197 143 unmodified linesmodified:jinja2/defaults.py+1 added
6 unmodified lines7 8 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11+from six.moves import xrange12 from jinja2.utils import generate_lorem_ipsum, Cycler, Joiner13 14 15 # defaults for the parser / lexer26 unmodified linesmodified:jinja2/environment.py+13 added-18 removed
21 unmodified lines22 from jinja2.utils import import_string, LRUCache, Markup, missing, \23 concat, consume, internalcode, _encode_filename24 import six25 from functools import reduce26-from six.moves import filter27-from six.moves import map28-from six.moves import zip26+from six.moves import filter, map, zip27 28 29 # for direct template usage we have up to ten living environments30 _spontaneous_environments = LRUCache(10)42 unmodified lines73 Returns a dict of instantiated environments.74 """75 result = {}76 for extension in extensions:79- if isinstance(extension, basestring):77+ if isinstance(extension, six.string_types):78 extension = import_string(extension)79 result[extension.identifier] = extension(environment)80 return result81 272 unmodified lines354 """Get an item or attribute of an object but prefer the item."""355 try:356 return obj[argument]357 except (TypeError, LookupError):360- if isinstance(argument, basestring):358+ if isinstance(argument, six.string_types):359 try:360 attr = str(argument)361 except Exception:362 pass113 unmodified lines476 `defer_init` parameter added.477 """478 source_hint = None479 try:482- if isinstance(source, basestring):480+ if isinstance(source, six.string_types):481 source_hint = source482 source = self._parse(source, name, filename)483 if self.optimized:484 source = optimize(source, self)188 unmodified lines673 return self.exception_formatter(traceback)674 if self.exception_handler is not None:675 self.exception_handler(traceback)676 exc_type, exc_value, tb = traceback.standard_exc_info679- raise exc_type, exc_value, tb677+ six.reraise(exc_type, exc_value, tb)678 679 def join_path(self, template, parent):680 """Join a template with the parent. By default all the lookups are681 relative to the loader root so this method returns the `template`78 unmodified lines760 :meth:`get_template`.761 762 .. versionadded:: 2.3763 """766- if isinstance(template_name_or_list, basestring):764+ if isinstance(template_name_or_list, six.string_types):765 return self.get_template(template_name_or_list, parent, globals)766 elif isinstance(template_name_or_list, Template):767 return template_name_or_list768 return self.select_template(template_name_or_list, parent, globals)236 unmodified lines1005 def __html__(self):1006 return Markup(concat(self._body_stream))1007 1008 def __str__(self):1009+ s = self.__unicode__()1011- return six.text_type(self).encode('utf-8')1010+ return s if six.PY3 else s.encode('utf-8')1011 1013- # unicode goes after __str__ because we configured 2to3 to rename1014- # __unicode__ to __str__. because the 2to3 tree is not designed to1015- # remove nodes from it, we leave the above __str__ around and let1016- # it override at runtime.1012 def __unicode__(self):1013 return concat(self._body_stream)1014 1015 def __repr__(self):22 unmodified lines1038 rv = None1039 return rv1040 1041 1047-class TemplateStream(object):1042+class TemplateStream(six.Iterator):1043 """A template stream works pretty much like an ordinary python generator1044 but it can buffer multiple items to reduce the number of total iterations.1045 Per default the output is unbuffered which means that for every unbuffered1046 instruction in the template one unicode string is yielded.16 unmodified lines1063 1064 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1065 """1066 close = False1072- if isinstance(fp, basestring):1067+ if isinstance(fp, six.string_types):1068 fp = file(fp, 'w')1069 close = True1070 try:1071 if encoding is not None:10 unmodified lines1082 fp.close()1083 1084 def disable_buffering(self):1085 """Disable the output buffering."""1091- self._next = self._gen.next1086+ self._next = lambda: six.next(self._gen)1087 self.buffered = False1088 1089 def enable_buffering(self, size=5):1090 """Enable buffering. Buffer `size` items before yielding them."""19 unmodified lines1110 del buf[:]1111 c_size = 01112 1113 self.buffered = True1119- self._next = generator(self._gen.next).next1114+ self._next = lambda: six.next(generator(lambda: six.next(self._gen)))1115 1116 def __iter__(self):1117 return self1118 1124- def next(self):1119+ def __next__(self):1120 return self._next()1121 1122 1123 # hook in default template class. if anyone reads this comment: ignore that2 unmodified linesmodified:jinja2/exceptions.py+4 added-8 removed
7 unmodified lines8 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11 import six12-from six.moves import map13-from six.moves import zip12+from six.moves import map, zip13 14 15 class TemplateError(Exception):16 """Baseclass for all template errors."""47 unmodified lines64 65 def __init__(self, names=(), message=None):66 if message is None:67 message = u'none of the templates given were found: ' + \69- u', '.join(map(unicode, names))68+ u', '.join(map(six.text_type, names))69 TemplateNotFound.__init__(self, names and names[-1] or None, message)70 self.templates = list(names)71 72 11 unmodified lines84 # function translated the syntax error into a new traceback85 self.translated = False86 87 def __str__(self):88+ s = self.__unicode__()89- return six.text_type(self).encode('utf-8')89+ return s if six.PY3 else s.encode('utf-8')90 91- # unicode goes after __str__ because we configured 2to3 to rename92- # __unicode__ to __str__. because the 2to3 tree is not designed to93- # remove nodes from it, we leave the above __str__ around and let94- # it override at runtime.91 def __unicode__(self):92 # for translated errors we only return the message93 if self.translated:94 return self.message48 unmodified linesmodified:jinja2/ext.py+16 added-16 removed
14 unmodified lines15 from jinja2.defaults import *16 from jinja2.environment import Environment17 from jinja2.runtime import Undefined, concat18 from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError19-from jinja2.utils import contextfunction, import_string, Markup, next19+from jinja2.utils import contextfunction, import_string, Markup20 import six21 22 23 # the only real useful gettext functions for a Jinja template. Note10 unmodified lines34 rv.identifier = rv.__module__ + '.' + rv.__name__35 return rv36 37 38-class Extension(object):38+class Extension(six.with_metaclass(ExtensionRegistry, object)):39 """Extensions can be used to add extra functionality to the Jinja template40 system at the parser level. Custom extensions are bound to an environment41 but may not store environment specific data on `self`. The reason for42 this is that an extension can be bound to another environment (for162 unmodified lines205 for key in 'gettext', 'ngettext':206 self.environment.globals.pop(key, None)207 208 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):209- if isinstance(source, basestring):209+ if isinstance(source, six.string_types):210 source = self.environment.parse(source)211 return extract_from_ast(source, gettext_functions)212 213 def parse(self, parser):214 """Parse a translatable tag."""215- lineno = next(parser.stream).lineno215+ lineno = six.advance_iterator(parser.stream).lineno216 num_called_num = False217 218 # find all the variables referenced. Additionally a variable can be219 # defined in the body of the trans block too, but this is checked at15 unmodified lines235 exc=TemplateAssertionError)236 237 # expressions238 if parser.stream.current.type == 'assign':239- next(parser.stream)239+ six.advance_iterator(parser.stream)240 variables[name.value] = var = parser.parse_expression()241 else:242 variables[name.value] = var = nodes.Name(name.value, 'load')243 17 unmodified lines261 262 # if we have a pluralize block, we parse that too263 if parser.stream.current.test('name:pluralize'):264 have_plural = True265- next(parser.stream)265+ six.advance_iterator(parser.stream)266 if parser.stream.current.type != 'block_end':267 name = parser.stream.expect('name')268 if name.value not in variables:269 parser.fail('unknown variable %r for pluralization' %2 unmodified lines272 plural_expr = variables[name.value]273 num_called_num = name.value == 'num'274 parser.stream.expect('block_end')275 plural_names, plural = self._parse_block(parser, False)276- next(parser.stream)276+ six.advance_iterator(parser.stream)277 referenced.update(plural_names)278 else:279- next(parser.stream)279+ six.advance_iterator(parser.stream)280 281 # register free names as simple name expressions282 for var in referenced:283 if var not in variables:16 unmodified lines300 buf = []301 while 1:302 if parser.stream.current.type == 'data':303 buf.append(parser.stream.current.value.replace('%', '%%'))304- next(parser.stream)304+ six.advance_iterator(parser.stream)305 elif parser.stream.current.type == 'variable_begin':306- next(parser.stream)306+ six.advance_iterator(parser.stream)307 name = parser.stream.expect('name').value308 referenced.append(name)309 buf.append('%%(%s)s' % name)310 parser.stream.expect('variable_end')311 elif parser.stream.current.type == 'block_begin':312- next(parser.stream)312+ six.advance_iterator(parser.stream)313 if parser.stream.current.test('name:endtrans'):314 break315 elif parser.stream.current.test('name:pluralize'):316 if allow_pluralize:64 unmodified lines381 """382 tags = set(['do'])383 384 def parse(self, parser):385- node = nodes.ExprStmt(lineno=next(parser.stream).lineno)385+ node = nodes.ExprStmt(lineno=six.advance_iterator(parser.stream).lineno)386 node.node = parser.parse_tuple()387 return node388 389 1 unmodified line391 """Adds break and continue to the template engine."""392 tags = set(['break', 'continue'])393 394 def parse(self, parser):395- token = next(parser.stream)395+ token = six.advance_iterator(parser.stream)396 if token.value == 'break':397 return nodes.Break(lineno=token.lineno)398 return nodes.Continue(lineno=token.lineno)399 2 unmodified lines402 """Adds support for a django-like with block."""403 tags = set(['with'])404 405 def parse(self, parser):406- node = nodes.Scope(lineno=next(parser.stream).lineno)406+ node = nodes.Scope(lineno=six.advance_iterator(parser.stream).lineno)407 assignments = []408 while parser.stream.current.type != 'block_end':409 lineno = parser.stream.current.lineno410 if assignments:12 unmodified lines423 """Changes auto escape rules for a scope."""424 tags = set(['autoescape'])425 426 def parse(self, parser):427- node = nodes.ScopedEvalContextModifier(lineno=next(parser.stream).lineno)427+ node = nodes.ScopedEvalContextModifier(lineno=six.advance_iterator(parser.stream).lineno)428 node.options = [429 nodes.Keyword('autoescape', parser.parse_expression())430 ]431 node.body = parser.parse_statements(('name:endautoescape',),44 unmodified lines476 477 strings = []478 for arg in node.args:479 if isinstance(arg, nodes.Const) and \480- isinstance(arg.value, basestring):480+ isinstance(arg.value, six.string_types):481 strings.append(arg.value)482 else:483 strings.append(None)484 137 unmodified linesmodified:jinja2/filters.py+11 added-12 removed
10 unmodified lines11 import re12 import math13 from random import choice14 from operator import itemgetter15-from itertools import imap, groupby15+from itertools import groupby16 from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode, \17 unicode_urlencode18 from jinja2.runtime import Undefined19 from jinja2.exceptions import FilterArgumentError20 import six21-from six.moves import map22-from six.moves import zip21+from six.moves import map, zip22 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 """60- if not isinstance(attribute, basestring) or '.' not in attribute:59+ if not isinstance(attribute, six.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:17 unmodified lines81 """82 itemiter = None83 if isinstance(value, dict):84 itemiter = six.iteritems(value)86- elif not isinstance(value, basestring):85+ elif not isinstance(value, six.string_types):86 try:87 itemiter = iter(value)88 except TypeError:89 pass121 unmodified lines211 raise FilterArgumentError('You can only sort by either '212 '"key" or "value"')213 def sort_func(item):214 value = item[pos]216- if isinstance(value, basestring) and not case_sensitive:215+ if isinstance(value, six.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):253- if isinstance(item, basestring):252+ if isinstance(item, six.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:311- value = imap(make_attrgetter(eval_ctx.environment, attribute), value)310+ value = map(make_attrgetter(eval_ctx.environment, attribute), value)311 312 # no automatic escaping? joining is a lot eaiser then313 if not eval_ctx.autoescape:315- return six.text_type(d).join(imap(unicode, value))314+ return six.text_type(d).join(map(six.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__'):10 unmodified lines329 d = six.text_type(d)330 return d.join(value)331 332 # no html involved, to normal joining334- return soft_unicode(d).join(imap(soft_unicode, value))333+ return soft_unicode(d).join(map(soft_unicode, value))334 335 336 def do_center(value, width=80):337 """Centers the value in a field of a given width."""377 unmodified lines715 The `attribute` parameter was added to allow suming up over716 attributes. Also the `start` parameter was moved on to the right.717 """718 if attribute is not None:720- iterable = imap(make_attrgetter(environment, attribute), iterable)719+ iterable = map(make_attrgetter(environment, attribute), iterable)720 return sum(iterable, start)721 722 723 def do_list(value):18 unmodified lines742 def do_reverse(value):743 """Reverse the object or return an iterator the iterates over it the other744 way round.745 """747- if isinstance(value, basestring):746+ if isinstance(value, six.string_types):747 return value[::-1]748 try:749 return reversed(value)750 except TypeError:81 unmodified linesmodified:jinja2/lexer.py+22 added-15 removed
16 unmodified lines17 import re18 from operator import itemgetter19 from collections import deque20 from jinja2.exceptions import TemplateSyntaxError21-from jinja2.utils import LRUCache, next21+from jinja2.utils import LRUCache22 import six23 24 25 # cache for the lexers. Exists in order to be able to have multiple19 unmodified lines45 46 float_re = re.compile(r'(?<!\.)\d+\.\d+')47 newline_re = re.compile(r'(\r\n|\r|\n)')48 49+try:50+ intern = intern # py251+except NameError:52+ import sys53+ intern = sys.intern # py354+55 # internal the tokens and keep references to them56 TOKEN_ADD = intern('add')57 TOKEN_ASSIGN = intern('assign')58 TOKEN_COLON = intern('colon')209 unmodified lines268 self.value269 )270 271 266-class TokenStreamIterator(object):272+class TokenStreamIterator(six.Iterator):273 """The iterator for tokenstreams. Iterate over the stream274 until the eof token is reached.275 """276 2 unmodified lines279 280 def __iter__(self):281 return self282 277- def next(self):283+ def __next__(self):284 token = self.stream.current285 if token.type is TOKEN_EOF:286 self.stream.close()287 raise StopIteration()282- next(self.stream)288+ six.advance_iterator(self.stream)289 return token290 291 286-class TokenStream(object):292+class TokenStream(six.Iterator):293 """A token stream is an iterable that yields :class:`Token`\s. The294 parser however does not iterate over it but calls :meth:`next` to go295 one token ahead. The current active token is stored as :attr:`current`.296 """297 298 def __init__(self, generator, name, filename):293- self._next = iter(generator).next299+ self._iter = iter(generator)300 self._pushed = deque()301 self.name = name302 self.filename = filename303 self.closed = False304 self.current = Token(1, TOKEN_INITIAL, '')299- next(self)305+ six.advance_iterator(self)306 307 def __iter__(self):308 return TokenStreamIterator(self)309 304- def __nonzero__(self):310+ def __bool__(self):311 return bool(self._pushed) or self.current.type is not TOKEN_EOF312+ __nonzero__ = __bool__ # py2313 314 eos = property(lambda x: not x, doc="Are we at the end of the stream?")315 316 def push(self, token):1 unmodified line318 self._pushed.append(token)319 320 def look(self):321 """Look at the next token."""315- old_token = next(self)322+ old_token = six.advance_iterator(self)323 result = self.current324 self.push(result)325 self.current = old_token326 return result327 328 def skip(self, n=1):329 """Got n tokens ahead."""330 for x in range(n):324- next(self)331+ six.advance_iterator(self)332 333 def next_if(self, expr):334 """Perform the token test and return the token if it matched.335 Otherwise the return value is `None`.336 """337 if self.current.test(expr):331- return next(self)338+ return six.advance_iterator(self)339 340 def skip_if(self, expr):341 """Like :meth:`next_if` but only returns `True` or `False`."""342 return self.next_if(expr) is not None343 337- def next(self):344+ def __next__(self):345 """Go one token ahead and return the old one"""346 rv = self.current347 if self._pushed:348 self.current = self._pushed.popleft()349 elif self.current.type is not TOKEN_EOF:350 try:344- self.current = self._next()351+ self.current = six.advance_iterator(self._iter)352 except StopIteration:353 self.close()354 return rv355 356 def close(self):357 """Close the stream."""358 self.current = Token(self.current.lineno, TOKEN_EOF, '')352- self._next = None359+ self._iter = None360 self.closed = True361 362 def expect(self, expr):363 """Expect a given token type and return it. This accepts the same12 unmodified lines376 self.name, self.filename)377 try:378 return self.current379 finally:373- next(self)380+ six.advance_iterator(self)381 382 383 def get_lexer(environment):384 """Return a lexer which is probably cached."""305 unmodified linesmodified:jinja2/loaders.py+3 added-3 removed
152 unmodified lines153 by setting the `encoding` parameter to something else.154 """155 156 def __init__(self, searchpath, encoding='utf-8'):157- if isinstance(searchpath, basestring):157+ if isinstance(searchpath, six.string_types):158 searchpath = [searchpath]159 self.searchpath = list(searchpath)160 self.encoding = encoding161 144 unmodified lines306 def get_source(self, environment, template):307 rv = self.load_func(template)308 if rv is None:309 raise TemplateNotFound(template)310- elif isinstance(rv, basestring):310+ elif isinstance(rv, six.string_types):311 return rv, None, None312 return rv313 314 116 unmodified lines431 432 # create a fake module that looks for the templates in the433 # path given.434 mod = _TemplateModule(package_name)435- if isinstance(path, basestring):435+ if isinstance(path, six.string_types):436 path = [path]437 else:438 path = list(path)439 mod.__path__ = path35 unmodified linesmodified:jinja2/meta.py+4 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 six15 15-16 class TrackingCodeGenerator(CodeGenerator):17 """We abuse the code generator for introspection."""18 19 def __init__(self, environment):56 unmodified lines76 for template_name in node.template.items:77 # something const, only yield the strings and ignore78 # non-string consts that really just make no sense79 if isinstance(template_name, nodes.Const):80- if isinstance(template_name.value, basestring):80+ if isinstance(template_name.value, six.string_types):81 yield template_name.value82 # something dynamic in there83 else:84 yield None1 unmodified line86 else:87 yield None88 continue89 # constant is a basestring, direct template name90- if isinstance(node.template.value, basestring):90+ if isinstance(node.template.value, six.string_types):91 yield node.template.value92 # a tuple or list (latter *should* not happen) made of consts,93 # yield the consts that are strings. We could warn here for94 # non string values95 elif isinstance(node, nodes.Include) and \96 isinstance(node.template.value, (tuple, list)):97 for template_name in node.template.value:98- if isinstance(template_name, basestring):98+ if isinstance(template_name, six.string_types):99 yield template_name100 # something else we don't care about, we could warn here101 else:102 yield Nonemodified:jinja2/nodes.py+3 added-3 removed
11 unmodified lines12 :copyright: (c) 2010 by the Jinja Team.13 :license: BSD, see LICENSE for more details.14 """15 import operator16-from itertools import chain, izip16 from collections import deque17 from jinja2.utils import Markup, MethodType, FunctionType18 import six19+from six.moves import zip20 21 22 #: the types we support for context functions23 _context_function_types = (FunctionType, MethodType)78 unmodified lines102 return EvalContext(node.environment)103 return ctx104 105 106-class Node(object):106+class Node(six.with_metaclass(NodeType, object)):107 """Baseclass for all Jinja2 nodes. There are a number of nodes available108 of different types. There are three major types:109 110 - :class:`Stmt`: statements25 unmodified lines136 self.__class__.__name__,137 len(self.fields),138 len(self.fields) != 1 and 's' or ''139 ))140- for name, arg in izip(self.fields, fields):140+ for name, arg in zip(self.fields, fields):141 setattr(self, name, arg)142 for attr in self.attributes:143 setattr(self, attr, attributes.pop(attr, None))144 if attributes:767 unmodified linesmodified:jinja2/parser.py+49 added-50 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from jinja2 import nodes12 from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError13-from jinja2.utils import next13 from jinja2.lexer import describe_token, describe_token_expr15-from six.moves import map16-from six.moves import zip14+import six15+from six.moves import map, zip16 17 18 #: statements that callinto 19 _statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',142 unmodified lines162 if self.stream.current.type == 'eof':163 self.fail_eof(end_tokens)164 165 if drop_needle:167- next(self.stream)166+ six.advance_iterator(self.stream)167 return result168 169 def parse_set(self):170 """Parse an assign statement."""172- lineno = next(self.stream).lineno171+ lineno = six.advance_iterator(self.stream).lineno172 target = self.parse_assign_target()173 self.stream.expect('assign')174 expr = self.parse_tuple()175 return nodes.Assign(target, expr, lineno=lineno)9 unmodified lines185 if self.stream.skip_if('name:if'):186 test = self.parse_expression()187 recursive = self.stream.skip_if('name:recursive')188 body = self.parse_statements(('name:endfor', 'name:else'))190- if next(self.stream).value == 'endfor':189+ if six.advance_iterator(self.stream).value == 'endfor':190 else_ = []191 else:192 else_ = self.parse_statements(('name:endfor',), drop_needle=True)193 return nodes.For(target, iter, body, else_, test,5 unmodified lines199 while 1:200 node.test = self.parse_tuple(with_condexpr=False)201 node.body = self.parse_statements(('name:elif', 'name:else',202 'name:endif'))204- token = next(self.stream)203+ token = six.advance_iterator(self.stream)204 if token.test('name:elif'):205 new_node = nodes.If(lineno=self.stream.current.lineno)206 node.else_ = [new_node]207 node = new_node6 unmodified lines214 break215 return result216 217 def parse_block(self):219- node = nodes.Block(lineno=next(self.stream).lineno)218+ node = nodes.Block(lineno=six.advance_iterator(self.stream).lineno)219 node.name = self.stream.expect('name').value220 node.scoped = self.stream.skip_if('name:scoped')221 222 # common problem people encounter when switching from django8 unmodified lines231 self.stream.skip_if('name:' + node.name)232 return node233 234 def parse_extends(self):236- node = nodes.Extends(lineno=next(self.stream).lineno)235+ node = nodes.Extends(lineno=six.advance_iterator(self.stream).lineno)236 node.template = self.parse_expression()237 return node238 239 def parse_import_context(self, node, default):240 if self.stream.current.test_any('name:with', 'name:without') and \241 self.stream.look().test('name:context'):243- node.with_context = next(self.stream).value == 'with'242+ node.with_context = six.advance_iterator(self.stream).value == 'with'243 self.stream.skip()244 else:245 node.with_context = default246 return node247 248 def parse_include(self):250- node = nodes.Include(lineno=next(self.stream).lineno)249+ node = nodes.Include(lineno=six.advance_iterator(self.stream).lineno)250 node.template = self.parse_expression()251 if self.stream.current.test('name:ignore') and \252 self.stream.look().test('name:missing'):253 node.ignore_missing = True2 unmodified lines256 node.ignore_missing = False257 return self.parse_import_context(node, True)258 259 def parse_import(self):261- node = nodes.Import(lineno=next(self.stream).lineno)260+ node = nodes.Import(lineno=six.advance_iterator(self.stream).lineno)261 node.template = self.parse_expression()262 self.stream.expect('name:as')263 node.target = self.parse_assign_target(name_only=True).name264 return self.parse_import_context(node, False)265 266 def parse_from(self):268- node = nodes.FromImport(lineno=next(self.stream).lineno)267+ node = nodes.FromImport(lineno=six.advance_iterator(self.stream).lineno)268 node.template = self.parse_expression()269 self.stream.expect('name:import')270 node.names = []271 272 def parse_context():273 if self.stream.current.value in ('with', 'without') and \274 self.stream.look().test('name:context'):276- node.with_context = next(self.stream).value == 'with'275+ node.with_context = six.advance_iterator(self.stream).value == 'with'276 self.stream.skip()277 return True278 return False279 36 unmodified lines316 args.append(arg)317 self.stream.expect('rparen')318 319 def parse_call_block(self):321- node = nodes.CallBlock(lineno=next(self.stream).lineno)320+ node = nodes.CallBlock(lineno=six.advance_iterator(self.stream).lineno)321 if self.stream.current.type == 'lparen':322 self.parse_signature(node)323 else:324 node.args = []5 unmodified lines330 node.body = self.parse_statements(('name:endcall',), drop_needle=True)331 return node332 333 def parse_filter_block(self):335- node = nodes.FilterBlock(lineno=next(self.stream).lineno)334+ node = nodes.FilterBlock(lineno=six.advance_iterator(self.stream).lineno)335 node.filter = self.parse_filter(None, start_inline=True)336 node.body = self.parse_statements(('name:endfilter',),337 drop_needle=True)338 return node339 340 def parse_macro(self):342- node = nodes.Macro(lineno=next(self.stream).lineno)341+ node = nodes.Macro(lineno=six.advance_iterator(self.stream).lineno)342 node.name = self.parse_assign_target(name_only=True).name343 self.parse_signature(node)344 node.body = self.parse_statements(('name:endmacro',),345 drop_needle=True)346 return node347 348 def parse_print(self):350- node = nodes.Output(lineno=next(self.stream).lineno)349+ node = nodes.Output(lineno=six.advance_iterator(self.stream).lineno)350 node.nodes = []351 while self.stream.current.type != 'block_end':352 if node.nodes:353 self.stream.expect('comma')65 unmodified lines419 return left420 421 def parse_not(self):422 if self.stream.current.test('name:not'):424- lineno = next(self.stream).lineno423+ lineno = six.advance_iterator(self.stream).lineno424 return nodes.Not(self.parse_not(), lineno=lineno)425 return self.parse_compare()426 427 def parse_compare(self):2 unmodified lines430 ops = []431 while 1:432 token_type = self.stream.current.type433 if token_type in _compare_operators:435- next(self.stream)434+ six.advance_iterator(self.stream)435 ops.append(nodes.Operand(token_type, self.parse_add()))436 elif self.stream.skip_if('name:in'):437 ops.append(nodes.Operand('in', self.parse_add()))438 elif self.stream.current.test('name:not') and \10 unmodified lines449 def parse_add(self):450 lineno = self.stream.current.lineno451 left = self.parse_sub()452 while self.stream.current.type == 'add':454- next(self.stream)453+ six.advance_iterator(self.stream)454 right = self.parse_sub()455 left = nodes.Add(left, right, lineno=lineno)456 lineno = self.stream.current.lineno457 return left1 unmodified line459 def parse_sub(self):460 lineno = self.stream.current.lineno461 left = self.parse_concat()462 while self.stream.current.type == 'sub':464- next(self.stream)463+ six.advance_iterator(self.stream)464 right = self.parse_concat()465 left = nodes.Sub(left, right, lineno=lineno)466 lineno = self.stream.current.lineno467 return left1 unmodified line469 def parse_concat(self):470 lineno = self.stream.current.lineno471 args = [self.parse_mul()]472 while self.stream.current.type == 'tilde':474- next(self.stream)473+ six.advance_iterator(self.stream)474 args.append(self.parse_mul())475 if len(args) == 1:476 return args[0]477 return nodes.Concat(args, lineno=lineno)1 unmodified line479 def parse_mul(self):480 lineno = self.stream.current.lineno481 left = self.parse_div()482 while self.stream.current.type == 'mul':484- next(self.stream)483+ six.advance_iterator(self.stream)484 right = self.parse_div()485 left = nodes.Mul(left, right, lineno=lineno)486 lineno = self.stream.current.lineno487 return left1 unmodified line489 def parse_div(self):490 lineno = self.stream.current.lineno491 left = self.parse_floordiv()492 while self.stream.current.type == 'div':494- next(self.stream)493+ six.advance_iterator(self.stream)494 right = self.parse_floordiv()495 left = nodes.Div(left, right, lineno=lineno)496 lineno = self.stream.current.lineno497 return left1 unmodified line499 def parse_floordiv(self):500 lineno = self.stream.current.lineno501 left = self.parse_mod()502 while self.stream.current.type == 'floordiv':504- next(self.stream)503+ six.advance_iterator(self.stream)504 right = self.parse_mod()505 left = nodes.FloorDiv(left, right, lineno=lineno)506 lineno = self.stream.current.lineno507 return left1 unmodified line509 def parse_mod(self):510 lineno = self.stream.current.lineno511 left = self.parse_pow()512 while self.stream.current.type == 'mod':514- next(self.stream)513+ six.advance_iterator(self.stream)514 right = self.parse_pow()515 left = nodes.Mod(left, right, lineno=lineno)516 lineno = self.stream.current.lineno517 return left1 unmodified line519 def parse_pow(self):520 lineno = self.stream.current.lineno521 left = self.parse_unary()522 while self.stream.current.type == 'pow':524- next(self.stream)523+ six.advance_iterator(self.stream)524 right = self.parse_unary()525 left = nodes.Pow(left, right, lineno=lineno)526 lineno = self.stream.current.lineno527 return left1 unmodified line529 def parse_unary(self, with_filter=True):530 token_type = self.stream.current.type531 lineno = self.stream.current.lineno532 if token_type == 'sub':534- next(self.stream)533+ six.advance_iterator(self.stream)534 node = nodes.Neg(self.parse_unary(False), lineno=lineno)535 elif token_type == 'add':537- next(self.stream)536+ six.advance_iterator(self.stream)537 node = nodes.Pos(self.parse_unary(False), lineno=lineno)538 else:539 node = self.parse_primary()540 node = self.parse_postfix(node)10 unmodified lines551 elif token.value in ('none', 'None'):552 node = nodes.Const(None, lineno=token.lineno)553 else:554 node = nodes.Name(token.value, 'load', lineno=token.lineno)556- next(self.stream)555+ six.advance_iterator(self.stream)556 elif token.type == 'string':558- next(self.stream)557+ six.advance_iterator(self.stream)558 buf = [token.value]559 lineno = token.lineno560 while self.stream.current.type == 'string':561 buf.append(self.stream.current.value)563- next(self.stream)562+ six.advance_iterator(self.stream)563 node = nodes.Const(''.join(buf), lineno=lineno)564 elif token.type in ('integer', 'float'):566- next(self.stream)565+ six.advance_iterator(self.stream)566 node = nodes.Const(token.value, lineno=token.lineno)567 elif token.type == 'lparen':569- next(self.stream)568+ six.advance_iterator(self.stream)569 node = self.parse_tuple(explicit_parentheses=True)570 self.stream.expect('rparen')571 elif token.type == 'lbracket':572 node = self.parse_list()113 unmodified lines686 break687 return node688 689 def parse_subscript(self, node):691- token = next(self.stream)690+ token = six.advance_iterator(self.stream)691 if token.type == 'dot':692 attr_token = self.stream.current694- next(self.stream)693+ six.advance_iterator(self.stream)694 if attr_token.type == 'name':695 return nodes.Getattr(node, attr_token.value, 'load',696 lineno=token.lineno)697 elif attr_token.type != 'integer':17 unmodified lines715 def parse_subscribed(self):716 lineno = self.stream.current.lineno717 718 if self.stream.current.type == 'colon':720- next(self.stream)719+ six.advance_iterator(self.stream)720 args = [None]721 else:722 node = self.parse_expression()723 if self.stream.current.type != 'colon':724 return node726- next(self.stream)725+ six.advance_iterator(self.stream)726 args = [node]727 728 if self.stream.current.type == 'colon':729 args.append(None)2 unmodified lines732 else:733 args.append(None)734 735 if self.stream.current.type == 'colon':737- next(self.stream)736+ six.advance_iterator(self.stream)737 if self.stream.current.type not in ('rbracket', 'comma'):738 args.append(self.parse_expression())739 else:740 args.append(None)21 unmodified lines762 if self.stream.current.type == 'rparen':763 break764 if self.stream.current.type == 'mul':765 ensure(dyn_args is None and dyn_kwargs is None)767- next(self.stream)766+ six.advance_iterator(self.stream)767 dyn_args = self.parse_expression()768 elif self.stream.current.type == 'pow':769 ensure(dyn_kwargs is None)771- next(self.stream)770+ six.advance_iterator(self.stream)771 dyn_kwargs = self.parse_expression()772 else:773 ensure(dyn_args is None and dyn_kwargs is None)774 if self.stream.current.type == 'name' and \17 unmodified lines792 793 def parse_filter(self, node, start_inline=False):794 while self.stream.current.type == 'pipe' or start_inline:795 if not start_inline:797- next(self.stream)796+ six.advance_iterator(self.stream)797 token = self.stream.expect('name')798 name = token.value799 while self.stream.current.type == 'dot':801- next(self.stream)800+ six.advance_iterator(self.stream)801 name += '.' + self.stream.expect('name').value802 if self.stream.current.type == 'lparen':803 args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)804 else:5 unmodified lines810 start_inline = False811 return node812 813 def parse_test(self, node):815- token = next(self.stream)814+ token = six.advance_iterator(self.stream)815 if self.stream.current.test('name:not'):817- next(self.stream)816+ six.advance_iterator(self.stream)817 negated = True818 else:819 negated = False820 name = self.stream.expect('name').value821 while self.stream.current.type == 'dot':823- next(self.stream)822+ six.advance_iterator(self.stream)823 name += '.' + self.stream.expect('name').value824 dyn_args = dyn_kwargs = None825 kwargs = []826 if self.stream.current.type == 'lparen':34 unmodified lines861 if token.type == 'data':862 if token.value:863 add_data(nodes.TemplateData(token.value,864 lineno=token.lineno))866- next(self.stream)865+ six.advance_iterator(self.stream)866 elif token.type == 'variable_begin':868- next(self.stream)867+ six.advance_iterator(self.stream)868 add_data(self.parse_tuple(with_condexpr=True))869 self.stream.expect('variable_end')870 elif token.type == 'block_begin':871 flush_data()873- next(self.stream)872+ six.advance_iterator(self.stream)873 if end_tokens is not None and \874 self.stream.current.test_any(*end_tokens):875 return body876 rv = self.parse_statement()20 unmodified linesmodified:jinja2/runtime.py+19 added-14 removed
6 unmodified lines7 8 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD.10 """11-from itertools import chain, imap11+from itertools import chain12 from jinja2.nodes import EvalContext, _context_function_types13 from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \14- concat, internalcode, next, object_type_repr14+ concat, internalcode, object_type_repr15 from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \16 TemplateNotFound17 import six18+from six.moves import map19 20 21 # these variables are exported to the template runtime22 __all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',3 unmodified lines26 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:29-to_string = unicode31+ to_string = unicode32+except NameError:33+ to_string = str34 35 #: the identity function. Useful for certain things in the environment36 identity = lambda x: x37 2 unmodified lines40 41 def markup_join(seq):42 """Concatenation that escapes if necessary and converts to unicode."""43 buf = []40- iterator = imap(soft_unicode, seq)44+ iterator = map(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."""50- return concat(imap(unicode, seq))54+ return concat(map(six.text_type, seq))55 56 57 def new_context(environment, template_name, blocks, vars=None,58 shared=None, globals=None, locals=None):249 unmodified lines308 return LoopContextIterator(self)309 310 def _safe_next(self):311 try:308- return next(self._iterator)312+ return six.advance_iterator(self._iterator)313 except StopIteration:314 return _last_iteration315 316 @internalcode27 unmodified lines344 self.length345 )346 347 344-class LoopContextIterator(object):348+class LoopContextIterator(six.Iterator):349 """The iterator for a loop context."""350 __slots__ = ('context',)351 352 def __init__(self, context):1 unmodified line354 355 def __iter__(self):356 return self357 354- def next(self):358+ def __next__(self):359 ctx = self.context360 ctx.index0 += 1361 if ctx._after is _last_iteration:362 raise StopIteration()96 unmodified lines459 """460 if self._undefined_hint is None:461 if self._undefined_obj is missing:462 hint = '%r is undefined' % self._undefined_name459- elif not isinstance(self._undefined_name, basestring):463+ elif not isinstance(self._undefined_name, six.string_types):464 hint = '%s has no element %r' % (465 object_type_repr(self._undefined_obj),466 self._undefined_name467 )19 unmodified lines487 __float__ = __complex__ = __pow__ = __rpow__ = \488 _fail_with_undefined_error489 490 def __str__(self):491+ s = self.__unicode__()487- return six.text_type(self).encode('utf-8')492+ return s if six.PY3 else s.encode('utf-8')493 489- # unicode goes after __str__ because we configured 2to3 to rename490- # __unicode__ to __str__. because the 2to3 tree is not designed to491- # remove nodes from it, we leave the above __str__ around and let492- # it override at runtime.494 def __unicode__(self):495 return u''496 497 def __len__(self):24 unmodified lines522 UndefinedError: 'foo' is undefined523 """524 __slots__ = ()525 526+ def __str__(self):527+ s = self.__unicode__()528+ return s if six.PY3 else s.encode('utf-8')529+530 def __unicode__(self):531 if self._undefined_hint is None:532 if self._undefined_obj is missing:533 return u'{{ %s }}' % self._undefined_name34 unmodified linesmodified:jinja2/sandbox.py+2 added-1 removed
11 unmodified lines12 :copyright: (c) 2010 by the Jinja Team.13 :license: BSD.14 """15 import operator16+import six17 from jinja2.environment import Environment18 from jinja2.exceptions import SecurityError19 from jinja2.utils import FunctionType, MethodType, TracebackType, CodeType, \20 FrameType, GeneratorType278 unmodified lines299 """Subscribe an object from sandboxed code."""300 try:301 return obj[argument]302 except (TypeError, LookupError):302- if isinstance(argument, basestring):303+ if isinstance(argument, six.string_types):304 try:305 attr = str(argument)306 except Exception:307 pass55 unmodified linesmodified:jinja2/tests.py+2 added-2 removed
85 unmodified lines86 87 88 def test_string(value):89 """Return true if the object is a string."""90- return isinstance(value, basestring)90+ return isinstance(value, six.string_types)91 92 93 def test_mapping(value):94 """Return true if the object is a mapping (dict etc.).4 unmodified lines99 100 101 def test_number(value):102 """Return true if the variable is a number."""103- return isinstance(value, (int, long, float, complex))103+ return isinstance(value, (int, float, complex))104 105 106 def test_sequence(value):107 """Return true if the variable is a sequence. Sequences are variables55 unmodified linesmodified:jinja2/utils.py+12 added-19 removed
10 unmodified lines11 import re12 import sys13 import errno14 import six15+from six.moves import map16 try:17 from urllib.parse import quote_from_bytes as url_quote18 except ImportError:19 from urllib import quote as url_quote20 try:21 from thread import allocate_lock22 except ImportError:23+ try:24+ from _thread import allocate_lock # py 325+ except ImportError:22- from dummy_thread import allocate_lock26+ from dummy_thread import allocate_lock27 from collections import deque24-from itertools import imap28 26-29 _word_split_re = re.compile(r'(\s+)')30 _punctuation_re = re.compile(31 '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (30- '|'.join(imap(re.escape, ('(', '<', '<'))),31- '|'.join(imap(re.escape, ('.', ',', ')', '>', '\n', '>')))32+ '|'.join(map(re.escape, ('(', '<', '<'))),33+ '|'.join(map(re.escape, ('.', ',', ')', '>', '\n', '>')))34 )35 )36 _simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')37 _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')25 unmodified lines63 except Exception:64 # this hack is needed so that the current frame65 # does not show up in the traceback.66 exc_type, exc_value, tb = sys.exc_info()65- raise exc_type, exc_value, tb.tb_next67+ six.reraise(exc_type, exc_value, tb.tb_next)68 else:69 concat = _concat70 del _test_gen_bug, _error71 72 71-# for python 2.x we create ourselves a next() function that does the72-# basics without exception catching.73-try:74- next = next75-except NameError:76- def next(x):77- return six.advance_iterator(x)78-79-73 # if this python version is unable to deal with unicode filenames74 # when passed to encode we let this function encode it properly.75 # This is used in a couple of places. As far as Jinja is concerned76 # filenames are unicode *or* bytestrings in 2.x and unicode only in278 unmodified lines355 356 If non strings are provided they are converted to their unicode357 representation first.358 """366- if not isinstance(obj, basestring):359+ if not isinstance(obj, six.string_types):360 obj = six.text_type(obj)368- if isinstance(obj, unicode):361+ if isinstance(obj, six.text_type):362 obj = obj.encode(charset)363 return six.text_type(url_quote(obj))364 365 189 unmodified lines555 except ImportError:556 pass557 558 566-class Cycler(object):559+class Cycler(six.Iterator):560 """A cycle helper for templates."""561 562 def __init__(self, *items):563 if not items:9 unmodified lines573 def current(self):574 """Returns the current item."""575 return self.items[self.pos]576 584- def next(self):577+ def __next__(self):578 """Goes one item ahead and returns it."""579 rv = self.current580 self.pos = (self.pos + 1) % len(self.items)581 return rv38 unmodified linesmodified:setup.py+1 added-10 removed
46 unmodified lines47 ],48 )49 50 51-# tell distribute to use 2to3 with our own fixers.52-extra = {}53-if sys.version_info >= (3, 0):54- extra.update(55- use_2to3=True,56- use_2to3_fixers=['custom_fixers']57- )58-51 # ignore the old '--with-speedups' flag52 try:53 speedups_pos = sys.argv.index('--with-speedups')54 except ValueError:41 unmodified lines96 entry_points="""97 [babel.extractors]98 jinja2 = jinja2.ext:babel_extract[i18n]99 """,108- features={'debugsupport': debugsupport},109- **extra100+ features={'debugsupport': debugsupport}101 )