Skip to content
Myr

PY3 -> PY2 macro

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 630804f · Browse files · 10 files+95 added−58 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

10 files+95 added−58 removed

  • other:+95 added−58 removed

10 files+95 added−58 removed

modified:jinja2/testsuite/__init__.py+2 added-2 removed
14 unmodified lines
15import sys16import unittest17from traceback import format_exception18from jinja2 import loaders19from jinja2._compat import PY319from jinja2._compat import PY2202122here = os.path.dirname(os.path.abspath(__file__))23
65 unmodified lines
89 suite.addTest(utils.suite())9091 # doctests will not run on python 3 currently. Too many issues92 # with that, do not test that on that platform.93 if not PY3:93 if PY2:94 suite.addTest(doctests.suite())9596 return suite
modified:jinja2/testsuite/filters.py+5 added-5 removed
10 unmodified lines
11import unittest12from jinja2.testsuite import JinjaTestCase1314from jinja2 import Markup, Environment15from jinja2._compat import text_type, PY315from jinja2._compat import text_type, PY21617env = Environment()1819
278 unmodified lines
298 def __init__(self, value):299 self.value = value300 def __unicode__(self):301 return text_type(self.value)302 if PY3:303 __str__ = __unicode__304 del __unicode__305 else:302 if PY2:303 def __str__(self):304 return self.__unicode__().encode('utf-8')305 else:306 __str__ = __unicode__307 del __unicode__308 tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')309 assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'310311 def test_groupby(self):
195 unmodified lines
modified:jinja2/testsuite/lexnparse.py+2 added-2 removed
12 unmodified lines
13from jinja2.testsuite import JinjaTestCase1415from jinja2 import Environment, Template, TemplateSyntaxError, \16 UndefinedError, nodes17from jinja2._compat import next, iteritems, text_type, PY317from jinja2._compat import next, iteritems, text_type, PY218from jinja2.lexer import Token, TokenStream, TOKEN_EOF, \19 TOKEN_BLOCK_BEGIN, TOKEN_BLOCK_END2021env = Environment()222324# how does a string look like in jinja syntax?25if not PY3:25if PY2:26 def jinja_string_repr(string):27 return repr(string)[1:]28else:29 jinja_string_repr = repr
564 unmodified lines
modified:jinja2/_compat.py+60 added-26 removed
1 unmodified line
2"""3 jinja2._compat4 ~~~~~~~~~~~~~~56 Some py2/py3 compatibility support that is not yet available in7 "six" 1.3.0. Generally all uses of six should go through this module8 so that we have one central place to remove stuff from when we9 eventually drop 2.x.6 Some py2/py3 compatibility support based on a stripped down7 version of six so we don't have to depend on a specific version8 of it.910 :copyright: Copyright 2013 by the Jinja team, see AUTHORS.11 :license: BSD, see LICENSE for details.12"""14import six13import sys1417PY3 = six.PY315PY2 = sys.version_info[0] == 21619# https://bitbucket.org/gutworth/six/issue/25/add-unichr20try:21 unichr = unichr # py222except NameError:23 unichr = chr # py31725range_type = six.moves.xrange26next = six.advance_iterator27imap = six.moves.map28izip = six.moves.zip29text_type = six.text_type30string_types = six.string_types18if not PY2:19 unichr = chr20 range_type = range21 text_type = str22 string_types = (str,)2332iteritems = six.iteritems33iterkeys = six.iterkeys34itervalues = six.itervalues24 _iterkeys = 'keys'25 _itervalues = 'values'26 _iteritems = 'items'2736if six.PY3:28 from io import BytesIO, StringIO29 NativeStringIO = StringIO3031 ifilter = filter32 imap = map33 izip = zip3435 def reraise(tp, value, tb=None):36 if value.__traceback__ is not tb:37 raise value.with_traceback(tb)38 raise value3940 Iterator = object41else:42 text_type = unicode43 unichr = unichr44 string_types = (str, unicode)4546 _iterkeys = 'iterkeys'47 _itervalues = 'itervalues'48 _iteritems = 'iteritems'4950 from itertools import imap, izip, ifilter51 range_type = xrange5253 from cStringIO import StringIO as BytesIO54 from StringIO import StringIO55 NativeStringIO = BytesIO5657 exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')5859 class Iterator(object):60 def next(self):61 return self.__next__()6263try:64 next = next65except NameError:66 def next(it):67 return it.next()686970def with_metaclass(meta, *bases):71 """Create a base class with a metaclass."""72 return meta('NewBase', bases, {})7374def iterkeys(d, **kw):75 return iter(getattr(d, _iterkeys)(**kw))7677def itervalues(d, **kw):78 return iter(getattr(d, _itervalues)(**kw))7980def iteritems(d, **kw):81 return iter(getattr(d, _iteritems)(**kw))8283try:84 import cPickle as pickle85except ImportError:86 import pickle8749ifilter = six.moves.filter50reraise = six.reraise51Iterator = six.Iterator52with_metaclass = six.with_metaclass5388try:89 from collections import Mapping as mapping_types90except ImportError:91 import UserDict
21 unmodified lines
modified:jinja2/bccache.py+2 added-2 removed
19 unmodified lines
20import tempfile21import fnmatch22from hashlib import sha123from jinja2.utils import open_if_exists24from jinja2._compat import BytesIO, pickle, PY324from jinja2._compat import BytesIO, pickle, PY2252627# marshal works better on 3.x, one hack less required28if PY3:28if not PY2:29 marshal_dump = marshal.dump30 marshal_load = marshal.load31else:32
279 unmodified lines
modified:jinja2/environment.py+8 added-5 removed
26 unmodified lines
27 TemplatesNotFound, TemplateRuntimeError28from jinja2.utils import import_string, LRUCache, Markup, missing, \29 concat, consume, internalcode, _encode_filename30from jinja2._compat import imap, ifilter, string_types, iteritems, \31 text_type, reraise, PY3, Iterator, next31 text_type, reraise, PY2, Iterator, next32from functools import reduce333435# for direct template usage we have up to ten living environments
1028 unmodified lines
10641065 def __html__(self):1066 return Markup(concat(self._body_stream))10671068 def __str__(self):1069 s = self.__unicode__()1070 return s if PY3 else s.encode('utf-8')10711068 def __unicode__(self):1069 return concat(self._body_stream)10701071 if PY2:1072 def __str__(self):1073 return self.__unicode__().encode('utf-8')1074 else:1075 __str__ = __unicode__1076 del __unicode__10771078 def __repr__(self):1079 if self.__name__ is None:1080 name = 'memory:%x' % id(self)1081 else:
107 unmodified lines
modified:jinja2/exceptions.py+6 added-6 removed
6 unmodified lines
78 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11from jinja2._compat import imap, text_type, PY311from jinja2._compat import imap, text_type, PY2121314class TemplateError(Exception):15 """Baseclass for all template errors."""1617 if not PY3:17 if PY2:18 def __init__(self, message=None):19 if message is not None:20 message = text_type(message).encode('utf-8')21 Exception.__init__(self, message)
92 unmodified lines
114 lines.append(' ' + line.strip())115116 return u'\n'.join(lines)117118 if PY3:119 __str__ = __unicode__120 del __unicode__121 else:118 if PY2:119 def __str__(self):120 return self.__unicode__().encode('utf-8')121 else:122 __str__ = __unicode__123 del __unicode__124125126class TemplateAssertionError(TemplateSyntaxError):127 """Like a template syntax error, but covers cases where something in the
26 unmodified lines
modified:jinja2/runtime.py+7 added-7 removed
13 unmodified lines
14 internalcode, object_type_repr15from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \16 TemplateNotFound17from jinja2._compat import next, imap, text_type, iteritems, Iterator, \18 string_types, PY318 string_types, PY2192021# these variables are exported to the template runtime22__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',
477 unmodified lines
500501 def __unicode__(self):502 return u''503504 if PY3:505 __str__ = __unicode__506 del __unicode__507 else:504 if PY2:505 def __str__(self):506 return self.__unicode__().encode('utf-8')507 else:508 __str__ = __unicode__509 del __unicode__510511 def __len__(self):512 return 0513
32 unmodified lines
546 self._undefined_name547 )548 return u'{{ undefined value printed: %s }}' % self._undefined_hint549550 if PY3:550 if not PY2:551 __str__ = __unicode__552 del __unicode__553554
19 unmodified lines
574 __slots__ = ()575 __iter__ = __str__ = __len__ = __nonzero__ = __eq__ = \576 __ne__ = __bool__ = Undefined._fail_with_undefined_error577578 if not PY3:578 if PY2:579 __unicode__ = Undefined._fail_with_undefined_error580581582# remove remaining slots attributes, after the metaclass did the magic they
2 unmodified lines
modified:jinja2/utils.py+2 added-2 removed
21 unmodified lines
22 from _thread import allocate_lock # py 323 except ImportError:24 from dummy_thread import allocate_lock25from collections import deque26from jinja2._compat import text_type, string_types, Iterator, PY326from jinja2._compat import text_type, string_types, Iterator, PY2272829_word_split_re = re.compile(r'(\s+)')30_punctuation_re = re.compile(
21 unmodified lines
52# when passed to encode we let this function encode it properly.53# This is used in a couple of places. As far as Jinja is concerned54# filenames are unicode *or* bytestrings in 2.x and unicode only in55# 3.x because compile cannot handle bytes56if not PY3:56if PY2:57 def _encode_filename(filename):58 if isinstance(filename, unicode):59 return filename.encode('utf-8')60 return filename
489 unmodified lines
modified:setup.py+1 added-1 removed
78 unmodified lines
79 'Topic :: Software Development :: Libraries :: Python Modules',80 'Topic :: Text Processing :: Markup :: HTML'81 ],82 packages=['jinja2', 'jinja2.testsuite', 'jinja2.testsuite.res'],83 install_requires=['six>=1.3.0', 'markupsafe'],83 install_requires=['markupsafe'],84 extras_require={'i18n': ['Babel>=0.8']},85 test_suite='jinja2.testsuite.suite',86 include_package_data=True,87 entry_points="""
4 unmodified lines