python 3 port: automated changes by a slightly modified python-modernize
Before adoption: this commit came in with the history the project adopted, so no landing records it.
(replacing unicode with six.text_type, but not replacing u"" by six.u(""))
authored by Thomas Waldmann · committed by Thomas Waldmann · parent 846bdc1 · Browse files · 29 files·+171 added−131 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
29 files+171 added−131 removed
- other:+171 added−131 removed
Provenance
- Commit
e000355- Tree
29bb5ba- Author
Thomas Waldmann <tw@waldmann-edv.de>- Committer
Thomas Waldmann <tw@waldmann-edv.de>- Parent
846bdc1
29 files changed+171 added−131 removed
modified:jinja2/_markupsafe/__init__.py+8 added-5 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import re12 from itertools import imap13+import six14+from six.moves import map15+from six.moves import zip16 17 18 __all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent']19 58 unmodified lines78 return self79 80 def __add__(self, other):81 if hasattr(other, '__html__') or isinstance(other, basestring):79- return self.__class__(unicode(self) + unicode(escape(other)))82+ return self.__class__(six.text_type(self) + six.text_type(escape(other)))83 return NotImplemented84 85 def __radd__(self, other):86 if hasattr(other, '__html__') or isinstance(other, basestring):84- return self.__class__(unicode(escape(other)) + unicode(self))87+ return self.__class__(six.text_type(escape(other)) + six.text_type(self))88 return NotImplemented89 90 def __mul__(self, num):91 if isinstance(num, (int, long)):49 unmodified lines141 return unichr(int(name[1:]))142 except ValueError:143 pass144 return u''142- return _entity_re.sub(handle_match, unicode(self))145+ return _entity_re.sub(handle_match, six.text_type(self))146 147 def striptags(self):148 r"""Unescape markup into an unicode string and strip all tags. This149 also resolves known HTML4 and XHTML entities. Whitespace is19 unmodified lines169 def make_wrapper(name):170 orig = getattr(unicode, name)171 def func(self, *args, **kwargs):172 args = _escape_argspec(list(args), enumerate(args))170- _escape_argspec(kwargs, kwargs.iteritems())173+ _escape_argspec(kwargs, six.iteritems(kwargs))174 return self.__class__(orig(self, *args, **kwargs))175 func.__name__ = orig.__name__176 func.__doc__ = orig.__doc__177 return func35 unmodified lines213 self.obj = obj214 215 __getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x])216 __str__ = lambda s: str(escape(s.obj))214- __unicode__ = lambda s: unicode(escape(s.obj))217+ __unicode__ = lambda s: six.text_type(escape(s.obj))218 __repr__ = lambda s: str(escape(repr(s.obj)))219 __int__ = lambda s: int(s.obj)220 __float__ = lambda s: float(s.obj)221 7 unmodified linesmodified:jinja2/_markupsafe/_bundle.py+2 added-1 removed
8 unmodified lines9 10 :copyright: Copyright 2010 by the Jinja team, see AUTHORS.11 :license: BSD, see LICENSE for details.12 """13+from __future__ import print_function14 import sys15 import os16 import re17 7 unmodified lines25 26 27 def main():28 if len(sys.argv) != 2:28- print 'error: only argument is path to markupsafe'29+ print('error: only argument is path to markupsafe')30 sys.exit(1)31 basedir = os.path.dirname(__file__)32 markupdir = sys.argv[1]33 for filename in os.listdir(markupdir):17 unmodified linesmodified:jinja2/_markupsafe/_native.py+3 added-2 removed
7 unmodified lines8 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 from jinja2._markupsafe import Markup12+import six13 14 15 def escape(s):16 """Convert the characters &, <, >, ' and " in string s to HTML-safe1 unmodified line18 such characters in HTML. Marks return value as markup string.19 """20 if hasattr(s, '__html__'):21 return s.__html__()21- return Markup(unicode(s)22+ return Markup(six.text_type(s)23 .replace('&', '&')24 .replace('>', '>')25 .replace('<', '<')26 .replace("'", ''')14 unmodified lines41 """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- s = unicode(s)45+ s = six.text_type(s)46 return smodified:jinja2/_markupsafe/tests.py+4 added-3 removed
1 import gc2 import unittest3 from jinja2._markupsafe import Markup, escape, escape_silent4+import six5 6 7 class MarkupTestCase(unittest.TestCase):8 9 def test_markup_operations(self):10 # adding two strings should escape the unsafe one11 unsafe = '<script type="application/x-some-script">alert("foo");</script>'12 safe = Markup('<em>username</em>')12- assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe)13+ assert unsafe + safe == six.text_type(escape(unsafe)) + six.text_type(safe)14 15 # string interpolations are safe to use too16 assert Markup('<em>%s</em>') % '<bad user>' == \17 '<em><bad user></em>'37 unmodified lines55 class MarkupLeakTestCase(unittest.TestCase):56 57 def test_markup_leaks(self):58 counts = set()58- for count in xrange(20):59- for item in xrange(1000):59+ for count in range(20):60+ for item in range(1000):61 escape("foo")62 escape("<foo>")63 escape(u"foo")64 escape(u"<foo>")17 unmodified linesmodified:jinja2/testsuite/__init__.py+1 added-1 removed
57 unmodified lines58 59 def assert_traceback_matches(self, callback, expected_tb):60 try:61 callback()62- except Exception, e:62+ except Exception as e:63 tb = format_exception(*sys.exc_info())64 if re.search(expected_tb.strip(), ''.join(tb)) is None:65 raise self.fail('Traceback did not match:\n\n%s\nexpected:\n%s'66 % (''.join(tb), expected_tb))29 unmodified linesmodified:jinja2/testsuite/api.py+17 added-16 removed
14 unmodified lines15 from jinja2 import Environment, Undefined, DebugUndefined, \16 StrictUndefined, UndefinedError, meta, \17 is_undefined, Template, DictLoader18 from jinja2.utils import Cycler19+import six20 21 env = Environment()22 23 26 unmodified lines50 items = 1, 2, 351 c = Cycler(*items)52 for item in items + items:53 assert c.current == item53- assert c.next() == item54- c.next()54+ assert six.advance_iterator(c) == item55+ six.advance_iterator(c)56 assert c.current == 257 c.reset()58 assert c.current == 159 47 unmodified lines107 108 def test_find_refererenced_templates(self):109 ast = env.parse('{% extends "layout.html" %}{% include helper %}')110 i = meta.find_referenced_templates(ast)110- assert i.next() == 'layout.html'111- assert i.next() is None111+ assert six.advance_iterator(i) == 'layout.html'112+ assert six.advance_iterator(i) is None113 assert list(i) == []114 115 ast = env.parse('{% extends "layout.html" %}'116 '{% from "test.html" import a, b as c %}'24 unmodified lines141 142 def test_basic_streaming(self):143 tmpl = env.from_string("<ul>{% for item in seq %}<li>{{ loop.index "144 "}} - {{ item }}</li>{%- endfor %}</ul>")144- stream = tmpl.stream(seq=range(4))145- self.assert_equal(stream.next(), '<ul>')146- self.assert_equal(stream.next(), '<li>1 - 0</li>')147- self.assert_equal(stream.next(), '<li>2 - 1</li>')148- self.assert_equal(stream.next(), '<li>3 - 2</li>')149- self.assert_equal(stream.next(), '<li>4 - 3</li>')150- self.assert_equal(stream.next(), '</ul>')145+ stream = tmpl.stream(seq=list(range(4)))146+ self.assert_equal(six.advance_iterator(stream), '<ul>')147+ self.assert_equal(six.advance_iterator(stream), '<li>1 - 0</li>')148+ self.assert_equal(six.advance_iterator(stream), '<li>2 - 1</li>')149+ self.assert_equal(six.advance_iterator(stream), '<li>3 - 2</li>')150+ self.assert_equal(six.advance_iterator(stream), '<li>4 - 3</li>')151+ self.assert_equal(six.advance_iterator(stream), '</ul>')152 153 def test_buffered_streaming(self):154 tmpl = env.from_string("<ul>{% for item in seq %}<li>{{ loop.index "155 "}} - {{ item }}</li>{%- endfor %}</ul>")155- stream = tmpl.stream(seq=range(4))156+ stream = tmpl.stream(seq=list(range(4)))157 stream.enable_buffering(size=3)157- self.assert_equal(stream.next(), u'<ul><li>1 - 0</li><li>2 - 1</li>')158- self.assert_equal(stream.next(), u'<li>3 - 2</li><li>4 - 3</li></ul>')158+ self.assert_equal(six.advance_iterator(stream), u'<ul><li>1 - 0</li><li>2 - 1</li>')159+ self.assert_equal(six.advance_iterator(stream), u'<li>3 - 2</li><li>4 - 3</li></ul>')160 161 def test_streaming_behavior(self):162 tmpl = env.from_string("")163 stream = tmpl.stream()58 unmodified lines222 223 def test_none_gives_proper_error(self):224 try:225 Environment().getattr(None, 'split')()225- except UndefinedError, e:226+ except UndefinedError as e:227 assert e.message == "'None' has no attribute 'split'"228 else:229 assert False, 'expected exception'230 231 def test_object_repr(self):232 try:233 Undefined(obj=42, name='upper')()233- except UndefinedError, e:234+ except UndefinedError as e:235 assert e.message == "'int object' has no attribute 'upper'"236 else:237 assert False, 'expected exception'238 8 unmodified linesmodified:jinja2/testsuite/core_tags.py+3 added-3 removed
20 unmodified lines21 class ForLoopTestCase(JinjaTestCase):22 23 def test_simple(self):24 tmpl = env.from_string('{% for item in seq %}{{ item }}{% endfor %}')25- assert tmpl.render(seq=range(10)) == '0123456789'25+ assert tmpl.render(seq=list(range(10))) == '0123456789'26 27 def test_else(self):28 tmpl = env.from_string('{% for item in seq %}XXX{% else %}...{% endfor %}')29 assert tmpl.render() == '...'24 unmodified lines54 def test_cycling(self):55 tmpl = env.from_string('''{% for item in seq %}{{56 loop.cycle('<1>', '<2>') }}{% endfor %}{%57 for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''')58- output = tmpl.render(seq=range(4), through=('<1>', '<2>'))58+ output = tmpl.render(seq=list(range(4)), through=('<1>', '<2>'))59 assert output == '<1><2>' * 460 61 def test_scope(self):62 tmpl = env.from_string('{% for item in seq %}{% endfor %}{{ item }}')63- output = tmpl.render(seq=range(10))63+ output = tmpl.render(seq=list(range(10)))64 assert not output65 66 def test_varlen(self):67 def inner():218 unmodified linesmodified:jinja2/testsuite/ext.py+2 added-1 removed
16 unmodified lines17 from jinja2.exceptions import TemplateAssertionError18 from jinja2.ext import Extension19 from jinja2.lexer import Token, count_newlines20 from jinja2.utils import next21+import six22 23 # 2.x / 3.x24 try:25 from io import BytesIO196 unmodified lines222 def test_rebinding(self):223 original = Environment(extensions=[TestExtension])224 overlay = original.overlay()225 for env in original, overlay:225- for ext in env.extensions.itervalues():226+ for ext in six.itervalues(env.extensions):227 assert ext.environment is env228 229 def test_preprocessor_extension(self):230 env = Environment(extensions=[PreprocessorExtension])226 unmodified linesmodified:jinja2/testsuite/filters.py+11 added-8 removed
10 unmodified lines11 import unittest12 from jinja2.testsuite import JinjaTestCase13 14 from jinja2 import Markup, Environment15+import six16+from six.moves import map17+from six.moves import zip18 19 env = Environment()20 21 27 unmodified lines49 50 def test_batch(self):51 tmpl = env.from_string("{{ foo|batch(3)|list }}|"52 "{{ foo|batch(3, 'X')|list }}")50- out = tmpl.render(foo=range(10))53+ out = tmpl.render(foo=list(range(10)))54 assert out == ("[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]|"55 "[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 'X', 'X']]")56 57 def test_slice(self):58 tmpl = env.from_string('{{ foo|slice(3)|list }}|'59 '{{ foo|slice(3, "X")|list }}')57- out = tmpl.render(foo=range(10))60+ out = tmpl.render(foo=list(range(10)))61 assert out == ("[[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]|"62 "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]")63 64 def test_escape(self):46 unmodified lines111 112 113 def test_first(self):114 tmpl = env.from_string('{{ foo|first }}')112- out = tmpl.render(foo=range(10))115+ out = tmpl.render(foo=list(range(10)))116 assert out == '0'117 118 def test_float(self):119 tmpl = env.from_string('{{ "42"|float }}|'37 unmodified lines157 assert tmpl.render(users=map(User, ['foo', 'bar'])) == 'foo, bar'158 159 def test_last(self):160 tmpl = env.from_string('''{{ foo|last }}''')158- out = tmpl.render(foo=range(10))161+ out = tmpl.render(foo=list(range(10)))162 assert out == '9'163 164 def test_length(self):165 tmpl = env.from_string('''{{ "hello world"|length }}''')7 unmodified lines173 174 def test_pprint(self):175 from pprint import pformat176 tmpl = env.from_string('''{{ data|pprint }}''')174- data = range(1000)177+ data = list(range(1000))178 assert tmpl.render(data=data) == pformat(data)179 180 def test_random(self):181 tmpl = env.from_string('''{{ seq|random }}''')179- seq = range(100)182+ seq = list(range(100))183 for _ in range(10):184 assert int(tmpl.render(seq=seq)) in seq185 186 def test_reverse(self):3 unmodified lines190 191 def test_string(self):192 x = [1, 2, 3, 4, 5]193 tmpl = env.from_string('''{{ obj|string }}''')191- assert tmpl.render(obj=x) == unicode(x)194+ assert tmpl.render(obj=x) == six.text_type(x)195 196 def test_title(self):197 tmpl = env.from_string('''{{ "foo bar"|title }}''')198 assert tmpl.render() == "Foo Bar"100 unmodified lines299 class Magic(object):300 def __init__(self, value):301 self.value = value302 def __unicode__(self):300- return unicode(self.value)303+ return six.text_type(self.value)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/imports.py+1 added-1 removed
81 unmodified lines82 t = test_env.from_string('{% include ["missing", "missing2"] %}')83 self.assert_raises(TemplateNotFound, t.render)84 try:85 t.render()86- except TemplatesNotFound, e:86+ except TemplatesNotFound as e:87 assert e.templates == ['missing', 'missing2']88 assert e.name == 'missing2'89 else:90 assert False, 'thou shalt raise'51 unmodified linesmodified:jinja2/testsuite/inheritance.py+2 added-2 removed
146 unmodified lines147 '{% endblock %}]{% endfor %}'148 }))149 t = env.from_string('{% extends "master.html" %}{% block item %}'150 '{{ item }}{% endblock %}')151- assert t.render(seq=range(5)) == '[0][1][2][3][4]'151+ assert t.render(seq=list(range(5))) == '[0][1][2][3][4]'152 153 def test_super_in_scoped_block(self):154 env = Environment(loader=DictLoader({155 'master.html': '{% for item in seq %}[{% block item scoped %}'156 '{{ item }}{% endblock %}]{% endfor %}'157 }))158 t = env.from_string('{% extends "master.html" %}{% block item %}'159 '{{ super() }}|{{ item * 2 }}{% endblock %}')160- assert t.render(seq=range(5)) == '[0|0][1|2][2|4][3|6][4|8]'160+ assert t.render(seq=list(range(5))) == '[0|0][1|2][2|4][3|6][4|8]'161 162 def test_scoped_block_after_inheritance(self):163 env = Environment(loader=DictLoader({164 'layout.html': '''63 unmodified linesmodified:jinja2/testsuite/lexnparse.py+15 added-14 removed
13 unmodified lines14 from jinja2.testsuite import JinjaTestCase15 16 from jinja2 import Environment, Template, TemplateSyntaxError, \17 UndefinedError, nodes18+import six19 20 env = Environment()21 22 19 unmodified lines42 def test_balancing(self):43 env = Environment('{%', '%}', '${', '}')44 tmpl = env.from_string('''{% for item in seq45 %}${{'foo': item}|upper}{% endfor %}''')45- assert tmpl.render(seq=range(3)) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"46+ assert tmpl.render(seq=list(range(3))) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"47 48 def test_comments(self):49 env = Environment('<!--', '-->', '{', '}')50 tmpl = env.from_string('''\1 unmodified line52 <!--- for item in seq -->53 <li>{item}</li>54 <!--- endfor -->55 </ul>''')55- assert tmpl.render(seq=range(3)) == ("<ul>\n <li>0</li>\n "56+ assert tmpl.render(seq=list(range(3))) == ("<ul>\n <li>0</li>\n "57 "<li>1</li>\n <li>2</li>\n</ul>")58 59 def test_string_escapes(self):60 for char in u'\0', u'\u2668', u'\xe4', u'\t', u'\r', u'\n':7 unmodified lines68 assert tmpl.render() == pformat('foo') + '|' + pformat(u'bär')69 70 def test_operators(self):71 from jinja2.lexer import operators71- for test, expect in operators.iteritems():72+ for test, expect in six.iteritems(operators):73 if test in '([{}])':74 continue75 stream = env.lexer.tokenize('{{ %s }}' % test)75- stream.next()76+ six.advance_iterator(stream)77 assert stream.current.type == expect78 79 def test_normalizing(self):80 for seq in '\r', '\r\n', '\n':11 unmodified lines92 <!-- I'm a comment, I'm not interesting -->\93 <? for item in seq -?>94 <?= item ?>95 <?- endfor ?>''')95- assert tmpl.render(seq=range(5)) == '01234'96+ assert tmpl.render(seq=list(range(5))) == '01234'97 98 def test_erb_syntax(self):99 env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>')100 tmpl = env.from_string('''\101 <%# I'm a comment, I'm not interesting %>\102 <% for item in seq -%>103 <%= item %>104 <%- endfor %>''')104- assert tmpl.render(seq=range(5)) == '01234'105+ assert tmpl.render(seq=list(range(5))) == '01234'106 107 def test_comment_syntax(self):108 env = Environment('<!--', '-->', '${', '}', '<!--#', '-->')109 tmpl = env.from_string('''\110 <!--# I'm a comment, I'm not interesting -->\111 <!-- for item in seq --->112 ${item}113 <!--- endfor -->''')113- assert tmpl.render(seq=range(5)) == '01234'114+ assert tmpl.render(seq=list(range(5))) == '01234'115 116 def test_balancing(self):117 tmpl = env.from_string('''{{{'foo':'bar'}.foo}}''')118 assert tmpl.render() == 'bar'11 unmodified lines130 <%# regular comment %>131 % for item in seq:132 ${item}133 % endfor''')133- assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \134- range(5)134+ assert [int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()] == \135+ list(range(5))136 137 env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##')138 tmpl = env.from_string('''\139 <%# regular comment %>140 % for item in seq:141 ${item} ## the rest of the stuff142 % endfor''')142- assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \143- range(5)143+ assert [int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()] == \144+ list(range(5))145 146 def test_line_syntax_priority(self):147 # XXX: why is the whitespace there in front of the newline?148 env = Environment('{%', '%}', '${', '}', '/*', '*/', '##', '#')17 unmodified lines166 def test_error_messages(self):167 def assert_error(code, expected):168 try:169 Template(code)169- except TemplateSyntaxError, e:170+ except TemplateSyntaxError as e:171 assert str(e) == expected, 'unexpected error message'172 else:173 assert False, 'that was supposed to be an error'174 160 unmodified lines335 tmpl = env.from_string('{{ "foo" "bar" "baz" }}')336 assert tmpl.render() == 'foobarbaz'337 338 def test_notin(self):338- bar = xrange(100)339+ bar = range(100)340 tmpl = env.from_string('''{{ not 42 in bar }}''')340- assert tmpl.render(bar=bar) == unicode(not 42 in bar)341+ assert tmpl.render(bar=bar) == six.text_type(not 42 in bar)342 343 def test_implicit_subscribed_tuple(self):344 class Foo(object):345 def __getitem__(self, x):43 unmodified linesmodified:jinja2/testsuite/regression.py+4 added-2 removed
12 unmodified lines13 from jinja2.testsuite import JinjaTestCase14 15 from jinja2 import Template, Environment, DictLoader, TemplateSyntaxError, \16 TemplateNotFound, PrefixLoader17+from six.moves import map18+from six.moves import zip19 20 env = Environment()21 22 96 unmodified lines119 {% endfor %}120 121 ''')122 121- assert tmpl.render().split() == map(unicode, range(1, 11)) * 5123+ assert tmpl.render().split() == map(unicode, list(range(1, 11))) * 5124 125 def test_weird_inline_comment(self):126 env = Environment(line_statement_prefix='%')127 self.assert_raises(TemplateSyntaxError, env.from_string,115 unmodified lines243 'foo': DictLoader({})244 }))245 try:246 env.get_template('foo/bar.html')245- except TemplateNotFound, e:247+ except TemplateNotFound as e:248 assert e.name == 'foo/bar.html'249 else:250 assert False, 'expected error here'251 6 unmodified linesmodified:jinja2/testsuite/security.py+5 added-4 removed
16 unmodified lines17 ImmutableSandboxedEnvironment, unsafe18 from jinja2 import Markup, escape19 from jinja2.exceptions import SecurityError, TemplateSyntaxError, \20 TemplateRuntimeError21+import six22 23 24 class PrivateStuff(object):25 50 unmodified lines76 def test_markup_operations(self):77 # adding two strings should escape the unsafe one78 unsafe = '<script type="application/x-some-script">alert("foo");</script>'79 safe = Markup('<em>username</em>')79- assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe)80+ assert unsafe + safe == six.text_type(escape(unsafe)) + six.text_type(safe)81 82 # string interpolations are safe to use too83 assert Markup('<em>%s</em>') % '<bad user>' == \84 '<em><bad user></em>'29 unmodified lines114 '<p>Hello {{ name }}!</p>{% endmacro %}'115 '{{ say_hello("<blink>foo</blink>") }}')116 escaped_out = '<p>Hello <blink>foo</blink>!</p>'117 assert t.render() == escaped_out117- assert unicode(t.module) == escaped_out118+ assert six.text_type(t.module) == escaped_out119 assert escape(t.module) == escaped_out120 assert t.module.say_hello('<blink>foo</blink>') == escaped_out121 assert escape(t.module.say_hello('<blink>foo</blink>')) == escaped_out122 13 unmodified lines136 env.intercepted_binops = frozenset(['+'])137 t = env.from_string('{{ %s }}' % expr)138 try:139 t.render(ctx)139- except TemplateRuntimeError, e:140+ except TemplateRuntimeError as e:141 pass142 else:143 self.fail('expected runtime error')144 8 unmodified lines153 env.intercepted_unops = frozenset(['-'])154 t = env.from_string('{{ %s }}' % expr)155 try:156 t.render(ctx)156- except TemplateRuntimeError, e:157+ except TemplateRuntimeError as e:158 pass159 else:160 self.fail('expected runtime error')161 5 unmodified linesmodified:jinja2/testsuite/utils.py+2 added-2 removed
58 unmodified lines59 class MarkupLeakTestCase(JinjaTestCase):60 61 def test_markup_leaks(self):62 counts = set()63- for count in xrange(20):64- for item in xrange(1000):63+ for count in range(20):64+ for item in range(1000):65 escape("foo")66 escape("<foo>")67 escape(u"foo")68 escape(u"<foo>")14 unmodified linesmodified:jinja2/compiler.py+11 added-8 removed
14 unmodified lines15 from jinja2.nodes import EvalContext16 from jinja2.visitor import NodeVisitor17 from jinja2.exceptions import TemplateAssertionError18 from jinja2.utils import Markup, concat, escape, is_python_keyword, next19+import six20+from six.moves import map21+from six.moves import zip22 23 24 operators = {25 'eq': '==',6 unmodified lines32 'notin': 'not in'33 }34 35 try:33- exec '(0 if 0 else 0)'36+ exec('(0 if 0 else 0)')37 except SyntaxError:38 have_condexpr = False39 else:40 have_condexpr = True12 unmodified lines53 x = 4254 def f():55 if 0: dummy(x)56 return f54-unoptimize_before_dead_code = bool(unoptimize_before_dead_code().func_closure)57+unoptimize_before_dead_code = bool(unoptimize_before_dead_code().__closure__)58 59 60 def generate(node, environment, name, filename, stream=None,61 defer_init=False):18 unmodified lines80 if not has_safe_repr(item):81 return False82 return True83 elif isinstance(value, dict):81- for key, value in value.iteritems():84+ for key, value in six.iteritems(value):85 if not has_safe_repr(key):86 return False87 if not has_safe_repr(value):88 return False455 unmodified lines544 for kwarg in node.kwargs:545 self.write(', ')546 self.visit(kwarg, frame)547 if extra_kwargs is not None:545- for key, value in extra_kwargs.iteritems():548+ for key, value in six.iteritems(extra_kwargs):549 self.write(', %s=%s' % (key, value))550 if node.dyn_args:551 self.write(', *')552 self.visit(node.dyn_args, frame)7 unmodified lines560 self.write('%r: ' % kwarg.key)561 self.visit(kwarg.value, frame)562 self.write(', ')563 if extra_kwargs is not None:561- for key, value in extra_kwargs.iteritems():564+ for key, value in six.iteritems(extra_kwargs):565 self.write('%r: %s, ' % (key, value))566 if node.dyn_kwargs is not None:567 self.write('}, **')568 self.visit(node.dyn_kwargs, frame)58 unmodified lines627 return aliases628 629 def pop_scope(self, aliases, frame):630 """Restore all aliases and delete unused variables."""628- for name, alias in aliases.iteritems():631+ for name, alias in six.iteritems(aliases):632 self.writeline('l_%s = %s' % (name, alias))633 to_delete = set()634 for name in frame.identifiers.declared_locally:635 if name not in aliases:193 unmodified lines829 self.writeline('yield event')830 self.outdent(2 + (not self.has_known_extends))831 832 # at this point we now have the blocks collected and can visit them too.830- for name, block in self.blocks.iteritems():833+ for name, block in six.iteritems(self.blocks):834 block_frame = Frame(eval_ctx)835 block_frame.inspect(block.body)836 block_frame.block = name837 self.writeline('def block_%s(context%s):' % (name, envenv),380 unmodified lines1218 if self.has_known_extends and frame.require_output_check:1219 return1220 1221 if self.environment.finalize:1219- finalize = lambda x: unicode(self.environment.finalize(x))1222+ finalize = lambda x: six.text_type(self.environment.finalize(x))1223 else:1224 finalize = unicode1225 1226 # if we are inside a frame that requires output checking, we do so426 unmodified linesmodified:jinja2/debug.py+5 added-4 removed
13 unmodified lines14 import traceback15 from types import TracebackType16 from jinja2.utils import CodeType, missing, internal_code17 from jinja2.exceptions import TemplateSyntaxError18+import six19 20 # on pypy we can take advantage of transparent proxies21 try:22 from __pypy__ import tproxy2 unmodified lines25 26 27 # how does the raise helper look like?28 try:28- exec "raise TypeError, 'foo'"29+ exec("raise TypeError, 'foo'")30 except SyntaxError:31 raise_helper = 'raise __jinja_exception__[1]'32 except TypeError:33 raise_helper = 'raise __jinja_exception__[0], __jinja_exception__[1]'124 unmodified lines158 tb = exc_info[2]159 frames = []160 161 # skip some internal frames if wanted161- for x in xrange(initial_skip):162+ for x in range(initial_skip):163 if tb is not None:164 tb = tb.tb_next165 initial_tb = tb166 39 unmodified lines206 if ctx:207 locals = ctx.get_all()208 else:209 locals = {}209- for name, value in real_locals.iteritems():210+ for name, value in six.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 get39 unmodified lines254 pass255 256 # execute the code and catch the new traceback257 try:257- exec code in globals, locals258+ exec(code, globals, locals)259 except:260 exc_info = sys.exc_info()261 new_tb = exc_info[2].tb_next262 78 unmodified linesmodified:jinja2/environment.py+14 added-9 removed
19 unmodified lines20 from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \21 TemplatesNotFound22 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 zip29 30 31 # for direct template usage we have up to ten living environments32 _spontaneous_environments = LRUCache(10)263 unmodified lines296 """Add the items to the instance of the environment if they do not exist297 yet. This is used by :ref:`extensions <writing-extensions>` to register298 callbacks and configuration values without breaking inheritance.299 """295- for key, value in attributes.iteritems():300+ for key, value in six.iteritems(attributes):301 if not hasattr(self, key):302 setattr(self, key, value)303 304 def overlay(self, block_start_string=missing, block_end_string=missing,22 unmodified lines327 rv.__dict__.update(self.__dict__)328 rv.overlayed = True329 rv.linked_to = self330 326- for key, value in args.iteritems():331+ for key, value in six.iteritems(args):332 if value is not missing:333 setattr(rv, key, value)334 335 if cache_size is not missing:1 unmodified line337 else:338 rv.cache = copy_cache(self.cache)339 340 rv.extensions = {}336- for key, value in self.extensions.iteritems():341+ for key, value in six.iteritems(self.extensions):342 rv.extensions[key] = value.bind(rv)343 if extensions is not missing:344 rv.extensions.update(load_extensions(rv, extensions))345 65 unmodified lines411 This does not perform preprocessing. If you want the preprocessing412 of the extensions to be applied you have to filter source through413 the :meth:`preprocess` method.414 """410- source = unicode(source)415+ source = six.text_type(source)416 try:417 return self.lexer.tokeniter(source, name, filename)418 except TemplateSyntaxError:419 exc_info = sys.exc_info()4 unmodified lines424 called for all parsing and compiling methods but *not* for :meth:`lex`425 because there you usually only want the actual source tokenized.426 """427 return reduce(lambda s, e: e.preprocess(s, name, filename),423- self.iter_extensions(), unicode(source))428+ self.iter_extensions(), six.text_type(source))429 430 def _tokenize(self, source, name, filename=None, state=None):431 """Called by the parser to do the preprocessing and filtering432 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.148 unmodified lines581 582 def write_file(filename, data, mode):583 if zip:584 info = ZipInfo(filename)580- info.external_attr = 0755 << 16L585+ info.external_attr = 0o755 << 16586 zip_file.writestr(info, data)587 else:588 f = open(os.path.join(target, filename), mode)589 try:15 unmodified lines605 for name in self.list_templates(extensions, filter_func):606 source, filename, _ = self.loader.get_source(self, name)607 try:608 code = self.compile(source, name, filename, True, True)604- except TemplateSyntaxError, e:609+ except TemplateSyntaxError as e:610 if not ignore_errors:611 raise612 log_function('Could not compile "%s": %s' % (name, e))613 continue233 unmodified lines847 namespace = {848 'environment': environment,849 '__file__': code.co_filename850 }846- exec code in namespace851+ exec(code, namespace)852 rv = cls._from_namespace(environment, namespace, globals)853 rv._uptodate = uptodate854 return rv855 151 unmodified lines1007 def __html__(self):1008 return Markup(concat(self._body_stream))1009 1010 def __str__(self):1006- return unicode(self).encode('utf-8')1011+ return six.text_type(self).encode('utf-8')1012 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 let115 unmodified linesmodified:jinja2/exceptions.py+5 added-2 removed
6 unmodified lines7 8 :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 zip14 15 16 class TemplateError(Exception):17 """Baseclass for all template errors."""18 19 def __init__(self, message=None):20 if message is not None:18- message = unicode(message).encode('utf-8')21+ message = six.text_type(message).encode('utf-8')22 Exception.__init__(self, message)23 24 @property25 def message(self):59 unmodified lines85 # function translated the syntax error into a new traceback86 self.translated = False87 88 def __str__(self):86- return unicode(self).encode('utf-8')89+ return six.text_type(self).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 let53 unmodified linesmodified:jinja2/ext.py+3 added-2 removed
15 unmodified lines16 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, next20+import six21 22 23 # the only real useful gettext functions for a Jinja template. Note24 # that ugettext must be assigned to gettext as Jinja doesn't support329 unmodified lines354 # in case newstyle gettext is used, the method is powerful355 # enough to handle the variable expansion and autoescape356 # handling itself357 if self.environment.newstyle_gettext:357- for key, value in variables.iteritems():358+ for key, value in six.iteritems(variables):359 # the function adds that later anyways in case num was360 # called num, so just skip it.361 if num_called_num and key == 'num':362 continue238 unmodified lines601 source = fileobj.read().decode(options.get('encoding', 'utf-8'))602 try:603 node = environment.parse(source)604 tokens = list(environment.lex(environment.preprocess(source)))604- except TemplateSyntaxError, e:605+ except TemplateSyntaxError as e:606 if not silent:607 raise608 # skip templates with syntax errors609 return12 unmodified linesmodified:jinja2/filters.py+18 added-14 removed
15 unmodified lines16 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 zip23 24 25 _word_re = re.compile(r'\w+(?u)')26 43 unmodified lines70 def do_forceescape(value):71 """Enforce HTML escaping. This will probably double escape variables."""72 if hasattr(value, '__html__'):73 value = value.__html__()71- return escape(unicode(value))74+ return escape(six.text_type(value))75 76 77 def do_urlencode(value):78 """Escape strings for use in URLs (uses UTF-8 encoding). It accepts both2 unmodified lines81 .. versionadded:: 2.782 """83 itemiter = None84 if isinstance(value, dict):82- itemiter = value.iteritems()85+ itemiter = six.iteritems(value)86 elif not isinstance(value, basestring):87 try:88 itemiter = iter(value)89 except TypeError:22 unmodified lines112 """113 if count is None:114 count = -1115 if not eval_ctx.autoescape:113- return unicode(s).replace(unicode(old), unicode(new), count)116+ return six.text_type(s).replace(six.text_type(old), six.text_type(new), count)117 if hasattr(old, '__html__') or hasattr(new, '__html__') and \118 not hasattr(s, '__html__'):119 s = escape(s)120 else:36 unmodified lines157 if the filter returned something unless the second parameter is false.158 """159 rv = u' '.join(160 u'%s="%s"' % (escape(key), escape(value))158- for key, value in d.iteritems()161+ for key, value in six.iteritems(d)162 if value is not None and not isinstance(value, Undefined)163 )164 if autospace and rv:165 rv = u' ' + rv145 unmodified lines311 value = imap(make_attrgetter(eval_ctx.environment, attribute), value)312 313 # no automatic escaping? joining is a lot eaiser then314 if not eval_ctx.autoescape:312- return unicode(d).join(imap(unicode, value))315+ return six.text_type(d).join(imap(unicode, value))316 317 # if the delimiter doesn't have an html representation we check318 # if any of the items has. If yes we do a coercion to Markup319 if not hasattr(d, '__html__'):2 unmodified lines322 for idx, item in enumerate(value):323 if hasattr(item, '__html__'):324 do_escape = True325 else:323- value[idx] = unicode(item)326+ value[idx] = six.text_type(item)327 if do_escape:328 d = escape(d)329 else:327- d = unicode(d)330+ d = six.text_type(d)331 return d.join(value)332 333 # no html involved, to normal joining334 return soft_unicode(d).join(imap(soft_unicode, value))335 336 337 def do_center(value, width=80):338 """Centers the value in a field of a given width."""336- return unicode(value).center(width)339+ return six.text_type(value).center(width)340 341 342 @environmentfilter343 def do_first(environment, seq):344 """Return the first item of a sequence."""345 try:343- return iter(seq).next()346+ return six.advance_iterator(iter(seq))347 except StopIteration:348 return environment.undefined('No first item, sequence was empty.')349 350 351 @environmentfilter352 def do_last(environment, seq):353 """Return the last item of a sequence."""354 try:352- return iter(reversed(seq)).next()355+ return six.advance_iterator(iter(reversed(seq)))356 except StopIteration:357 return environment.undefined('No last item, sequence was empty.')358 359 181 unmodified lines541 """Strip SGML/XML tags and replace adjacent whitespace by one space.542 """543 if hasattr(value, '__html__'):544 value = value.__html__()542- return Markup(unicode(value)).striptags()545+ return Markup(six.text_type(value)).striptags()546 547 548 def do_slice(value, slices, fill_with=None):549 """Slice an iterator and return a list of lists containing19 unmodified lines569 length = len(seq)570 items_per_slice = length // slices571 slices_with_extra = length % slices572 offset = 0570- for slice_number in xrange(slices):573+ for slice_number in range(slices):574 start = offset + slice_number * items_per_slice575 if slice_number < slices_with_extra:576 offset += 1577 end = offset + (slice_number + 1) * items_per_slice116 unmodified lines694 __slots__ = ()695 grouper = property(itemgetter(0))696 list = property(itemgetter(1))697 695- def __new__(cls, (key, value)):698+ def __new__(cls, xxx_todo_changeme):699+ (key, value) = xxx_todo_changeme700 return tuple.__new__(cls, (key, list(value)))701 702 703 @environmentfilter32 unmodified lines736 737 738 def do_mark_unsafe(value):739 """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""736- return unicode(value)740+ return six.text_type(value)741 742 743 def do_reverse(value):744 """Reverse the object or return an iterator the iterates over it the other88 unmodified linesmodified:jinja2/lexer.py+7 added-6 removed
17 unmodified lines18 from operator import itemgetter19 from collections import deque20 from jinja2.exceptions import TemplateSyntaxError21 from jinja2.utils import LRUCache, next22+import six23 24 25 # cache for the lexers. Exists in order to be able to have multiple26 # environments with the same lexer99 unmodified lines126 ',': TOKEN_COMMA,127 ';': TOKEN_SEMICOLON128 }129 129-reverse_operators = dict([(v, k) for k, v in operators.iteritems()])130+reverse_operators = dict([(v, k) for k, v in six.iteritems(operators)])131 assert len(operators) == len(reverse_operators), 'operators dropped'132 operator_re = re.compile('(%s)' % '|'.join(re.escape(x) for x in133 sorted(operators, key=lambda x: -len(x))))134 184 unmodified lines319 return result320 321 def skip(self, n=1):322 """Got n tokens ahead."""322- for x in xrange(n):323+ for x in range(n):324 next(self)325 326 def next_if(self, expr):327 """Perform the token test and return the token if it matched.198 unmodified lines526 try:527 value = self._normalize_newlines(value[1:-1]) \528 .encode('ascii', 'backslashreplace') \529 .decode('unicode-escape')529- except Exception, e:530+ except Exception as e:531 msg = str(e).split(':')[-1].strip()532 raise TemplateSyntaxError(msg, lineno, name, filename)533 # if we can express it as bytestring (ascii only)534 # we do that for support of semi broken APIs14 unmodified lines549 def tokeniter(self, source, name, filename=None, state=None):550 """This method tokenizes the text and returns the tokens in a551 generator. Use this method if you just want to tokenize a template.552 """552- source = '\n'.join(unicode(source).splitlines())553+ source = '\n'.join(six.text_type(source).splitlines())554 pos = 0555 lineno = 1556 stack = ['root']557 if state is not None and state != 'root':32 unmodified lines590 # bygroup is a bit more complex, in that case we591 # yield for the current token the first named592 # group that matched593 elif token == '#bygroup':593- for key, value in m.groupdict().iteritems():594+ for key, value in six.iteritems(m.groupdict()):595 if value is not None:596 yield lineno, key, value597 lineno += value.count('\n')598 break48 unmodified lines647 if new_state == '#pop':648 stack.pop()649 # resolve the new state by group checking650 elif new_state == '#bygroup':650- for key, value in m.groupdict().iteritems():651+ for key, value in six.iteritems(m.groupdict()):652 if value is not None:653 stack.append(key)654 break655 else:27 unmodified linesmodified:jinja2/loaders.py+2 added-1 removed
11 unmodified lines12 import sys13 import weakref14 from types import ModuleType15 from os import path16+import six17 try:18 from hashlib import sha119 except ImportError:20 from sha import new as sha1338 unmodified lines359 raise TemplateNotFound(name)360 361 def list_templates(self):362 result = []362- for prefix, loader in self.mapping.iteritems():363+ for prefix, loader in six.iteritems(self.mapping):364 for template in loader.list_templates():365 result.append(prefix + self.delimiter + template)366 return result367 107 unmodified linesmodified:jinja2/nodes.py+4 added-3 removed
14 unmodified lines15 import operator16 from itertools import chain, izip17 from collections import deque18 from jinja2.utils import Markup, MethodType, FunctionType19+import six20 21 22 #: the types we support for context functions23 _context_function_types = (FunctionType, MethodType)118 unmodified lines142 for attr in self.attributes:143 setattr(self, attr, attributes.pop(attr, None))144 if attributes:145 raise TypeError('unknown attribute %r' %145- iter(attributes).next())146+ six.advance_iterator(iter(attributes)))147 148 def iter_fields(self, exclude=None, only=None):149 """This method iterates over all fields that are defined and yields150 ``(key, value)`` tuples. Per default all fields are returned, but289 unmodified lines440 """Return a const object if the value is representable as441 constant value in the generated code, otherwise it will raise442 an `Impossible` exception.443 """443- from compiler import has_safe_repr444+ from .compiler import has_safe_repr445 if not has_safe_repr(value):446 raise Impossible()447 return cls(value, lineno=lineno, environment=environment)448 238 unmodified lines687 fields = ('nodes',)688 689 def as_const(self, eval_ctx=None):690 eval_ctx = get_eval_context(self, eval_ctx)690- return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)691+ return ''.join(six.text_type(x.as_const(eval_ctx)) for x in self.nodes)692 693 694 class Compare(Expr):695 """Compares an expression with some other expressions. `ops` must be a216 unmodified linesmodified:jinja2/parser.py+2 added
10 unmodified lines11 from jinja2 import nodes12 from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError13 from jinja2.utils import next14 from jinja2.lexer import describe_token, describe_token_expr15+from six.moves import map16+from six.moves import zip17 18 19 #: statements that callinto 20 _statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',877 unmodified linesmodified:jinja2/runtime.py+5 added-4 removed
12 unmodified lines13 from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \14 concat, internalcode, next, object_type_repr15 from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \16 TemplateNotFound17+import six18 19 20 # these variables are exported to the template runtime21 __all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',41 unmodified lines63 # if the parent is shared a copy should be created because64 # we don't want to modify the dict passed65 if shared:66 parent = dict(parent)66- for key, value in locals.iteritems():67+ for key, value in six.iteritems(locals):68 if key[:2] == 'l_' and value is not missing:69 parent[key[2:]] = value70 return Context(environment, parent, template_name, blocks)71 47 unmodified lines119 120 # create the initial mapping of blocks. Whenever template inheritance121 # takes place the runtime will update this mapping with the new blocks122 # from the template.122- self.blocks = dict((k, [v]) for k, v in blocks.iteritems())123+ self.blocks = dict((k, [v]) for k, v in six.iteritems(blocks))124 125 def super(self, name, current):126 """Render a parent block."""127 try:63 unmodified lines191 context = new_context(self.environment, self.name, {},192 self.parent, True, None, locals)193 context.vars.update(self.vars)194 context.eval_ctx = self.eval_ctx194- context.blocks.update((k, list(v)) for k, v in self.blocks.iteritems())195+ context.blocks.update((k, list(v)) for k, v in six.iteritems(self.blocks))196 return context197 198 def _all(meth):199 proxy = lambda self: getattr(self.get_all(), meth)()283 unmodified lines483 __float__ = __complex__ = __pow__ = __rpow__ = \484 _fail_with_undefined_error485 486 def __str__(self):486- return unicode(self).encode('utf-8')487+ return six.text_type(self).encode('utf-8')488 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 let71 unmodified linesmodified:jinja2/sandbox.py+1 added-1 removed
88 unmodified lines89 def safe_range(*args):90 """A range that can't generate ranges with a length of more than91 MAX_RANGE items.92 """93- rng = xrange(*args)93+ rng = range(*args)94 if len(rng) > MAX_RANGE:95 raise OverflowError('range too big, maximum size for range is %d' %96 MAX_RANGE)97 return rng264 unmodified linesmodified:jinja2/tests.py+3 added-2 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import re12 from jinja2.runtime import Undefined13+import six14 15 try:16 from collections import Mapping as MappingType17 except ImportError:58 unmodified lines76 77 78 def test_lower(value):79 """Return true if the variable is lowercased."""79- return unicode(value).islower()80+ return six.text_type(value).islower()81 82 83 def test_upper(value):84 """Return true if the variable is uppercased."""84- return unicode(value).isupper()85+ return six.text_type(value).isupper()86 87 88 def test_string(value):89 """Return true if the object is a string."""73 unmodified linesmodified:jinja2/utils.py+11 added-10 removed
9 unmodified lines10 """11 import re12 import sys13 import errno14+import six15 try:16 from urllib.parse import quote_from_bytes as url_quote17 except ImportError:18 from urllib import quote as url_quote33 unmodified lines52 def _test_gen_bug():53 raise TypeError(_test_gen_bug)54 yield None55 _concat(_test_gen_bug())55-except TypeError, _error:56+except TypeError as _error:57 if not _error.args or _error.args[0] is not _test_gen_bug:58 def concat(gen):59 try:60 return _concat(list(gen))12 unmodified lines73 try:74 next = next75 except NameError:76 def next(x):76- return x.next()77+ return six.advance_iterator(x)78 79 80 # if this python version is unable to deal with unicode filenames81 # when passed to encode we let this function encode it properly.23 unmodified lines105 yield None106 FunctionType = type(_func)107 GeneratorType = type(_func())108 MethodType = type(_C.method)108-CodeType = type(_C.method.func_code)109+CodeType = type(_C.method.__code__)110 try:111 raise TypeError()112 except TypeError:113 _tb = sys.exc_info()[2]42 unmodified lines156 157 158 def internalcode(f):159 """Marks the function as internally used"""159- internal_code.add(f.func_code)160+ internal_code.add(f.__code__)161 return f162 163 164 def is_undefined(obj):61 unmodified lines226 otherwise `None`.227 """228 try:229 return open(filename, mode)229- except IOError, e:230+ except IOError as e:231 if e.errno not in (errno.ENOENT, errno.EISDIR):232 raise233 234 40 unmodified lines275 """276 trim_url = lambda x, limit=trim_url_limit: limit is not None \277 and (x[:limit] + (len(x) >=limit and '...'278 or '')) or x278- words = _word_split_re.split(unicode(escape(text)))279+ words = _word_split_re.split(six.text_type(escape(text)))280 nofollow_attr = nofollow and ' rel="nofollow"' or ''281 for i, word in enumerate(words):282 match = _punctuation_re.match(word)283 if match:28 unmodified lines312 from random import choice, randrange313 words = LOREM_IPSUM_WORDS.split()314 result = []315 315- for _ in xrange(n):316+ for _ in range(n):317 next_capitalized = True318 last_comma = last_fullstop = 0319 word = None320 last = None321 p = []322 323 # each paragraph contains out of 20 to 100 words.323- for idx, _ in enumerate(xrange(randrange(min, max))):324+ for idx, _ in enumerate(range(randrange(min, max))):325 while True:326 word = choice(words)327 if word != last:328 last = word34 unmodified lines363 If non strings are provided they are converted to their unicode364 representation first.365 """366 if not isinstance(obj, basestring):366- obj = unicode(obj)367+ obj = six.text_type(obj)368 if isinstance(obj, unicode):369 obj = obj.encode(charset)369- return unicode(url_quote(obj))370+ return six.text_type(url_quote(obj))371 372 373 class LRUCache(object):374 """A simple LRU Cache implementation."""252 unmodified lines