added first code for parser extensions and moved some code in speedups around
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent f41d139 · Browse files · 15 files·+275 added−89 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+275 added−89 removed
- other:+275 added−89 removed
Provenance
- Commit
f59bac2- Tree
b8b31be- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
f41d139
15 files changed+275 added−89 removed
modified:examples/translate.py+1 added-2 removed
1 from jinja2 import Environment2 3-print Environment().from_string("""\4-{{ foo.bar }}3+print Environment(parser_extensions=['jinja2.i18n.trans']).from_string("""\4 {% trans %}Hello {{ user }}!{% endtrans %}5 {% trans count=users|count %}{{ count }} user{% pluralize %}{{ count }} users{% endtrans %}6 """).render(user="someone")modified:jinja2/__init__.py+1 added
58 unmodified lines59 from jinja2.environment import Environment60 from jinja2.loaders import BaseLoader, FileSystemLoader, PackageLoader, \61 DictLoader62 from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined63+from jinja2.filters import environmentfilter, contextfilter64 from jinja2.utils import Markup, escapemodified:jinja2/_speedups.c+27 added-23 removed
44 unmodified lines45 while (*(inp) || in->length > inp - in->str)46 switch (*inp++) {47 case '&':48 len += 5;49- erepl++;49+ ++erepl;50 break;51 case '"':52 len += 6;53- erepl++;53+ ++erepl;54 break;55 case '<':56 case '>':57 len += 4;58- erepl++;58+ ++erepl;59 break;60 default:61- len++;61+ ++len;62 }63 64 /* Do we need to escape anything at all? */65 if (!erepl) {17 unmodified lines83 switch (*inp) {84 case '&':85 Py_UNICODE_COPY(outp, amp, 5);86 outp += 5;87- repl++;87+ ++repl;88 break;89 case '"':90 Py_UNICODE_COPY(outp, qt, 6);91 outp += 6;92- repl++;92+ ++repl;93 break;94 case '<':95 Py_UNICODE_COPY(outp, lt, 4);96 outp += 4;97- repl++;97+ ++repl;98 break;99 case '>':100 Py_UNICODE_COPY(outp, gt, 4);101 outp += 4;102- repl++;102+ ++repl;103 break;104 default:105 *outp++ = *inp;106 };4 unmodified lines111 }112 113 114 static PyObject*115-escape(PyObject *self, PyObject *args)115+soft_unicode(PyObject *self, PyObject *s)116 {117- PyObject *text = NULL, *s = NULL, *rv = NULL;118- if (!PyArg_UnpackTuple(args, "escape", 1, 1, &text))119- return NULL;117+ if (!PyUnicode_Check(s))118+ return PyObject_Unicode(s);119+ Py_INCREF(s);120+ return s;121+}122 123+124+static PyObject*125+escape(PyObject *self, PyObject *text)126+{127+ PyObject *s = NULL, *rv = NULL;128+129 /* we don't have to escape integers, bools or floats */130 if (PyInt_CheckExact(text) || PyLong_CheckExact(text) ||131 PyFloat_CheckExact(text) || PyBool_Check(text) ||132 text == Py_None) {125- args = PyTuple_New(1);133+ PyObject *args = PyTuple_New(1);134 if (!args) {135 Py_DECREF(s);136 return NULL;137 }21 unmodified lines159 else160 s = escape_unicode((PyUnicodeObject*)text);161 162 /* convert the unicode string into a markup object. */155- args = PyTuple_New(1);156- if (!args) {157- Py_DECREF(s);158- return NULL;159- }160- PyTuple_SET_ITEM(args, 0, (PyObject*)s);161- rv = PyObject_CallObject(markup, args);162- Py_DECREF(args);163- return rv;163+ return PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL);164 }165 166 167 static PyObject *23 unmodified lines191 }192 193 194 static PyMethodDef module_methods[] = {195- {"escape", (PyCFunction)escape, METH_VARARGS,195+ {"escape", (PyCFunction)escape, METH_O,196 "escape(s) -> string\n\n"197 "Convert the characters &, <, >, and \" in string s to HTML-safe\n"198 "sequences. Use this if you need to display text that might contain\n"199 "such characters in HTML."},200+ {"soft_unicode", (PyCFunction)soft_unicode, METH_O,201+ "soft_unicode(object) -> string\n\n"202+ "Make a string unicode if it isn't already. That way a markup\n"203+ "string is not converted back to unicode."},204 {"tb_set_next", (PyCFunction)tb_set_next, METH_VARARGS,205 "Set the tb_next member of a traceback object."},206 {NULL, NULL, 0, NULL} /* Sentinel */207 };13 unmodified linesmodified:jinja2/compiler.py+6 added
278 unmodified lines279 280 # the current indentation281 self._indentation = 0282 283+ def get_visitor(self, node):284+ """Custom nodes have their own compilation method."""285+ if isinstance(node, nodes.CustomStmt):286+ return node.compile287+ return NodeVisitor.get_visitor(self, node)288+289 def temporary_identifier(self):290 """Get a new unique identifier."""291 self._last_identifier += 1292 return 't%d' % self._last_identifier772 unmodified linesmodified:jinja2/datastructure.py+24 added-13 removed
11 unmodified lines12 from collections import deque13 from jinja2.exceptions import TemplateSyntaxError, TemplateRuntimeError14 15 16-_missing = object()17-18-16 class Token(tuple):17 """18 Token class.19 """8 unmodified lines28 if self.type in keywords:29 return self.type30 elif self.type in reverse_operators:31 return reverse_operators[self.type]35- return self.value32+ return '%s:%s' % (self.type, self.value)33 34+ def test(self, expr):35+ """Test a token against a token expression. This can either be a36+ token type or 'token_type:token_value'. This can only test against37+ string values!38+ """39+ # here we do a regular string equality check as test_many is usually40+ # passed an iterable of not interned strings.41+ if self.type == expr:42+ return True43+ elif ':' in expr:44+ return expr.split(':', 1) == [self.type, self.value]45+ return False46+47+ def test_many(self, iterable):48+ """Test against multiple token expressions."""49+ for expr in iterable:50+ if self.test(expr):51+ return True52+ return False53+54 def __repr__(self):55 return 'Token(%r, %r, %r)' % (56 self.lineno,57 self.type,85 unmodified lines143 """Close the stream."""144 self.current = Token(self.current.lineno, 'eof', '')145 self._next = None146 130- def expect(self, token_type, token_value=_missing):147+ def expect(self, expr):148 """Expect a given token type and return it"""132- if self.current.type is not token_type:149+ if not self.current.test(expr):150 raise TemplateSyntaxError("expected token %r, got %r" %134- (token_type, self.current.type),151+ (expr, self.current),152 self.current.lineno,153 self.filename)137- elif token_value is not _missing and \138- self.current.value != token_value:139- raise TemplateSyntaxError("expected %r, got %r" %140- (token_value, self.current.value),141- self.current.lineno,142- self.filename)154 try:155 return self.current156 finally:157 self.next()modified:jinja2/environment.py+15 added-1 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import sys12 from jinja2.lexer import Lexer13-from jinja2.parser import Parser13+from jinja2.parser import Parser, ParserExtension14 from jinja2.optimizer import optimize15 from jinja2.compiler import generate16 from jinja2.runtime import Undefined17 from jinja2.debug import translate_exception18+from jinja2.utils import import_string19 from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE20 21 22 class Environment(object):20 unmodified lines43 trim_blocks=False,44 optimized=True,45 undefined=Undefined,46 loader=None,47+ parser_extensions=(),48 finalize=unicode):49 """Here the possible initialization parameters:50 51 ========================= ============================================17 unmodified lines69 ``True``.70 `undefined` a subclass of `Undefined` that is used to71 represent undefined variables.72 `loader` the loader which should be used.73+ `parser_extensions` List of parser extensions to use.74+ `finalize` A callable that finalizes the variable. Per75+ default this is `unicode`, other useful76+ builtin finalizers are `escape`.77 ========================= ============================================78 """79 80 # santity checks11 unmodified lines92 self.comment_start_string = comment_start_string93 self.comment_end_string = comment_end_string94 self.line_statement_prefix = line_statement_prefix95 self.trim_blocks = trim_blocks96+ self.parser_extensions = {}97+ for extension in parser_extensions:98+ if isinstance(extension, basestring):99+ extension = import_string(extension)100+ self.parser_extensions[extension.tag] = extension101+102+103+ # runtime information104 self.undefined = undefined105 self.optimized = optimized106 self.finalize = finalize107 222 unmodified linesmodified:jinja2/filters.py+12 added-2 removed
42 unmodified lines43 f.environmentfilter = True44 return f45 46 47+def do_forceescape(value):48+ """Enforce HTML escaping. This will probably double escape variables."""49+ if hasattr(value, '__html__'):50+ value = value.__html__()51+ return escape(unicode(value))52+53+54 def do_replace(s, old, new, count=None):55 """Return a copy of the value with all occurrences of a substring56 replaced with a new one. The first argument is the substring57 that should be replaced, the second is the replacement string.331 unmodified lines389 """390 try:391 return int(value)392 except (TypeError, ValueError):393+ # this quirk is necessary so that "42.23"|int gives 42.394 try:395 return int(float(value))396 except (TypeError, ValueError):397 return default32 unmodified lines430 431 def do_striptags(value):432 """Strip SGML/XML tags and replace adjacent whitespace by one space.433 """434+ if hasattr(value, '__html__'):435+ value = value.__html__()426- return ' '.join(_striptags_re.sub('', value).split())436+ return u' '.join(_striptags_re.sub('', value).split())437 438 439 def do_slice(value, slices, fill_with=None):440 """Slice an iterator and return a list of lists containing139 unmodified lines580 'upper': do_upper,581 'lower': do_lower,582 'escape': escape,583 'e': escape,574- 'xmlattr': do_xmlattr,584+ 'forceescape': do_forceescape,585 'capitalize': do_capitalize,586 'title': do_title,587 'default': do_default,588 'join': do_join,33 unmodified linesmodified:jinja2/i18n.py+79 added-6 removed
6 unmodified lines7 8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: BSD.10 """11+from collections import deque12 from jinja2 import nodes12-from jinja2.parser import _statement_end_tokens13+from jinja2.environment import Environment14+from jinja2.parser import ParserExtension, statement_end_tokens15 from jinja2.exceptions import TemplateAssertionError16 17 18+# the only real useful gettext functions for a Jinja template. Note19+# that ugettext must be assigned to gettext as Jinja doesn't support20+# non unicode strings.21+GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext')22+23+24+def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS):25+ """Extract localizable strings from the given template node.26+27+ For every string found this function yields a ``(lineno, function,28+ message)`` tuple, where:29+30+ * ``lineno`` is the number of the line on which the string was found,31+ * ``function`` is the name of the ``gettext`` function used (if the32+ string was extracted from embedded Python code), and33+ * ``message`` is the string itself (a ``unicode`` object, or a tuple34+ of ``unicode`` objects for functions with multiple string arguments).35+ """36+ for call in node.find_all(nodes.Call):37+ if not isinstance(node.node, nodes.Name) or \38+ node.node.name not in gettext_functions:39+ continue40+41+ strings = []42+ for arg in node.args:43+ if isinstance(arg, nodes.Const) and \44+ isinstance(arg.value, basestring):45+ strings.append(arg)46+ else:47+ strings.append(None)48+49+ if len(strings) == 1:50+ strings = strings[0]51+ else:52+ strings = tuple(strings)53+ yield node.lineno, node.node.name, strings54+55+56+def babel_extract(fileobj, keywords, comment_tags, options):57+ """Babel extraction method for Jinja templates.58+59+ :param fileobj: the file-like object the messages should be extracted from60+ :param keywords: a list of keywords (i.e. function names) that should be61+ recognized as translation functions62+ :param comment_tags: a list of translator tags to search for and include63+ in the results. (Unused)64+ :param options: a dictionary of additional options (optional)65+ :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.66+ (comments will be empty currently)67+ """68+ encoding = options.get('encoding', 'utf-8')69+ environment = Environment(70+ options.get('block_start_string', '{%'),71+ options.get('block_end_string', '%}'),72+ options.get('variable_start_string', '{{'),73+ options.get('variable_end_string', '}}'),74+ options.get('comment_start_string', '{#'),75+ options.get('comment_end_string', '#}'),76+ options.get('line_statement_prefix') or None,77+ options.get('trim_blocks', '').lower() in ('1', 'on', 'yes', 'true')78+ )79+ node = environment.parse(fileobj.read().decode(encoding))80+ for lineno, func, message in extract_from_ast(node, keywords):81+ yield lineno, func, message, []82+83+84 def parse_trans(parser):85 """Parse a translatable tag."""18- lineno = parser.stream.expect('trans').lineno86+ lineno = parser.stream.next().lineno87 88 # skip colon for python compatibility89 if parser.stream.current.type is 'colon':90 parser.stream.next()33 unmodified lines124 if plural_expr is None:125 plural_expr = nodes.Name(singular_names[0], 'load')126 127 # if we have a pluralize block, we parse that too60- if parser.stream.current.type is 'pluralize':128+ if parser.stream.current.test('name:pluralize'):129 have_plural = True130 parser.stream.next()131 if parser.stream.current.type is not 'block_end':132 plural_expr = parser.parse_expression()48 unmodified lines181 buf.append('%%(%s)s' % name)182 parser.stream.expect('variable_end')183 elif parser.stream.current.type is 'block_begin':184 parser.stream.next()117- if parser.stream.current.type is 'endtrans':185+ if parser.stream.current.test('name:endtrans'):186 break119- elif parser.stream.current.type is 'pluralize':187+ elif parser.stream.current.test('name:pluralize'):188 if allow_pluralize:189 break190 raise TemplateSyntaxError('a translatable section can have '191 'only one pluralize section',9 unmodified lines201 return referenced, u''.join(buf)202 203 204 def _make_node(singular, plural, variables, plural_expr):137- """Generates a useful node from the data provided."""205+ """Generates a useful node from the data provided. The nodes won't have206+ a line number information so the caller must set it via `set_lineno` later.207+ """208 # singular only:209 if plural_expr is None:210 gettext = nodes.Name('gettext', 'load')211 node = nodes.Call(gettext, [nodes.Const(singular)],11 unmodified lines223 ], [], None, None)224 if variables:225 node = nodes.Mod(node, variables)226 return nodes.Output([node])227+228+229+trans = ParserExtension('trans', parse_trans)modified:jinja2/lexer.py+3 added-3 removed
36 unmodified lines37 38 # set of used keywords39 keywords = set(['and', 'block', 'elif', 'else', 'endblock', 'print',40 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',41- 'endtrans', 'extends', 'filter', 'for', 'if', 'in',42- 'include', 'is', 'macro', 'not', 'or', 'pluralize', 'raw',43- 'recursive', 'set', 'trans', 'call', 'endcall'])41+ 'extends', 'filter', 'for', 'if', 'in',42+ 'include', 'is', 'macro', 'not', 'or', 'raw',43+ 'recursive', 'set', 'call', 'endcall'])44 45 # bind operators to token types46 operators = {47 '+': 'add',452 unmodified linesmodified:jinja2/nodes.py+22 added-1 removed
61 unmodified lines62 storage.extend(getattr(base, attr, ()))63 storage.extend(d.get(attr, ()))64 assert len(storage) == len(set(storage))65 d[attr] = tuple(storage)66- return type.__new__(cls, name, bases, d)66+ rv = type.__new__(cls, name, bases, d)67 68+ # unless the node is a subclass of `CustomNode` it may not69+ # be defined in any other module than the jinja2.nodes module.70+ # the reason for this is that the we don't want users to take71+ # advantage of the fact that the parser is using the node name72+ # only as callback name for non custom nodes. This could lead73+ # to broken code in the future and is disallowed because of this.74+ if rv.__module__ != 'jinja2.nodes' and not \75+ isinstance(rv, CustomStmt):76+ raise TypeError('non builtin node %r is not a subclass of '77+ 'CustomStmt.' % node.__class__.__name__)78+ return rv79 80+81 class Node(object):82 """Baseclass for all Jinja nodes."""83 __metaclass__ = NodeType84 fields = ()119 unmodified lines204 class Helper(Node):205 """Nodes that exist in a specific context only."""206 207 208+class CustomStmt(Stmt):209+ """Custom statements must extend this node."""210+211+ def compile(self, compiler):212+ """The compiler calls this method to get the python sourcecode213+ for the statement.214+ """215+216+217 class Template(Node):218 """Node that represents a template."""219 fields = ('body',)220 388 unmodified linesmodified:jinja2/parser.py+34 added-19 removed
6 unmodified lines7 8 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+from operator import itemgetter12 from jinja2 import nodes13 from jinja2.exceptions import TemplateSyntaxError14 15 16 _statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',16- 'macro', 'include', 'trans'])17+ 'macro', 'include'])18 _compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq', 'in'])18-_statement_end_tokens = set(['elif', 'else', 'endblock', 'endfilter',19+statement_end_tokens = set(['elif', 'else', 'endblock', 'endfilter',20 'endfor', 'endif', 'endmacro', 'variable_end',21 'in', 'recursive', 'endcall', 'block_end'])22 23 10 unmodified lines34 self.source = unicode(source)35 self.filename = filename36 self.closed = False37 self.stream = environment.lexer.tokenize(source, filename)38+ self.extensions = environment.parser_extensions39 40 def end_statement(self):41 """Make sure that the statement ends properly."""42 if self.stream.current.type is 'semicolon':43 self.stream.next()42- elif self.stream.current.type not in _statement_end_tokens:44+ elif self.stream.current.type not in statement_end_tokens:45 raise TemplateSyntaxError('ambigous end of statement',46 self.stream.current.lineno,47 self.filename)48 5 unmodified lines54 elif token_type is 'call':55 return self.parse_call_block()56 elif token_type is 'filter':57 return self.parse_filter_block()58+ elif token_type is 'name':59+ ext = self.extensions.get(self.stream.current.value)60+ if ext is not None:61+ return ext(self)62 lineno = self.stream.current63 expr = self.parse_tuple()64 if self.stream.current.type == 'assign':65 result = self.parse_assign(expr)14 unmodified lines80 target.set_ctx('store')81 return nodes.Assign(target, expr, lineno=lineno)82 83 def parse_statements(self, end_tokens, drop_needle=False):84+ """Parse multiple statements into a list until one of the end tokens85+ is reached. This is used to parse the body of statements as it also86+ parses template data if appropriate.87 """79- Parse multiple statements into a list until one of the end tokens80- is reached. This is used to parse the body of statements as it81- also parses template data if appropriate.82- """88 # the first token may be a colon for python compatibility89 if self.stream.current.type is 'colon':90 self.stream.next()91 1 unmodified line93 self.stream.next()94 result = self.subparse(end_tokens)95 else:96 result = []92- while self.stream.current.type not in end_tokens:97+ while not self.stream.current.test_many(end_tokens):98 if self.stream.current.type is 'block_end':99 self.stream.next()100 result.extend(self.subparse(end_tokens))101 break129 unmodified lines231 232 def parse_print(self):233 node = nodes.Output(lineno=self.stream.expect('print').lineno)234 node.nodes = []230- while self.stream.current.type not in _statement_end_tokens:235+ while self.stream.current.type not in statement_end_tokens:236 if node.nodes:237 self.stream.expect('comma')238 node.nodes.append(self.parse_expression())239 self.end_statement()240 return node241 237- def parse_trans(self):238- """Parse a translatable section."""239- # lazily imported because we don't want the i18n overhead240- # if it's not used. (Even though the overhead is low)241- from jinja2.i18n import parse_trans242- return parse_trans(self)243-242 def parse_expression(self, no_condexpr=False):243 """Parse an expression."""244 if no_condexpr:245 return self.parse_or()193 unmodified lines439 is_tuple = False440 while 1:441 if args:442 self.stream.expect('comma')445- if self.stream.current.type in _statement_end_tokens:443+ if self.stream.current.type in statement_end_tokens:444 break445 args.append(parse())446 if self.stream.current.type is not 'comma':447 break211 unmodified lines659 self.stream.next()660 elif token.type is 'variable_begin':661 self.stream.next()662 want_comma = False665- while self.stream.current.type not in _statement_end_tokens:663+ while not self.stream.current.test_many(statement_end_tokens):664 if want_comma:665 self.stream.expect('comma')666 add_data(self.parse_expression())667 want_comma = True1 unmodified line669 elif token.type is 'block_begin':670 flush_data()671 self.stream.next()672 if end_tokens is not None and \675- self.stream.current.type in end_tokens:673+ self.stream.current.test_many(end_tokens):674 return body675 while self.stream.current.type is not 'block_end':676 body.append(self.parse_statement())677 self.stream.expect('block_end')7 unmodified lines685 """Parse the whole template into a `Template` node."""686 result = nodes.Template(self.subparse(), lineno=1)687 result.set_environment(self.environment)688 return result689+690+691+class ParserExtension(tuple):692+ """Instances of this class store parser extensions."""693+ __slots__ = ()694+695+ def __new__(cls, tag, parse_func):696+ return tuple.__new__(cls, (tag, parse_func))697+698+ def __call__(self, parser):699+ return self.parse_func(parser)700+701+ def __repr__(self):702+ return '<%s %r>' % (self.__class__.__name__, self.tag)703+704+ tag = property(itemgetter(0))705+ parse_func = property(itemgetter(1))modified:jinja2/runtime.py+2 added-8 removed
106 unmodified lines107 self._name = template.name108 self._rendered_body = u''.join(gen)109 self._context = context.get_exported()110 111- def __getitem__(self, name):112- return self._context[name]111+ __getitem__ = lambda x, n: x._context[n]112+ __html__ = __unicode__ = lambda x: x._rendered_body113 114- def __unicode__(self):115- return self._rendered_body116-117- def __html__(self):118- return self._rendered_body119-114 def __repr__(self):115 return '<%s %r>' % (116 self.__class__.__name__,117 self._name209 unmodified linesmodified:jinja2/tests.py+7 added-1 removed
24 unmodified lines25 """Return true of the variable is even."""26 return value % 2 == 027 28 29+def test_divisibleby(value, num):30+ """Check if a variable is divisible by a number."""31+ return value % num == 032+33+34 def test_defined(value):35 """Return true if the variable is defined:36 37 .. sourcecode:: jinja44 unmodified lines82 object:83 84 .. sourcecode:: jinja85 81- {% if foo.attribute is sameas(false) %}86+ {% if foo.attribute is sameas false %}87 the foo attribute really is the `False` singleton88 {% endif %}89 """90 return value is other1 unmodified line92 93 TESTS = {94 'odd': test_odd,95 'even': test_even,96+ 'divisibleby': test_divisibleby,97 'defined': test_defined,98 'lower': test_lower,99 'upper': test_upper,100 'numeric': test_numeric,3 unmodified linesmodified:jinja2/utils.py+36 added-8 removed
24 unmodified lines25 )26 _simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')27 28 29-def soft_unicode(s):30- """Make a string unicode if it isn't already. That way a markup31- string is not converted back to unicode.29+def import_string(import_name, silent=False):30+ """Imports an object based on a string. This use useful if you want to31+ use import paths as endpoints or something similar. An import path can32+ be specified either in dotted notation (``xml.sax.saxutils.escape``)33+ or with a colon as object delimiter (``xml.sax.saxutils:escape``).34+35+ If the `silent` is True the return value will be `None` if the import36+ fails.37+38+ :return: imported object39 """33- if not isinstance(s, unicode):34- s = unicode(s)35- return s40+ try:41+ if ':' in import_name:42+ module, obj = import_name.split(':', 1)43+ elif '.' in import_name:44+ items = import_name.split('.')45+ module = '.'.join(items[:-1])46+ obj = items[-1]47+ else:48+ return __import__(import_name)49+ return getattr(__import__(module, None, None, [obj]), obj)50+ except (ImportError, AttributeError):51+ if not silent:52+ raise53 54 55 def pformat(obj, verbose=False):56 """Prettyprint an object. Either use the `pretty` library or the59 unmodified lines116 The `escape` function returns markup objects so that double escaping can't117 happen. If you want to use autoescaping in Jinja just set the finalizer118 of the environment to `escape`.119 """103-120 __slots__ = ()121 122 def __html__(self):123 return self28 unmodified lines152 )153 154 def join(self, seq):155 return self.__class__(unicode.join(self, imap(escape, seq)))156+ join.__doc__ = unicode.join.__doc__157 158 def split(self, *args, **kwargs):159 return map(self.__class__, unicode.split(self, *args, **kwargs))160+ split.__doc__ = unicode.split.__doc__161 162 def rsplit(self, *args, **kwargs):163 return map(self.__class__, unicode.rsplit(self, *args, **kwargs))164+ rsplit.__doc__ = unicode.rsplit.__doc__165 166 def splitlines(self, *args, **kwargs):167 return map(self.__class__, unicode.splitlines(self, *args, **kwargs))168+ splitlines.__doc__ = unicode.splitlines.__doc__169 170 def make_wrapper(name):171 orig = getattr(unicode, name)172 def func(self, *args, **kwargs):142 unmodified lines315 316 # we have to import it down here as the speedups module imports the317 # markup type which is define above.318 try:299- from jinja2._speedups import escape319+ from jinja2._speedups import escape, soft_unicode320 except ImportError:321 def escape(obj):322 """Convert the characters &, <, >, and " in string s to HTML-safe323 sequences. Use this if you need to display text that might contain6 unmodified lines330 .replace('>', '>')331 .replace('<', '<')332 .replace('"', '"')333 )334+335+ def soft_unicode(s):336+ """Make a string unicode if it isn't already. That way a markup337+ string is not converted back to unicode.338+ """339+ if not isinstance(s, unicode):340+ s = unicode(s)341+ return smodified:setup.py+6 added-2 removed
106 unmodified lines107 # jinja is egg safe. But because we distribute the documentation108 # in form of html and txt files it's a better idea to extract the files109 zip_safe=False,110 classifiers=[111- 'Development Status :: 1 - Alpha',111+ 'Development Status :: 4 Beta',112 'Environment :: Web Environment',113 'Intended Audience :: Developers',114 'License :: OSI Approved :: BSD License',115 'Operating System :: OS Independent',14 unmodified lines130 Extension('jinja2._speedups', ['jinja2/_speedups.c'])131 ]132 )133 },134- extras_require={'plugin': ['setuptools>=0.6a2']}134+ extras_require={'i18n': ['Babel>=0.8']}135+ entry_points="""136+ [babel.extractors]137+ jinja2 = jinja.i18n:babel_extract[i18n]138+ """139 )