apply pyupgrade and f-strings
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 42edc13 · Browse files · 55 files·+642 added−833 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
55 files+642 added−833 removed
- tests:+229 added−261 removed
- other:+413 added−572 removed
Provenance
- Commit
2a8515d- Tree
88c9e78- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
42edc13
55 files changed+642 added−833 removed
modified:docs/examples/cache_extension.py+1 added-1 removed
5 unmodified lines6 # a set of names that trigger the extension.7 tags = {"cache"}8 9 def __init__(self, environment):10- super(FragmentCacheExtension, self).__init__(environment)10+ super().__init__(environment)11 12 # add the defaults to the environment13 environment.extend(fragment_cache_prefix="", fragment_cache=None)14 40 unmodified linesmodified:docs/examples/inline_gettext_extension.py+1 added-2 removed
1-# -*- coding: utf-8 -*-1 import re2 3 from jinja2.exceptions import TemplateSyntaxError4 from jinja2.ext import Extension47 unmodified lines52 paren_stack = 153 else:54 if gtok == "(" or paren_stack > 1:55 yield Token(lineno, "data", gtok)57- paren_stack += gtok == ")" and -1 or 156+ paren_stack += -1 if gtok == ")" else 157 if not paren_stack:58 yield Token(lineno, "block_begin", None)59 yield Token(lineno, "name", "endtrans")60 yield Token(lineno, "block_end", None)12 unmodified linesmodified:docs/api.rst+5 added-3 removed
673 unmodified lines674 675 import re676 from jinja2 import evalcontextfilter, Markup, escape677 678- _paragraph_re = re.compile(r'(?:\r\n|\r(?!\n)|\n){2,}')678+ _paragraph_re = re.compile(r"(?:\r\n|\r(?!\n)|\n){2,}")679 680 @evalcontextfilter681 def nl2br(eval_ctx, value):682- result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n'))683- for p in _paragraph_re.split(escape(value)))682+ result = "\n\n".join(683+ f"<p>{p.replace('\n', Markup('<br>\n'))}</p>"684+ for p in _paragraph_re.split(escape(value))685+ )686 if eval_ctx.autoescape:687 result = Markup(result)688 return result689 180 unmodified linesmodified:docs/conf.py+2 added-4 removed
40 unmodified lines41 singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]}42 html_static_path = ["_static"]43 html_favicon = "_static/jinja-logo-sidebar.png"44 html_logo = "_static/jinja-logo-sidebar.png"45-html_title = "Jinja Documentation ({})".format(version)45+html_title = f"Jinja Documentation ({version})"46 html_show_sourcelink = False47 48 # LaTeX ----------------------------------------------------------------49 50-latex_documents = [51- (master_doc, "Jinja-{}.tex".format(version), html_title, author, "manual")52-]50+latex_documents = [(master_doc, f"Jinja-{version}.tex", html_title, author, "manual")]modified:examples/basic/cycle.py-2 removed
1-from __future__ import print_function2-1 from jinja2 import Environment2 3 env = Environment(4 line_statement_prefix="#", variable_start_string="${", variable_end_string="}"12 unmodified linesmodified:examples/basic/debugger.py-2 removed
1-from __future__ import print_function2-1 from jinja2 import Environment2 from jinja2.loaders import FileSystemLoader3 4 env = Environment(loader=FileSystemLoader("templates"))2 unmodified linesmodified:examples/basic/inheritance.py-2 removed
1-from __future__ import print_function2-1 from jinja2 import Environment2 from jinja2.loaders import DictLoader3 4 env = Environment(9 unmodified linesmodified:examples/basic/test_filter_and_linestatements.py-2 removed
1-from __future__ import print_function2-1 from jinja2 import Environment2 3 env = Environment(4 line_statement_prefix="%", variable_start_string="${", variable_end_string="}"23 unmodified linesmodified:examples/basic/test_loop_filter.py-2 removed
1-from __future__ import print_function2-1 from jinja2 import Environment2 3 tmpl = Environment().from_string(4 """\9 unmodified linesmodified:examples/basic/test.py+3 added-5 removed
1-from __future__ import print_function2-1 from jinja2 import Environment2 from jinja2.loaders import DictLoader3 4 env = Environment(5 loader=DictLoader(6 {9- "child.html": u"""\7+ "child.html": """\8 {% extends master_layout or 'master.html' %}9 {% include helpers = 'helpers.html' %}10 {% macro get_the_answer() %}42{% endmacro %}11 {% title = 'Hello World' %}1 unmodified line13 {{ get_the_answer() }}14 {{ helpers.conspirate() }}15 {% endblock %}16 """,19- "master.html": u"""\17+ "master.html": """\18 <!doctype html>19 <title>{{ title }}</title>20 {% block body %}{% endblock %}21 """,24- "helpers.html": u"""\22+ "helpers.html": """\23 {% macro conspirate() %}23{% endmacro %}24 """,25 }26 )3 unmodified linesmodified:examples/basic/translate.py+1 added-3 removed
1-from __future__ import print_function2-1 from jinja2 import Environment2 3 env = Environment(extensions=["jinja2.ext.i18n"])4 env.globals["gettext"] = {"Hello %(user)s!": "Hallo %(user)s!"}.__getitem__5 env.globals["ngettext"] = lambda s, p, n: {6 "%(count)s user": "%(count)d Benutzer",7 "%(count)s users": "%(count)d Benutzer",10-}[n == 1 and s or p]8+}[s if n == 1 else p]9 print(10 env.from_string(11 """\12 {% trans %}Hello {{ user }}!{% endtrans %}6 unmodified linesmodified:scripts/generate_identifier_pattern.py+2 added-6 removed
1-#!/usr/bin/env python31 import itertools2 import os3 import re4 import sys5 7-if sys.version_info[0] < 3:8- raise RuntimeError("This needs to run on Python 3.")6 10-7 def get_characters():8 """Find every Unicode character that is valid in a Python `identifier`_ but9 is not matched by the regex ``\\w`` group.10 36 unmodified lines47 elif ord(b) - ord(a) == 1: # two chars, range is redundant48 out.append(a)49 out.append(b)50 else:55- out.append("{}-{}".format(a, b))51+ out.append(f"{a}-{b}")52 53 return "".join(out)54 55 9 unmodified lines65 with open(filename, "w", encoding="utf8") as f:66 f.write("import re\n\n")67 f.write("# generated by scripts/generate_identifier_pattern.py\n")68 f.write("pattern = re.compile(\n")73- f.write(' r"[\\w{}]+" # noqa: B950\n'.format(pattern))69+ f.write(f' r"[\\w{pattern}]+" # noqa: B950\n')70 f.write(")\n")71 72 73 if __name__ == "__main__":1 unmodified linemodified:src/jinja2/asyncfilters.py+1 added-1 removed
82 unmodified lines83 ]84 85 86 @asyncfiltervariant(filters.do_join)87-async def do_join(eval_ctx, value, d=u"", attribute=None):87+async def do_join(eval_ctx, value, d="", attribute=None):88 return filters.do_join(eval_ctx, await auto_to_seq(value), d, attribute)89 90 91 @asyncfiltervariant(filters.do_list)66 unmodified linesmodified:src/jinja2/asyncsupport.py-1 removed
1-# -*- coding: utf-8 -*-1 """The code for async support. Importing this patches Jinja."""2 import asyncio3 import inspect4 from functools import update_wrapper245 unmodified linesmodified:src/jinja2/bccache.py+5 added-6 removed
1-# -*- coding: utf-8 -*-1 """The optional bytecode cache system. This is useful if you have very2 complex template situations and the compilation of all those templates3 slows down your application too much.4 23 unmodified lines28 + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1], 2)29 )30 31 33-class Bucket(object):32+class Bucket:33 """Buckets are used to store the bytecode for one template. It's created34 and initialized by the bytecode cache and passed to the loading functions.35 36 The buckets get an internal checksum from the cache assigned and use this48 unmodified lines85 self.write_bytecode(out)86 return out.getvalue()87 88 90-class BytecodeCache(object):89+class BytecodeCache:90 """To implement your own bytecode cache you have to subclass this class91 and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of92 these methods are passed a :class:`~jinja2.bccache.Bucket`.93 109 unmodified lines203 return tmpdir204 if not hasattr(os, "getuid"):205 _unsafe_dir()206 208- dirname = "_jinja2-cache-%d" % os.getuid()207+ dirname = f"_jinja2-cache-{os.getuid()}"208 actual_dir = os.path.join(tmpdir, dirname)209 210 try:211 os.mkdir(actual_dir, stat.S_IRWXU)23 unmodified lines235 236 return actual_dir237 238 def _get_cache_filename(self, bucket):240- return os.path.join(self.directory, self.pattern % bucket.key)239+ return os.path.join(self.directory, self.pattern % (bucket.key,))240 241 def load_bytecode(self, bucket):242 f = open_if_exists(self._get_cache_filename(bucket), "rb")243 if f is not None:14 unmodified lines258 # write access on the file system and the function does not exist259 # normally.260 from os import remove261 263- files = fnmatch.filter(os.listdir(self.directory), self.pattern % "*")262+ files = fnmatch.filter(os.listdir(self.directory), self.pattern % ("*",))263 for filename in files:264 try:265 remove(os.path.join(self.directory, filename))266 except OSError:79 unmodified linesmodified:src/jinja2/compiler.py+146 added-190 removed
1-# -*- coding: utf-8 -*-1 """Compiles nodes from the parser into Python code."""2 from collections import namedtuple3 from functools import update_wrapper4 from io import StringIO82 unmodified lines87 pass88 return visitor.undeclared89 90 92-class MacroRef(object):91+class MacroRef:92 def __init__(self, node):93 self.node = node94 self.accesses_caller = False95 self.accesses_kwargs = False96 self.accesses_varargs = False97 98 100-class Frame(object):99+class Frame:100 """Holds compile time information for us."""101 102 def __init__(self, eval_ctx, parent=None, level=None):103 self.eval_ctx = eval_ctx105- self.symbols = Symbols(parent and parent.symbols or None, level=level)104+ self.symbols = Symbols(parent.symbols if parent else None, level=level)105 106 # a toplevel frame is the root + soft frames such as if conditions.107 self.toplevel = False108 12 unmodified lines121 # buffer.122 self.buffer = None123 124 # the name of the block we're in, otherwise None.126- self.block = parent and parent.block or None125+ self.block = parent.block if parent else None126 127 # the parent of this frame128 self.parent = parent129 154 unmodified lines284 285 def temporary_identifier(self):286 """Get a new unique identifier."""287 self._last_identifier += 1289- return "t_%d" % self._last_identifier288+ return f"t_{self._last_identifier}"289 290 def buffer(self, frame):291 """Enable buffering for the frame from that point onwards."""292 frame.buffer = self.temporary_identifier()294- self.writeline("%s = []" % frame.buffer)293+ self.writeline(f"{frame.buffer} = []")294 295 def return_buffer_contents(self, frame, force_unescaped=False):296 """Return the buffer contents of the frame."""297 if not force_unescaped:298 if frame.eval_ctx.volatile:299 self.writeline("if context.eval_ctx.autoescape:")300 self.indent()302- self.writeline("return Markup(concat(%s))" % frame.buffer)301+ self.writeline(f"return Markup(concat({frame.buffer}))")302 self.outdent()303 self.writeline("else:")304 self.indent()306- self.writeline("return concat(%s)" % frame.buffer)305+ self.writeline(f"return concat({frame.buffer})")306 self.outdent()307 return308 elif frame.eval_ctx.autoescape:310- self.writeline("return Markup(concat(%s))" % frame.buffer)309+ self.writeline(f"return Markup(concat({frame.buffer}))")310 return312- self.writeline("return concat(%s)" % frame.buffer)311+ self.writeline(f"return concat({frame.buffer})")312 313 def indent(self):314 """Indent by one."""315 self._indentation += 16 unmodified lines322 """Yield or write into the frame buffer."""323 if frame.buffer is None:324 self.writeline("yield ", node)325 else:327- self.writeline("%s.append(" % frame.buffer, node)326+ self.writeline(f"{frame.buffer}.append(", node)327 328 def end_write(self, frame):329 """End the writing process started by `start_write`."""330 if frame.buffer is not None:66 unmodified lines397 self.write(", ")398 self.visit(kwarg, frame)399 if extra_kwargs is not None:400 for key, value in extra_kwargs.items():402- self.write(", %s=%s" % (key, value))401+ self.write(f", {key}={value}")402 if node.dyn_args:403 self.write(", *")404 self.visit(node.dyn_args, frame)405 2 unmodified lines408 self.write(", **dict({")409 else:410 self.write(", **{")411 for kwarg in node.kwargs:413- self.write("%r: " % kwarg.key)412+ self.write(f"{kwarg.key!r}: ")413 self.visit(kwarg.value, frame)414 self.write(", ")415 if extra_kwargs is not None:416 for key, value in extra_kwargs.items():418- self.write("%r: %s, " % (key, value))417+ self.write(f"{key!r}: {value}, ")418 if node.dyn_kwargs is not None:419 self.write("}, **")420 self.visit(node.dyn_kwargs, frame)421 self.write(")")13 unmodified lines435 mapping = getattr(self, dependency)436 for name in getattr(visitor, dependency):437 if name not in mapping:438 mapping[name] = self.temporary_identifier()440- self.writeline(441- "%s = environment.%s[%r]" % (mapping[name], dependency, name)442- )439+ self.writeline(f"{mapping[name]} = environment.{dependency}[{name!r}]")440 441 def enter_frame(self, frame):442 undefs = []443 for target, (action, param) in frame.symbols.loads.items():444 if action == VAR_LOAD_PARAMETER:445 pass446 elif action == VAR_LOAD_RESOLVE:450- self.writeline("%s = %s(%r)" % (target, self.get_resolve_func(), param))447+ self.writeline(f"{target} = {self.get_resolve_func()}({param!r})")448 elif action == VAR_LOAD_ALIAS:452- self.writeline("%s = %s" % (target, param))449+ self.writeline(f"{target} = {param}")450 elif action == VAR_LOAD_UNDEFINED:451 undefs.append(target)452 else:453 raise NotImplementedError("unknown load instruction")454 if undefs:458- self.writeline("%s = missing" % " = ".join(undefs))455+ self.writeline(f"{' = '.join(undefs)} = missing")456 457 def leave_frame(self, frame, with_python_scope=False):458 if not with_python_scope:459 undefs = []460 for target in frame.symbols.loads:461 undefs.append(target)462 if undefs:466- self.writeline("%s = missing" % " = ".join(undefs))463+ self.writeline(f"{' = '.join(undefs)} = missing")464 465 def func(self, name):466 if self.environment.is_async:470- return "async def %s" % name471- return "def %s" % name467+ return f"async def {name}"468+ return f"def {name}"469 470 def macro_body(self, node, frame):471 """Dump the function def of a macro or call block."""472 frame = frame.inner()41 unmodified lines514 515 # macros are delayed, they never require output checks516 frame.require_output_check = False517 frame.symbols.analyze_node(node)521- self.writeline("%s(%s):" % (self.func("macro"), ", ".join(args)), node)518+ self.writeline(f"{self.func('macro')}({', '.join(args)}):", node)519 self.indent()520 521 self.buffer(frame)522 self.enter_frame(frame)523 524 self.push_parameter_definitions(frame)525 for idx, arg in enumerate(node.args):526 ref = frame.symbols.ref(arg.name)530- self.writeline("if %s is missing:" % ref)527+ self.writeline(f"if {ref} is missing:")528 self.indent()529 try:530 default = node.defaults[idx - len(node.args)]531 except IndexError:532 self.writeline(536- "%s = undefined(%r, name=%r)"537- % (ref, "parameter %r was not provided" % arg.name, arg.name)533+ f'{ref} = undefined("parameter {arg.name!r} was not provided",'534+ f" name={arg.name!r})"535 )536 else:540- self.writeline("%s = " % ref)537+ self.writeline(f"{ref} = ")538 self.visit(default, frame)539 self.mark_parameter_stored(ref)540 self.outdent()541 self.pop_parameter_definitions()11 unmodified lines553 name = getattr(macro_ref.node, "name", None)554 if len(macro_ref.node.args) == 1:555 arg_tuple += ","556 self.write(560- "Macro(environment, macro, %r, (%s), %r, %r, %r, "561- "context.eval_ctx.autoescape)"562- % (563- name,564- arg_tuple,565- macro_ref.accesses_kwargs,566- macro_ref.accesses_varargs,567- macro_ref.accesses_caller,568- )557+ f"Macro(environment, macro, {name!r}, ({arg_tuple}),"558+ f" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r},"559+ f" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)"560 )561 562 def position(self, node):563 """Return a human readable position for the node."""573- rv = "line %d" % node.lineno564+ rv = f"line {node.lineno}"565 if self.name is not None:575- rv += " in " + repr(self.name)566+ rv = f"{rv} in {self.name!r}"567 return rv568 569 def dump_local_context(self, frame):579- return "{%s}" % ", ".join(580- "%r: %s" % (name, target)570+ items_kv = ", ".join(571+ f"{name!r}: {target}"572 for name, target in frame.symbols.dump_stores().items()573 )574+ return f"{{{items_kv}}}"575 576 def write_commons(self):577 """Writes a common preamble that is used by root and block functions.578 Primarily this sets up common local helpers and enforces a generator38 unmodified lines617 def get_resolve_func(self):618 target = self._context_reference_stack[-1]619 if target == "context":620 return "resolve"629- return "%s.resolve" % target621+ return f"{target}.resolve"622 623 def derive_context(self, frame):632- return "%s.derived(%s)" % (633- self.get_context_ref(),634- self.dump_local_context(frame),635- )624+ return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})"625 626 def parameter_is_undeclared(self, target):627 """Checks if a given target is an undeclared parameter."""628 if not self._param_def_block:14 unmodified lines643 public_names = [x for x in vars if x[:1] != "_"]644 if len(vars) == 1:645 name = next(iter(vars))646 ref = frame.symbols.ref(name)658- self.writeline("context.vars[%r] = %s" % (name, ref))647+ self.writeline(f"context.vars[{name!r}] = {ref}")648 else:649 self.writeline("context.vars.update({")650 for idx, name in enumerate(vars):651 if idx:652 self.write(", ")653 ref = frame.symbols.ref(name)665- self.write("%r: %s" % (name, ref))654+ self.write(f"{name!r}: {ref}")655 self.write("})")656 if public_names:657 if len(public_names) == 1:669- self.writeline("context.exported_vars.add(%r)" % public_names[0])658+ self.writeline(f"context.exported_vars.add({public_names[0]!r})")659 else:671- self.writeline(672- "context.exported_vars.update((%s))"673- % ", ".join(map(repr, public_names))674- )660+ names_str = ", ".join(map(repr, public_names))661+ self.writeline(f"context.exported_vars.update(({names_str}))")662 663 # -- Statement Visitors664 665 def visit_Template(self, node, frame=None):12 unmodified lines678 )679 680 # if we want a deferred initialization we cannot move the681 # environment into a local name695- envenv = not self.defer_init and ", environment=environment" or ""682+ envenv = "" if self.defer_init else ", environment=environment"683 684 # do we have an extends tag at all? If not, we can save some685 # overhead by just not processing any inheritance code.686 have_extends = node.find(nodes.Extends) is not None687 688 # find all blocks689 for block in node.find_all(nodes.Block):690 if block.name in self.blocks:704- self.fail("block %r defined twice" % block.name, block.lineno)691+ self.fail(f"block {block.name!r} defined twice", block.lineno)692 self.blocks[block.name] = block693 694 # find all imports and import them695 for import_ in node.find_all(nodes.ImportedName):1 unmodified line697 imp = import_.importname698 self.import_aliases[imp] = alias = self.temporary_identifier()699 if "." in imp:700 module, obj = imp.rsplit(".", 1)714- self.writeline("from %s import %s as %s" % (module, obj, alias))701+ self.writeline(f"from {module} import {obj} as {alias}")702 else:716- self.writeline("import %s as %s" % (imp, alias))703+ self.writeline(f"import {imp} as {alias}")704 705 # add the load name719- self.writeline("name = %r" % self.name)706+ self.writeline(f"name = {self.name!r}")707 708 # generate the root render function.709 self.writeline(723- "%s(context, missing=missing%s):" % (self.func("root"), envenv), extra=1710+ f"{self.func('root')}(context, missing=missing{envenv}):", extra=1711 )712 self.indent()713 self.write_commons()714 715 # process the root716 frame = Frame(eval_ctx)717 if "self" in find_undeclared(node.body, ("self",)):718 ref = frame.symbols.declare_parameter("self")732- self.writeline("%s = TemplateReference(context)" % ref)719+ self.writeline(f"{ref} = TemplateReference(context)")720 frame.symbols.analyze_node(node)721 frame.toplevel = frame.rootlevel = True722 frame.require_output_check = have_extends and not self.has_known_extends723 if have_extends:12 unmodified lines736 self.indent()737 if not self.environment.is_async:738 self.writeline("yield from parent_template.root_render_func(context)")739 else:740+ loop = "async for" if self.environment.is_async else "for"741 self.writeline(754- "%sfor event in parent_template."755- "root_render_func(context):"756- % (self.environment.is_async and "async " or "")742+ f"{loop} event in parent_template.root_render_func(context):"743 )744 self.indent()745 self.writeline("yield event")746 self.outdent()1 unmodified line748 749 # at this point we now have the blocks collected and can visit them too.750 for name, block in self.blocks.items():751 self.writeline(766- "%s(context, missing=missing%s):"767- % (self.func("block_" + name), envenv),752+ f"{self.func('block_' + name)}(context, missing=missing{envenv}):",753 block,754 1,755 )756 self.indent()4 unmodified lines761 block_frame = Frame(eval_ctx)762 undeclared = find_undeclared(block.body, ("self", "super"))763 if "self" in undeclared:764 ref = block_frame.symbols.declare_parameter("self")780- self.writeline("%s = TemplateReference(context)" % ref)765+ self.writeline(f"{ref} = TemplateReference(context)")766 if "super" in undeclared:767 ref = block_frame.symbols.declare_parameter("super")783- self.writeline("%s = context.super(%r, block_%s)" % (ref, name, name))768+ self.writeline(f"{ref} = context.super({name!r}, block_{name})")769 block_frame.symbols.analyze_node(block)770 block_frame.block = name771 self.enter_frame(block_frame)772 self.pull_dependencies(block.body)773 self.blockvisit(block.body, block_frame)774 self.leave_frame(block_frame, with_python_scope=True)775 self.outdent()776 792- self.writeline(793- "blocks = {%s}" % ", ".join("%r: block_%s" % (x, x) for x in self.blocks),794- extra=1,795- )777+ blocks_kv_str = ", ".join(f"{x!r}: block_{x}" for x in self.blocks)778+ self.writeline(f"blocks = {{{blocks_kv_str}}}", extra=1)779+ debug_kv_str = "&".join(f"{k}={v}" for k, v in self.debug_info)780+ self.writeline(f"debug_info = {debug_kv_str!r}")781 797- # add a function that returns the debug info798- self.writeline(799- "debug_info = %r" % "&".join("%s=%s" % x for x in self.debug_info)800- )801-782 def visit_Block(self, node, frame):783 """Call a block and register it for the template."""784 level = 0785 if frame.toplevel:12 unmodified lines798 context = self.get_context_ref()799 800 if not self.environment.is_async and frame.buffer is None:801 self.writeline(822- "yield from context.blocks[%r][0](%s)" % (node.name, context), node802+ f"yield from context.blocks[{node.name!r}][0]({context})", node803 )804 else:825- loop = self.environment.is_async and "async for" or "for"805+ loop = "async for" if self.environment.is_async else "for"806 self.writeline(827- "%s event in context.blocks[%r][0](%s):" % (loop, node.name, context),828- node,807+ f"{loop} event in context.blocks[{node.name!r}][0]({context}):", node808 )809 self.indent()810 self.simple_write("event", frame)811 self.outdent()16 unmodified lines828 # same error at different times just "because we can".829 if not self.has_known_extends:830 self.writeline("if parent_template is not None:")831 self.indent()853- self.writeline("raise TemplateRuntimeError(%r)" % "extended multiple times")832+ self.writeline('raise TemplateRuntimeError("extended multiple times")')833 834 # if we have a known extends already we don't need that code here835 # as we know that the template execution will end here.836 if self.has_known_extends:2 unmodified lines839 self.outdent()840 841 self.writeline("parent_template = environment.get_template(", node)842 self.visit(node.template, frame)864- self.write(", %r)" % self.name)843+ self.write(f", {self.name!r})")844 self.writeline("for name, parent_block in parent_template.blocks.items():")845 self.indent()846 self.writeline("context.blocks.setdefault(name, []).append(parent_block)")847 self.outdent()21 unmodified lines869 func_name = "select_template"870 elif isinstance(node.template, (nodes.Tuple, nodes.List)):871 func_name = "select_template"872 894- self.writeline("template = environment.%s(" % func_name, node)873+ self.writeline(f"template = environment.{func_name}(", node)874 self.visit(node.template, frame)896- self.write(", %r)" % self.name)875+ self.write(f", {self.name!r})")876 if node.ignore_missing:877 self.outdent()878 self.writeline("except TemplateNotFound:")879 self.indent()3 unmodified lines883 self.indent()884 885 skip_event_yield = False886 if node.with_context:908- loop = self.environment.is_async and "async for" or "for"887+ loop = "async for" if self.environment.is_async else "for"888 self.writeline(910- "%s event in template.root_render_func("911- "template.new_context(context.get_all(), True, "912- "%s)):" % (loop, self.dump_local_context(frame))889+ f"{loop} event in template.root_render_func("890+ "template.new_context(context.get_all(), True,"891+ f" {self.dump_local_context(frame)})):"892 )893 elif self.environment.is_async:894 self.writeline(916- "for event in (await "917- "template._get_default_module_async())"895+ "for event in (await template._get_default_module_async())"896 "._body_stream:"897 )898 else:899 self.writeline("yield from template._get_default_module()._body_stream")8 unmodified lines908 self.outdent()909 910 def visit_Import(self, node, frame):911 """Visit regular imports."""934- self.writeline("%s = " % frame.symbols.ref(node.target), node)912+ self.writeline(f"{frame.symbols.ref(node.target)} = ", node)913 if frame.toplevel:936- self.write("context.vars[%r] = " % node.target)914+ self.write(f"context.vars[{node.target!r}] = ")915 if self.environment.is_async:916 self.write("await ")917 self.write("environment.get_template(")918 self.visit(node.template, frame)941- self.write(", %r)." % self.name)919+ self.write(f", {self.name!r}).")920 if node.with_context:921+ func = "make_module" + ("_async" if self.environment.is_async else "")922 self.write(944- "make_module%s(context.get_all(), True, %s)"945- % (946- self.environment.is_async and "_async" or "",947- self.dump_local_context(frame),948- )923+ f"{func}(context.get_all(), True, {self.dump_local_context(frame)})"924 )925 elif self.environment.is_async:926 self.write("_get_default_module_async()")927 else:928 self.write("_get_default_module()")929 if frame.toplevel and not node.target.startswith("_"):955- self.writeline("context.exported_vars.discard(%r)" % node.target)930+ self.writeline(f"context.exported_vars.discard({node.target!r})")931 932 def visit_FromImport(self, node, frame):933 """Visit named imports."""934 self.newline(node)960- self.write(961- "included_template = %senvironment.get_template("962- % (self.environment.is_async and "await " or "")963- )935+ prefix = "await " if self.environment.is_async else ""936+ self.write(f"included_template = {prefix}environment.get_template(")937 self.visit(node.template, frame)965- self.write(", %r)." % self.name)938+ self.write(f", {self.name!r}).")939 if node.with_context:940+ func = "make_module" + ("_async" if self.environment.is_async else "")941 self.write(968- "make_module%s(context.get_all(), True, %s)"969- % (970- self.environment.is_async and "_async" or "",971- self.dump_local_context(frame),972- )942+ f"{func}(context.get_all(), True, {self.dump_local_context(frame)})"943 )944 elif self.environment.is_async:945 self.write("_get_default_module_async()")946 else:6 unmodified lines953 name, alias = name954 else:955 alias = name956 self.writeline(987- "%s = getattr(included_template, "988- "%r, missing)" % (frame.symbols.ref(alias), name)957+ f"{frame.symbols.ref(alias)} ="958+ f" getattr(included_template, {name!r}, missing)"959 )990- self.writeline("if %s is missing:" % frame.symbols.ref(alias))960+ self.writeline(f"if {frame.symbols.ref(alias)} is missing:")961 self.indent()962+ message = (963+ "the template {included_template.__name__!r}"964+ f" (imported on {self.position(node)})"965+ f" does not export the requested name {name!r}"966+ )967 self.writeline(993- "%s = undefined(%r %% "994- "included_template.__name__, "995- "name=%r)"996- % (997- frame.symbols.ref(alias),998- "the template %%r (imported on %s) does "999- "not export the requested name %s"1000- % (self.position(node), repr(name)),1001- name,1002- )968+ f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})"969 )970 self.outdent()971 if frame.toplevel:972 var_names.append(alias)2 unmodified lines975 976 if var_names:977 if len(var_names) == 1:978 name = var_names[0]1013- self.writeline(1014- "context.vars[%r] = %s" % (name, frame.symbols.ref(name))1015- )979+ self.writeline(f"context.vars[{name!r}] = {frame.symbols.ref(name)}")980 else:1017- self.writeline(1018- "context.vars.update({%s})"1019- % ", ".join(1020- "%r: %s" % (name, frame.symbols.ref(name)) for name in var_names1021- )981+ names_kv = ", ".join(982+ f"{name!r}: {frame.symbols.ref(name)}" for name in var_names983 )984+ self.writeline(f"context.vars.update({{{names_kv}}})")985 if discarded_names:986 if len(discarded_names) == 1:1025- self.writeline("context.exported_vars.discard(%r)" % discarded_names[0])987+ self.writeline(f"context.exported_vars.discard({discarded_names[0]!r})")988 else:989+ names_str = ", ".join(map(repr, discarded_names))990 self.writeline(1028- "context.exported_vars.difference_"1029- "update((%s))" % ", ".join(map(repr, discarded_names))991+ f"context.exported_vars.difference_update(({names_str}))"992 )993 994 def visit_For(self, node, frame):995 loop_frame = frame.inner()17 unmodified lines1013 1014 if node.test:1015 loop_filter_func = self.temporary_identifier()1016 test_frame.symbols.analyze_node(node, for_branch="test")1055- self.writeline("%s(fiter):" % self.func(loop_filter_func), node.test)1017+ self.writeline(f"{self.func(loop_filter_func)}(fiter):", node.test)1018 self.indent()1019 self.enter_frame(test_frame)1058- self.writeline(self.environment.is_async and "async for " or "for ")1020+ self.writeline("async for " if self.environment.is_async else "for ")1021 self.visit(node.target, loop_frame)1022 self.write(" in ")1061- self.write(self.environment.is_async and "auto_aiter(fiter)" or "fiter")1023+ self.write("auto_aiter(fiter)" if self.environment.is_async else "fiter")1024 self.write(":")1025 self.indent()1026 self.writeline("if ", node.test)1027 self.visit(node.test, test_frame)8 unmodified lines1036 # variables at that point. Because loops can be nested but the loop1037 # variable is a special one we have to enforce aliasing for it.1038 if node.recursive:1039 self.writeline(1078- "%s(reciter, loop_render_func, depth=0):" % self.func("loop"), node1040+ f"{self.func('loop')}(reciter, loop_render_func, depth=0):", node1041 )1042 self.indent()1043 self.buffer(loop_frame)1044 2 unmodified lines1047 1048 # make sure the loop variable is a special one and raise a template1049 # assertion error if a loop tries to write to loop1050 if extended_loop:1089- self.writeline("%s = missing" % loop_ref)1051+ self.writeline(f"{loop_ref} = missing")1052 1053 for name in node.find_all(nodes.Name):1054 if name.ctx == "store" and name.name == "loop":1055 self.fail(2 unmodified lines1058 )1059 1060 if node.else_:1061 iteration_indicator = self.temporary_identifier()1100- self.writeline("%s = 1" % iteration_indicator)1062+ self.writeline(f"{iteration_indicator} = 1")1063 1102- self.writeline(self.environment.is_async and "async for " or "for ", node)1064+ self.writeline("async for " if self.environment.is_async else "for ", node)1065 self.visit(node.target, loop_frame)1066 if extended_loop:1105- if self.environment.is_async:1106- self.write(", %s in AsyncLoopContext(" % loop_ref)1107- else:1108- self.write(", %s in LoopContext(" % loop_ref)1067+ prefix = "Async" if self.environment.is_async else ""1068+ self.write(f", {loop_ref} in {prefix}LoopContext(")1069 else:1070 self.write(" in ")1071 1072 if node.test:1113- self.write("%s(" % loop_filter_func)1073+ self.write(f"{loop_filter_func}(")1074 if node.recursive:1075 self.write("reciter")1076 else:1077 if self.environment.is_async and not extended_loop:6 unmodified lines1084 1085 if node.recursive:1086 self.write(", undefined, loop_render_func, depth):")1087 else:1128- self.write(extended_loop and ", undefined):" or ":")1088+ self.write(", undefined):" if extended_loop else ":")1089 1090 self.indent()1091 self.enter_frame(loop_frame)1092 1093 self.blockvisit(node.body, loop_frame)1094 if node.else_:1135- self.writeline("%s = 0" % iteration_indicator)1095+ self.writeline(f"{iteration_indicator} = 0")1096 self.outdent()1097 self.leave_frame(1098 loop_frame, with_python_scope=node.recursive and not node.else_1099 )1100 1101 if node.else_:1142- self.writeline("if %s:" % iteration_indicator)1102+ self.writeline(f"if {iteration_indicator}:")1103 self.indent()1104 self.enter_frame(else_frame)1105 self.blockvisit(node.else_, else_frame)1106 self.leave_frame(else_frame)41 unmodified lines1148 macro_frame, macro_ref = self.macro_body(node, frame)1149 self.newline()1150 if frame.toplevel:1151 if not node.name.startswith("_"):1192- self.write("context.exported_vars.add(%r)" % node.name)1193- self.writeline("context.vars[%r] = " % node.name)1194- self.write("%s = " % frame.symbols.ref(node.name))1152+ self.write(f"context.exported_vars.add({node.name!r})")1153+ self.writeline(f"context.vars[{node.name!r}] = ")1154+ self.write(f"{frame.symbols.ref(node.name)} = ")1155 self.macro_def(macro_ref, macro_frame)1156 1157 def visit_CallBlock(self, node, frame):1158 call_frame, macro_ref = self.macro_body(node, frame)169 unmodified lines1328 body.append([const])1329 1330 if frame.buffer is not None:1331 if len(body) == 1:1372- self.writeline("%s.append(" % frame.buffer)1332+ self.writeline(f"{frame.buffer}.append(")1333 else:1374- self.writeline("%s.extend((" % frame.buffer)1334+ self.writeline(f"{frame.buffer}.extend((")1335 1336 self.indent()1337 1338 for item in body:50 unmodified lines1389 self.write(" = (Markup if context.eval_ctx.autoescape else identity)(")1390 if node.filter is not None:1391 self.visit_Filter(node.filter, block_frame)1392 else:1433- self.write("concat(%s)" % block_frame.buffer)1393+ self.write(f"concat({block_frame.buffer})")1394 self.write(")")1395 self.pop_assign_tracking(frame)1396 self.leave_frame(block_frame)1397 15 unmodified lines1413 and load[0] == VAR_LOAD_PARAMETER1414 and not self.parameter_is_undeclared(ref)1415 ):1416 self.write(1457- "(undefined(name=%r) if %s is missing else %s)"1458- % (node.name, ref, ref)1417+ f"(undefined(name={node.name!r}) if {ref} is missing else {ref})"1418 )1419 return1420 1421 self.write(ref)2 unmodified lines1424 # NSRefs can only be used to store values; since they use the normal1425 # `foo.bar` notation they will be parsed as a normal attribute access1426 # when used anywhere but in a `set` context1427 ref = frame.symbols.ref(node.name)1469- self.writeline("if not isinstance(%s, Namespace):" % ref)1428+ self.writeline(f"if not isinstance({ref}, Namespace):")1429 self.indent()1430 self.writeline(1472- "raise TemplateRuntimeError(%r)"1473- % "cannot assign attribute on non-namespace object"1431+ "raise TemplateRuntimeError"1432+ '("cannot assign attribute on non-namespace object")'1433 )1434 self.outdent()1476- self.writeline("%s[%r]" % (ref, node.attr))1435+ self.writeline(f"{ref}[{node.attr!r}]")1436 1437 def visit_Const(self, node, frame):1438 val = node.as_const(frame.eval_ctx)1439 if isinstance(val, float):5 unmodified lines1445 try:1446 self.write(repr(node.as_const(frame.eval_ctx)))1447 except nodes.Impossible:1448 self.write(1490- "(Markup if context.eval_ctx.autoescape else identity)(%r)" % node.data1449+ f"(Markup if context.eval_ctx.autoescape else identity)({node.data!r})"1450 )1451 1452 def visit_Tuple(self, node, frame):1453 self.write("(")1 unmodified line1455 for idx, item in enumerate(node.items):1456 if idx:1457 self.write(", ")1458 self.visit(item, frame)1500- self.write(idx == 0 and ",)" or ")")1459+ self.write(",)" if idx == 0 else ")")1460 1461 def visit_List(self, node, frame):1462 self.write("[")1463 for idx, item in enumerate(node.items):18 unmodified lines1482 if (1483 self.environment.sandboxed1484 and operator in self.environment.intercepted_binops1485 ):1527- self.write("environment.call_binop(context, %r, " % operator)1486+ self.write(f"environment.call_binop(context, {operator!r}, ")1487 self.visit(node.left, frame)1488 self.write(", ")1489 self.visit(node.right, frame)1490 else:1491 self.write("(")1492 self.visit(node.left, frame)1534- self.write(" %s " % operator)1493+ self.write(f" {operator} ")1494 self.visit(node.right, frame)1495 self.write(")")1496 1497 return visitor4 unmodified lines1502 if (1503 self.environment.sandboxed1504 and operator in self.environment.intercepted_unops1505 ):1547- self.write("environment.call_unop(context, %r, " % operator)1506+ self.write(f"environment.call_unop(context, {operator!r}, ")1507 self.visit(node.node, frame)1508 else:1509 self.write("(" + operator)1510 self.visit(node.node, frame)17 unmodified lines1528 1529 @optimizeconst1530 def visit_Concat(self, node, frame):1531 if frame.eval_ctx.volatile:1573- func_name = "(context.eval_ctx.volatile and markup_join or str_join)"1532+ func_name = "(markup_join if context.eval_ctx.volatile else str_join)"1533 elif frame.eval_ctx.autoescape:1534 func_name = "markup_join"1535 else:1536 func_name = "str_join"1578- self.write("%s((" % func_name)1537+ self.write(f"{func_name}((")1538 for arg in node.nodes:1539 self.visit(arg, frame)1540 self.write(", ")1541 self.write("))")6 unmodified lines1548 self.visit(op, frame)1549 self.write(")")1550 1551 def visit_Operand(self, node, frame):1593- self.write(" %s " % operators[node.op])1552+ self.write(f" {operators[node.op]} ")1553 self.visit(node.expr, frame)1554 1555 @optimizeconst1556 def visit_Getattr(self, node, frame):1 unmodified line1558 self.write("(await auto_await(")1559 1560 self.write("environment.getattr(")1561 self.visit(node.node, frame)1603- self.write(", %r)" % node.attr)1562+ self.write(f", {node.attr!r})")1563 1564 if self.environment.is_async:1565 self.write("))")1566 34 unmodified lines1601 self.write("await auto_await(")1602 self.write(self.filters[node.name] + "(")1603 func = self.environment.filters.get(node.name)1604 if func is None:1646- self.fail("no filter named %r" % node.name, node.lineno)1605+ self.fail(f"no filter named {node.name!r}", node.lineno)1606 if getattr(func, "contextfilter", False) is True:1607 self.write("context, ")1608 elif getattr(func, "evalcontextfilter", False) is True:1609 self.write("context.eval_ctx, ")5 unmodified lines1615 if node.node is not None:1616 self.visit(node.node, frame)1617 elif frame.eval_ctx.volatile:1618 self.write(1660- "(context.eval_ctx.autoescape and"1661- " Markup(concat(%s)) or concat(%s))" % (frame.buffer, frame.buffer)1619+ f"(Markup(concat({frame.buffer}))"1620+ f" if context.eval_ctx.autoescape else concat({frame.buffer}))"1621 )1622 elif frame.eval_ctx.autoescape:1664- self.write("Markup(concat(%s))" % frame.buffer)1623+ self.write(f"Markup(concat({frame.buffer}))")1624 else:1666- self.write("concat(%s)" % frame.buffer)1625+ self.write(f"concat({frame.buffer})")1626 self.signature(node, frame)1627 self.write(")")1628 if self.environment.is_async:1629 self.write(")")1 unmodified line1631 @optimizeconst1632 def visit_Test(self, node, frame):1633 self.write(self.tests[node.name] + "(")1634 if node.name not in self.environment.tests:1676- self.fail("no test named %r" % node.name, node.lineno)1635+ self.fail(f"no test named {node.name!r}", node.lineno)1636 self.visit(node.node, frame)1637 self.signature(node, frame)1638 self.write(")")1639 2 unmodified lines1642 def write_expr2():1643 if node.expr2 is not None:1644 return self.visit(node.expr2, frame)1645 self.write(1687- "cond_expr_undefined(%r)"1688- % (1689- "the inline if-"1690- "expression on %s evaluated to false and "1691- "no else section was defined." % self.position(node)1692- )1646+ f'cond_expr_undefined("the inline if-expression on'1647+ f" {self.position(node)} evaluated to false and no else"1648+ f' section was defined.")'1649 )1650 1651 self.write("(")1652 self.visit(node.expr1, frame)11 unmodified lines1664 self.write("environment.call(context, ")1665 else:1666 self.write("context.call(")1667 self.visit(node.node, frame)1712- extra_kwargs = forward_caller and {"caller": "caller"} or None1668+ extra_kwargs = {"caller": "caller"} if forward_caller else None1669 self.signature(node, frame, extra_kwargs)1670 self.write(")")1671 if self.environment.is_async:1672 self.write(")")9 unmodified lines1682 self.visit(node.expr, frame)1683 self.write(")")1684 1685 def visit_MarkSafeIfAutoescape(self, node, frame):1730- self.write("(context.eval_ctx.autoescape and Markup or identity)(")1686+ self.write("(Markup if context.eval_ctx.autoescape else identity)(")1687 self.visit(node.expr, frame)1688 self.write(")")1689 1690 def visit_EnvironmentAttribute(self, node, frame):1691 self.write("environment." + node.name)1692 1693 def visit_ExtensionAttribute(self, node, frame):1738- self.write("environment.extensions[%r].%s" % (node.identifier, node.name))1694+ self.write(f"environment.extensions[{node.identifier!r}].{node.name}")1695 1696 def visit_ImportedName(self, node, frame):1697 self.write(self.import_aliases[node.importname])1698 20 unmodified lines1719 self.leave_frame(scope_frame)1720 1721 def visit_OverlayScope(self, node, frame):1722 ctx = self.temporary_identifier()1767- self.writeline("%s = %s" % (ctx, self.derive_context(frame)))1768- self.writeline("%s.vars = " % ctx)1723+ self.writeline(f"{ctx} = {self.derive_context(frame)}")1724+ self.writeline(f"{ctx}.vars = ")1725 self.visit(node.context, frame)1726 self.push_context_reference(ctx)1727 1728 scope_frame = frame.inner(isolated=True)4 unmodified lines1733 self.pop_context_reference()1734 1735 def visit_EvalContextModifier(self, node, frame):1736 for keyword in node.options:1781- self.writeline("context.eval_ctx.%s = " % keyword.key)1737+ self.writeline(f"context.eval_ctx.{keyword.key} = ")1738 self.visit(keyword.value, frame)1739 try:1740 val = keyword.value.as_const(frame.eval_ctx)1741 except nodes.Impossible:3 unmodified lines1745 1746 def visit_ScopedEvalContextModifier(self, node, frame):1747 old_ctx_name = self.temporary_identifier()1748 saved_ctx = frame.eval_ctx.save()1793- self.writeline("%s = context.eval_ctx.save()" % old_ctx_name)1749+ self.writeline(f"{old_ctx_name} = context.eval_ctx.save()")1750 self.visit_EvalContextModifier(node, frame)1751 for child in node.body:1752 self.visit(child, frame)1753 frame.eval_ctx.revert(saved_ctx)1798- self.writeline("context.eval_ctx.revert(%s)" % old_ctx_name)1754+ self.writeline(f"context.eval_ctx.revert({old_ctx_name})")modified:src/jinja2/constants.py+1 added-2 removed
1-# -*- coding: utf-8 -*-1 #: list of lorem ipsum words used by the lipsum() helper function3-LOREM_IPSUM_WORDS = u"""\2+LOREM_IPSUM_WORDS = """\3 a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at4 auctor augue bibendum blandit class commodo condimentum congue consectetuer5 consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus6 diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend14 unmodified linesmodified:src/jinja2/debug.py+1 added-1 removed
104 unmodified lines105 106 if function == "root":107 location = "top-level template code"108 elif function.startswith("block_"):109- location = 'block "%s"' % function[6:]109+ location = f"block {function[6:]!r}"110 111 # Collect arguments for the new code object. CodeType only112 # accepts positional arguments, and arguments were inserted in113 # new Python versions.151 unmodified linesmodified:src/jinja2/defaults.py-1 removed
1-# -*- coding: utf-8 -*-1 from .filters import FILTERS as DEFAULT_FILTERS # noqa: F4012 from .tests import TESTS as DEFAULT_TESTS # noqa: F4013 from .utils import Cycler4 from .utils import generate_lorem_ipsum38 unmodified linesmodified:src/jinja2/environment.py+23 added-24 removed
1-# -*- coding: utf-8 -*-1 """Classes for managing templates and their runtime and compile time2 options.3 """4 import os94 unmodified lines99 result[extension.identifier] = extension(environment)100 return result101 102 104-def fail_for_missing_callable(string, name):105- msg = string % name103+def fail_for_missing_callable(thing, name):104+ msg = f"no {thing} named {name!r}"105+106 if isinstance(name, Undefined):107 try:108 name._fail_with_undefined_error()109 except Exception as e:110- msg = "%s (%s; did you forget to quote the callable name?)" % (msg, e)110+ msg = f"{msg} ({e}; did you forget to quote the callable name?)"111 raise TemplateRuntimeError(msg)112 113 114 def _environment_sanity_check(environment):5 unmodified lines120 environment.block_start_string121 != environment.variable_start_string122 != environment.comment_start_string123 ), "block, variable and comment start strings must be different"124- assert environment.newline_sequence in (124+ assert environment.newline_sequence in {125 "\r",126 "\r\n",127 "\n",128- ), "newline_sequence set to unknown line ending string."128+ }, "newline_sequence set to unknown line ending string."129 return environment130 131 132-class Environment(object):132+class Environment:133 r"""The core component of Jinja is the `Environment`. It contains134 important shared variables like configuration, filters, tests,135 globals and others. Instances of this class may be modified if136 they are not shared and if no template was loaded so far.341 unmodified lines478 .. versionadded:: 2.7479 """480 func = self.filters.get(name)481 if func is None:482- fail_for_missing_callable("no filter named %r", name)482+ fail_for_missing_callable("filter", name)483 args = [value] + list(args or ())484 if getattr(func, "contextfilter", False) is True:485 if context is None:486 raise TemplateRuntimeError(17 unmodified lines504 .. versionadded:: 2.7505 """506 func = self.tests.get(name)507 if func is None:508- fail_for_missing_callable("no test named %r", name)508+ fail_for_missing_callable("test", name)509 return func(value, *(args or ()), **(kwargs or {}))510 511 @internalcode512 def parse(self, source, name=None, filename=None):205 unmodified lines718 719 zip_file = ZipFile(720 target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]721 )722- log_function('Compiling into Zip archive "%s"' % target)722+ log_function(f"Compiling into Zip archive {target!r}")723 else:724 if not os.path.isdir(target):725 os.makedirs(target)726- log_function('Compiling into folder "%s"' % target)726+ log_function(f"Compiling into folder {target!r}")727 728 try:729 for name in self.list_templates(extensions, filter_func):730 source, filename, _ = self.loader.get_source(self, name)1 unmodified line732 code = self.compile(source, name, filename, True, True)733 except TemplateSyntaxError as e:734 if not ignore_errors:735 raise736- log_function('Could not compile "%s": %s' % (name, e))736+ log_function(f'Could not compile "{name}": {e}')737 continue738 739 filename = ModuleLoader.get_module_filename(name)740 741 write_file(filename, code)742- log_function('Compiled "%s" as %s' % (name, filename))742+ log_function(f'Compiled "{name}" as {filename}')743 finally:744 if zip:745 zip_file.close()746 111 unmodified lines858 names._fail_with_undefined_error()859 860 if not names:861 raise TemplatesNotFound(862- message=u"Tried to select from an empty list " u"of templates."862+ message="Tried to select from an empty list of templates."863 )864 globals = self.make_globals(globals)865 for name in names:866 if isinstance(name, Template):34 unmodified lines901 return self.globals902 return dict(self.globals, **d)903 904 905-class Template(object):905+class Template:906 """The central template object. This class represents a compiled template907 and is used to evaluate it.908 909 Normally the template object is generated from an :class:`Environment` but163 unmodified lines1073 It accepts the same arguments as :meth:`render`.1074 """1075 vars = dict(*args, **kwargs)1076 try:1077- for event in self.root_render_func(self.new_context(vars)):1078- yield event1077+ yield from self.root_render_func(self.new_context(vars))1078 except Exception:1079 yield self.environment.handle_exception()1080 1081 def generate_async(self, *args, **kwargs):84 unmodified lines1166 return []1167 1168 def __repr__(self):1169 if self.name is None:1171- name = "memory:%x" % id(self)1170+ name = f"memory:{id(self):x}"1171 else:1172 name = repr(self.name)1174- return "<%s %s>" % (self.__class__.__name__, name)1173+ return f"<{self.__class__.__name__} {name}>"1174 1175 1177-class TemplateModule(object):1176+class TemplateModule:1177 """Represents an imported template. All the exported names of the1178 template are available as attributes on this object. Additionally1179 converting it into a string renders the contents.1180 """19 unmodified lines1200 return concat(self._body_stream)1201 1202 def __repr__(self):1203 if self.__name__ is None:1205- name = "memory:%x" % id(self)1204+ name = f"memory:{id(self):x}"1205 else:1206 name = repr(self.__name__)1208- return "<%s %s>" % (self.__class__.__name__, name)1207+ return f"<{self.__class__.__name__} {name}>"1208 1209 1211-class TemplateExpression(object):1210+class TemplateExpression:1211 """The :meth:`jinja2.Environment.compile_expression` method returns an1212 instance of this object. It encapsulates the expression-like access1213 to the template with an expression it wraps.1214 """10 unmodified lines1225 rv = None1226 return rv1227 1228 1230-class TemplateStream(object):1229+class TemplateStream:1230 """A template stream works pretty much like an ordinary python generator1231 but it can buffer multiple items to reduce the number of total iterations.1232 Per default the output is unbuffered which means that for every unbuffered1233 instruction in the template one string is yielded.81 unmodified linesmodified:src/jinja2/exceptions.py+5 added-5 removed
63 unmodified lines64 parts.append(name._undefined_message)65 else:66 parts.append(name)67 68- message = u"none of the templates given were found: " + u", ".join(68+ message = "none of the templates given were found: " + ", ".join(69 map(str, parts)70 )71- TemplateNotFound.__init__(self, names and names[-1] or None, message)71+ TemplateNotFound.__init__(self, names[-1] if names else None, message)72 self.templates = list(names)73 74 75 class TemplateSyntaxError(TemplateError):15 unmodified lines91 if self.translated:92 return self.message93 94 # otherwise attach some stuff95- location = "line %d" % self.lineno95+ location = f"line {self.lineno}"96 name = self.filename or self.name97 if name:98- location = 'File "%s", %s' % (name, location)98+ location = f'File "{name}", {location}'99 lines = [self.message, " " + location]100 101 # if the source is set, add the line to the output102 if self.source is not None:3 unmodified lines106 line = None107 if line:108 lines.append(" " + line.strip())109 110- return u"\n".join(lines)110+ return "\n".join(lines)111 112 def __reduce__(self):113 # https://bugs.python.org/issue1692335 Exceptions that take114 # multiple required arguments have problems with pickling.33 unmodified linesmodified:src/jinja2/ext.py+8 added-9 removed
1-# -*- coding: utf-8 -*-1 """Extension API for adding custom tags and behavior."""2 import pprint3 import re4 from sys import version_info33 unmodified lines38 """Gives the extension an unique identifier."""39 40 def __new__(mcs, name, bases, d):41 rv = type.__new__(mcs, name, bases, d)43- rv.identifier = rv.__module__ + "." + rv.__name__42+ rv.identifier = f"{rv.__module__}.{rv.__name__}"43 return rv44 45 46 class Extension(metaclass=ExtensionRegistry):154 unmodified lines201 self._install_callables(gettext, ngettext, newstyle)202 203 def _install_null(self, newstyle=None):204 self._install_callables(206- lambda x: x, lambda s, p, n: (n != 1 and (p,) or (s,))[0], newstyle205+ lambda x: x, lambda s, p, n: s if n == 1 else p, newstyle206 )207 208 def _install_callables(self, gettext, ngettext, newstyle=None):209 if newstyle is not None:34 unmodified lines244 245 name = parser.stream.expect("name")246 if name.value in variables:247 parser.fail(249- "translatable variable %r defined twice." % name.value,248+ f"translatable variable {name.value!r} defined twice.",249 name.lineno,250 exc=TemplateAssertionError,251 )252 39 unmodified lines292 if parser.stream.current.type != "block_end":293 name = parser.stream.expect("name")294 if name.value not in variables:295 parser.fail(297- "unknown variable %r for pluralization" % name.value,296+ f"unknown variable {name.value!r} for pluralization",297 name.lineno,298 exc=TemplateAssertionError,299 )300 plural_expr = variables[name.value]50 unmodified lines351 elif parser.stream.current.type == "variable_begin":352 next(parser.stream)353 name = parser.stream.expect("name").value354 referenced.append(name)356- buf.append("%%(%s)s" % name)355+ buf.append(f"%({name})s")356 parser.stream.expect("variable_end")357 elif parser.stream.current.type == "block_begin":358 next(parser.stream)359 if parser.stream.current.test("name:endtrans"):74 unmodified lines434 """Adds a `do` tag to Jinja that works like the print statement just435 that it doesn't print the return value.436 """437 439- tags = set(["do"])438+ tags = {"do"}439 440 def parse(self, parser):441 node = nodes.ExprStmt(lineno=next(parser.stream).lineno)442 node.node = parser.parse_tuple()2 unmodified lines445 446 class LoopControlExtension(Extension):447 """Adds break and continue to the template engine."""448 450- tags = set(["break", "continue"])449+ tags = {"break", "continue"}450 451 def parse(self, parser):452 token = next(parser.stream)453 if token.value == "break":119 unmodified lines573 strings = tuple(strings)574 yield node.lineno, node.node.name, strings575 576 578-class _CommentFinder(object):577+class _CommentFinder:578 """Helper class to find comments in a token stream. Can only579 find comments for gettext calls forwards. Once the comment580 from line 4 is found, a comment for line 1 will not return a581 usable value.119 unmodified linesmodified:src/jinja2/filters.py+24 added-27 removed
1-# -*- coding: utf-8 -*-1 """Built-in template filters used with the ``|`` operator."""2 import math3 import random4 import re146 unmodified lines151 items = value.items()152 else:153 items = iter(value)154 156- return u"&".join(157- "%s=%s" % (url_quote(k, for_qs=True), url_quote(v, for_qs=True))158- for k, v in items155+ return "&".join(156+ f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items157 )158 159 160 @evalcontextfilter60 unmodified lines221 222 As you can see it automatically prepends a space in front of the item223 if the filter returned something unless the second parameter is false.224 """227- rv = u" ".join(228- u'%s="%s"' % (escape(key), escape(value))225+ rv = " ".join(226+ f'{escape(key)}="{escape(value)}"'227 for key, value in d.items()228 if value is not None and not isinstance(value, Undefined)229 )230 if autospace and rv:233- rv = u" " + rv231+ rv = " " + rv232 if _eval_ctx.autoescape:233 rv = Markup(rv)234 return rv235 176 unmodified lines412 """413 return _min_or_max(environment, value, max, case_sensitive, attribute)414 415 418-def do_default(value, default_value=u"", boolean=False):416+def do_default(value, default_value="", boolean=False):417 """If the value is undefined it will return the passed default value,418 otherwise the value of the variable:419 420 .. sourcecode:: jinja20 unmodified lines441 return value442 443 444 @evalcontextfilter447-def do_join(eval_ctx, value, d=u"", attribute=None):445+def do_join(eval_ctx, value, d="", attribute=None):446 """Return a string which is the concatenation of the strings in the447 sequence. The separator between elements is an empty string per448 default, you can define it with the optional parameter:449 88 unmodified lines538 Giga, etc.), if the second parameter is set to `True` the binary539 prefixes are used (Mebi, Gibi).540 """541 bytes = float(value)544- base = binary and 1024 or 1000542+ base = 1024 if binary else 1000543 prefixes = [546- (binary and "KiB" or "kB"),547- (binary and "MiB" or "MB"),548- (binary and "GiB" or "GB"),549- (binary and "TiB" or "TB"),550- (binary and "PiB" or "PB"),551- (binary and "EiB" or "EB"),552- (binary and "ZiB" or "ZB"),553- (binary and "YiB" or "YB"),544+ ("KiB" if binary else "kB"),545+ ("MiB" if binary else "MB"),546+ ("GiB" if binary else "GB"),547+ ("TiB" if binary else "TB"),548+ ("PiB" if binary else "PB"),549+ ("EiB" if binary else "EB"),550+ ("ZiB" if binary else "ZB"),551+ ("YiB" if binary else "YB"),552 ]553 if bytes == 1:554 return "1 Byte"555 elif bytes < base:558- return "%d Bytes" % bytes556+ return f"{int(bytes)} Bytes"557 else:558 for i, prefix in enumerate(prefixes):559 unit = base ** (i + 2)560 if bytes < unit:563- return "%.1f %s" % ((base * bytes / unit), prefix)564- return "%.1f %s" % ((base * bytes / unit), prefix)561+ return f"{base * bytes / unit:.1f} {prefix}"562+ return f"{base * bytes / unit:.1f} {prefix}"563 564 565 def do_pprint(value):566 """Pretty print a variable. Useful for debugging."""51 unmodified lines618 Blank lines are not indented by default.619 620 Rename the ``indentfirst`` argument to ``first``.621 """624- indention = u" " * width625- newline = u"\n"622+ indention = " " * width623+ newline = "\n"624 625 if isinstance(s, Markup):626 indention = Markup(indention)627 newline = Markup(newline)43 unmodified lines671 can be reconfigured globally.672 """673 if leeway is None:674 leeway = env.policies["truncate.leeway"]677- assert length >= len(end), "expected length >= %s, got %s" % (len(end), length)678- assert leeway >= 0, "expected leeway >= 0, got %s" % leeway675+ assert length >= len(end), f"expected length >= {len(end)}, got {length}"676+ assert leeway >= 0, f"expected leeway >= 0, got {leeway}"677 if len(s) <= length + leeway:678 return s679 if killwords:680 return s[: length - len(end)] + end561 unmodified lines1242 1243 def prepare_map(args, kwargs):1244 context = args[0]1245 seq = args[1]1248- default = None1246 1247 if len(args) == 2 and "attribute" in kwargs:1248 attribute = kwargs.pop("attribute")1249 default = kwargs.pop("default", None)1250 if kwargs:1251 raise FilterArgumentError(1255- "Unexpected keyword argument %r" % next(iter(kwargs))1252+ f"Unexpected keyword argument {next(iter(kwargs))!r}"1253 )1254 func = make_attrgetter(context.environment, attribute, default=default)1255 else:1256 try:105 unmodified linesmodified:src/jinja2/idtracking.py+5 added-5 removed
18 unmodified lines19 sym.analyze_node(node)20 return sym21 22 23-class Symbols(object):23+class Symbols:24 def __init__(self, parent=None, level=None):25 if level is None:26 if parent is None:27 level = 09 unmodified lines37 visitor = RootVisitor(self)38 visitor.visit(node, **kwargs)39 40 def _define_ref(self, name, load=None):41- ident = "l_%d_%s" % (self.level, name)41+ ident = f"l_{self.level}_{name}"42 self.refs[name] = ident43 if load is not None:44 self.loads[ident] = load45 return ident13 unmodified lines59 def ref(self, name):60 rv = self.find_ref(name)61 if rv is None:62 raise AssertionError(63- "Tried to resolve a name to a reference that "64- "was unknown to the frame (%r)" % name63+ "Tried to resolve a name to a reference that was"64+ f" unknown to the frame ({name!r})"65 )66 return rv67 68 def copy(self):129 unmodified lines198 self.sym_visitor.visit(child)199 200 def generic_visit(self, node, *args, **kwargs):201 raise NotImplementedError(202- "Cannot find symbols for %r" % node.__class__.__name__202+ f"Cannot find symbols for {node.__class__.__name__!r}"203 )204 205 206 class FrameSymbolVisitor(NodeVisitor):83 unmodified linesmodified:src/jinja2/lexer.py+43 added-77 removed
1-# -*- coding: utf-8 -*-1 """Implements a Jinja / Python combination lexer. The ``Lexer`` class2 is used to do some preprocessing. It filters out invalid operators like3 the bitshift operators we don't allow in templates. It separates4 template code and python code in expressions.113 unmodified lines118 ",": TOKEN_COMMA,119 ";": TOKEN_SEMICOLON,120 }121 123-reverse_operators = dict([(v, k) for k, v in operators.items()])122+reverse_operators = {v: k for k, v in operators.items()}123 assert len(operators) == len(reverse_operators), "operators dropped"124 operator_re = re.compile(126- "(%s)" % "|".join(re.escape(x) for x in sorted(operators, key=lambda x: -len(x)))125+ f"({'|'.join(re.escape(x) for x in sorted(operators, key=lambda x: -len(x)))})"126 )127 128 ignored_tokens = frozenset(129 [95 unmodified lines225 226 return [x[1:] for x in sorted(rules, reverse=True)]227 228 230-class Failure(object):229+class Failure:230 """Class that raises a `TemplateSyntaxError` if called.231 Used by the `Lexer` to specify known errors.232 """233 41 unmodified lines275 return True276 return False277 278 def __repr__(self):280- return "Token(%r, %r, %r)" % (self.lineno, self.type, self.value)279+ return f"Token({self.lineno!r}, {self.type!r}, {self.value!r})"280 281 283-class TokenStreamIterator(object):282+class TokenStreamIterator:283 """The iterator for tokenstreams. Iterate over the stream284 until the eof token is reached.285 """286 11 unmodified lines298 next(self.stream)299 return token300 301 303-class TokenStream(object):302+class TokenStream:303 """A token stream is an iterable that yields :class:`Token`\\s. The304 parser however does not iterate over it but calls :meth:`next` to go305 one token ahead. The current active token is stored as :attr:`current`.306 """76 unmodified lines383 if not self.current.test(expr):384 expr = describe_token_expr(expr)385 if self.current.type is TOKEN_EOF:386 raise TemplateSyntaxError(388- "unexpected end of template, expected %r." % expr,387+ f"unexpected end of template, expected {expr!r}.",388 self.current.lineno,389 self.name,390 self.filename,391 )392 raise TemplateSyntaxError(394- "expected token %r, got %r" % (expr, describe_token(self.current)),393+ f"expected token {expr!r}, got {describe_token(self.current)!r}",394 self.current.lineno,395 self.name,396 self.filename,397 )35 unmodified lines433 434 # Even though it looks like a no-op, creating instances fails435 # without this.436 def __new__(cls, *members, **kwargs):438- return super(OptionalLStrip, cls).__new__(cls, members)437+ return super().__new__(cls, members)438 439 441-class Lexer(object):440+class Lexer:441 """Class that implements a lexer for a given environment. Automatically442 created by the environment class, usually you don't have to do that.443 444 Note that the lexer is not automatically bound to an environment.24 unmodified lines469 # variables are just part of the rules if variable processing470 # is required.471 root_tag_rules = compile_rules(environment)472 473+ block_start_re = e(environment.block_start_string)474+ block_end_re = e(environment.block_end_string)475+ comment_end_re = e(environment.comment_end_string)476+ variable_end_re = e(environment.variable_end_string)477+478 # block suffix if trimming is enabled475- block_suffix_re = environment.trim_blocks and "\\n?" or ""479+ block_suffix_re = "\\n?" if environment.trim_blocks else ""480 481 # If lstrip is enabled, it should not be applied if there is any482 # non-whitespace between the newline and block.483 self.lstrip_unless_re = c(r"[^ \t]") if environment.lstrip_blocks else None484 485 self.newline_sequence = environment.newline_sequence486 self.keep_trailing_newline = environment.keep_trailing_newline487 488+ root_raw_re = (489+ fr"(?P<raw_begin>{block_start_re}(\-|\+|)\s*raw\s*"490+ fr"(?:\-{block_end_re}\s*|{block_end_re}))"491+ )492+ root_parts_re = "|".join(493+ [root_raw_re] + [fr"(?P<{n}>{r}(\-|\+|))" for n, r in root_tag_rules]494+ )495+496 # global lexing rules497 self.rules = {498 "root": [499 # directives500 (489- c(490- "(.*?)(?:%s)"491- % "|".join(492- [493- r"(?P<raw_begin>%s(\-|\+|)\s*raw\s*(?:\-%s\s*|%s))"494- % (495- e(environment.block_start_string),496- e(environment.block_end_string),497- e(environment.block_end_string),498- )499- ]500- + [501- r"(?P<%s>%s(\-|\+|))" % (n, r)502- for n, r in root_tag_rules503- ]504- )505- ),501+ c(fr"(.*?)(?:{root_parts_re})"),502 OptionalLStrip(TOKEN_DATA, "#bygroup"),503 "#bygroup",504 ),505 # data2 unmodified lines508 # comments509 TOKEN_COMMENT_BEGIN: [510 (511 c(516- r"(.*?)((?:\-%s\s*|%s)%s)"517- % (518- e(environment.comment_end_string),519- e(environment.comment_end_string),520- block_suffix_re,521- )512+ fr"(.*?)((?:\-{comment_end_re}\s*"513+ fr"|{comment_end_re}){block_suffix_re})"514 ),515 (TOKEN_COMMENT, TOKEN_COMMENT_END),516 "#pop",517 ),526- (c("(.)"), (Failure("Missing end of comment tag"),), None),518+ (c(r"(.)"), (Failure("Missing end of comment tag"),), None),519 ],520 # blocks521 TOKEN_BLOCK_BEGIN: [522 (531- c(532- r"(?:\-%s\s*|%s)%s"533- % (534- e(environment.block_end_string),535- e(environment.block_end_string),536- block_suffix_re,537- )538- ),523+ c(fr"(?:\-{block_end_re}\s*|{block_end_re}){block_suffix_re}"),524 TOKEN_BLOCK_END,525 "#pop",526 ),527 ]528 + tag_rules,529 # variables530 TOKEN_VARIABLE_BEGIN: [531 (547- c(548- r"\-%s\s*|%s"549- % (550- e(environment.variable_end_string),551- e(environment.variable_end_string),552- )553- ),532+ c(fr"\-{variable_end_re}\s*|{variable_end_re}"),533 TOKEN_VARIABLE_END,534 "#pop",535 )536 ]1 unmodified line538 # raw block539 TOKEN_RAW_BEGIN: [540 (541 c(563- r"(.*?)((?:%s(\-|\+|))\s*endraw\s*(?:\-%s\s*|%s%s))"564- % (565- e(environment.block_start_string),566- e(environment.block_end_string),567- e(environment.block_end_string),568- block_suffix_re,569- )542+ fr"(.*?)((?:{block_start_re}(\-|\+|))\s*endraw\s*"543+ fr"(?:\-{block_end_re}\s*|{block_end_re}{block_suffix_re}))"544 ),545 OptionalLStrip(TOKEN_DATA, TOKEN_RAW_END),546 "#pop",547 ),574- (c("(.)"), (Failure("Missing end of raw directive"),), None),548+ (c(r"(.)"), (Failure("Missing end of raw directive"),), None),549 ],550 # line statements551 TOKEN_LINESTATEMENT_BEGIN: [552 (c(r"\s*(\n|$)"), TOKEN_LINESTATEMENT_END, "#pop")69 unmodified lines622 generator. Use this method if you just want to tokenize a template.623 """624 lines = source.splitlines()625 if self.keep_trailing_newline and source:652- for newline in ("\r\n", "\r", "\n"):653- if source.endswith(newline):654- lines.append("")626+ if source.endswith(("\r\n", "\r", "\n")):627+ lines.append("")655- break628 source = "\n".join(lines)629 pos = 0630 lineno = 1631 stack = ["root"]71 unmodified lines703 lineno += value.count("\n")704 break705 else:706 raise RuntimeError(735- "%r wanted to resolve "736- "the token dynamically"737- " but no group matched" % regex707+ f"{regex!r} wanted to resolve the token dynamically"708+ " but no group matched"709 )710 # normal group711 else:712 data = groups[idx]14 unmodified lines727 balancing_stack.append("]")728 elif data in ("}", ")", "]"):729 if not balancing_stack:730 raise TemplateSyntaxError(760- "unexpected '%s'" % data, lineno, name, filename731+ f"unexpected '{data}'", lineno, name, filename732 )733 expected_op = balancing_stack.pop()734 if expected_op != data:735 raise TemplateSyntaxError(765- "unexpected '%s', "766- "expected '%s'" % (data, expected_op),736+ f"unexpected '{data}', expected '{expected_op}'",737 lineno,738 name,739 filename,740 )19 unmodified lines760 stack.append(key)761 break762 else:763 raise RuntimeError(794- "%r wanted to resolve the "795- "new state dynamically but"796- " no group matched" % regex764+ f"{regex!r} wanted to resolve the new state dynamically"765+ f" but no group matched"766 )767 # direct state name given768 else:769 stack.append(new_state)2 unmodified lines772 # this means a loop without break condition, avoid that and773 # raise error774 elif pos2 == pos:775 raise RuntimeError(807- "%r yielded empty string without stack change" % regex776+ f"{regex!r} yielded empty string without stack change"777 )778 # publish new function and start again779 pos = pos2780 break4 unmodified lines785 if pos >= source_length:786 return787 # something went wrong788 raise TemplateSyntaxError(820- "unexpected char %r at %d" % (source[pos], pos),821- lineno,822- name,823- filename,789+ f"unexpected char {source[pos]!r} at {pos}", lineno, name, filename790 )modified:src/jinja2/loaders.py+6 added-7 removed
1-# -*- coding: utf-8 -*-1 """API and implementations for loading templates from different data2 sources.3 """4 import os26 unmodified lines31 pieces.append(piece)32 return pieces33 34 36-class BaseLoader(object):35+class BaseLoader:36 """Baseclass for all loaders. Subclass this and override `get_source` to37 implement a custom loading mechanism. The environment provides a38 `get_template` method that calls the loader's `load` method to get the39 :class:`Template` object.44 unmodified lines84 the template will be reloaded.85 """86 if not self.has_source_access:87 raise RuntimeError(89- "%s cannot provide access to the source" % self.__class__.__name__88+ f"{self.__class__.__name__} cannot provide access to the source"89 )90 raise TemplateNotFound(template)91 92 def list_templates(self):182 unmodified lines275 break276 277 if self._template_root is None:278 raise ValueError(280- "The %r package was not installed in a way that"281- " PackageLoader understands." % package_name279+ f"The {package_name!r} package was not installed in a"280+ " way that PackageLoader understands."281 )282 283 def get_source(self, environment, template):284 p = os.path.join(self._template_root, *split_template_path(template))227 unmodified lines512 513 has_source_access = False514 515 def __init__(self, path):517- package_name = "_jinja2_module_templates_%x" % id(self)516+ package_name = f"_jinja2_module_templates_{id(self):x}"517 518 # create a fake module that looks for the templates in the519 # path given.520 mod = _TemplateModule(package_name)23 unmodified lines544 545 @internalcode546 def load(self, environment, name, globals=None):547 key = self.get_template_key(name)549- module = "%s.%s" % (self.package_name, key)548+ module = f"{self.package_name}.{key}"549 mod = getattr(self.module, module, None)550 if mod is None:551 try:552 mod = __import__(module, None, None, ["root"])10 unmodified linesmodified:src/jinja2/meta.py-1 removed
1-# -*- coding: utf-8 -*-1 """Functions that expose information about templates that might be2 interesting for introspection.3 """4 from . import nodes94 unmodified linesmodified:src/jinja2/nativetypes.py+3 added-2 removed
30 unmodified lines31 raw = head[0]32 else:33 if isinstance(nodes, types.GeneratorType):34 nodes = chain(head, nodes)35- raw = u"".join([str(v) for v in nodes])35+ raw = "".join([str(v) for v in nodes])36 37 try:38 literal = literal_eval(raw)39 except (ValueError, SyntaxError, MemoryError):3 unmodified lines43 # quote character to avoid dropping quotes between expression nodes.44 # Without this, "'{{ a }}', '{{ b }}'" results in "a, b", but should45 # be ('a', 'b').46 if preserve_quotes and isinstance(literal, str):47- return "{quote}{}{quote}".format(literal, quote=raw[0])47+ quote = raw[0]48+ return f"{quote}{literal}{quote}"49 50 return literal51 52 59 unmodified linesmodified:src/jinja2/nodes.py+16 added-30 removed
1-# -*- coding: utf-8 -*-1 """AST nodes generated by the parser for the compiler. Also provides2 some node tree helper functions used by the parser and compiler in order3 to normalize nodes.4 """11 unmodified lines16 "+": operator.add,17 "-": operator.sub,18 }19 21-_uaop_to_func = {"not": operator.not_, "+": operator.pos, "-": operator.neg}20+_uaop_to_func = {21+ "not": operator.not_,22+ "+": operator.pos,23+ "-": operator.neg,24+}25 26 _cmpop_to_func = {27 "eq": operator.eq,28 "ne": operator.ne,26 unmodified lines55 d.setdefault("abstract", False)56 return type.__new__(mcs, name, bases, d)57 58 56-class EvalContext(object):59+class EvalContext:60 """Holds evaluation time information. Custom attributes can be attached61 to it in extensions.62 """63 16 unmodified lines80 def get_eval_context(node, ctx):81 if ctx is None:82 if node.environment is None:83 raise RuntimeError(81- "if no eval context is passed, the "82- "node must have an attached "83- "environment."84+ "if no eval context is passed, the node must have an"85+ " attached environment."86 )87 return EvalContext(node.environment)88 return ctx89 24 unmodified lines114 raise TypeError("abstract nodes are not instantiable")115 if fields:116 if len(fields) != len(self.fields):117 if not self.fields:116- raise TypeError("%r takes 0 arguments" % self.__class__.__name__)118+ raise TypeError(f"{self.__class__.__name__!r} takes 0 arguments")119 raise TypeError(118- "%r takes 0 or %d argument%s"119- % (120- self.__class__.__name__,121- len(self.fields),122- len(self.fields) != 1 and "s" or "",123- )120+ f"{self.__class__.__name__!r} takes 0 or {len(self.fields)}"121+ f" argument{'s' if len(self.fields) != 1 else ''}"122 )123 for name, arg in zip(self.fields, fields):124 setattr(self, name, arg)125 for attr in self.attributes:126 setattr(self, attr, attributes.pop(attr, None))127 if attributes:130- raise TypeError("unknown attribute %r" % next(iter(attributes)))128+ raise TypeError(f"unknown attribute {next(iter(attributes))!r}")129 130 def iter_fields(self, exclude=None, only=None):131 """This method iterates over all fields that are defined and yields132 ``(key, value)`` tuples. Per default all fields are returned, but38 unmodified lines171 """172 for child in self.iter_child_nodes():173 if isinstance(child, node_type):174 yield child177- for result in child.find_all(node_type):178- yield result175+ yield from child.find_all(node_type)176 177 def set_ctx(self, ctx):178 """Reset the context of a node and all child nodes. Per default the179 parser will all generate nodes that have a 'load' context as it's the37 unmodified lines217 def __hash__(self):218 return hash(tuple(self.iter_fields()))219 220 def __repr__(self):224- return "%s(%s)" % (225- self.__class__.__name__,226- ", ".join("%s=%r" % (arg, getattr(self, arg, None)) for arg in self.fields),227- )221+ args_str = ", ".join(f"{a}={getattr(self, a, None)!r}" for a in self.fields)222+ return f"{self.__class__.__name__}({args_str})"223 224 def dump(self):225 def _dump(node):226 if not isinstance(node, Node):227 buf.append(repr(node))228 return229 235- buf.append("nodes.%s(" % node.__class__.__name__)230+ buf.append(f"nodes.{node.__class__.__name__}(")231 if not node.fields:232 buf.append(")")233 return234 for idx, field in enumerate(node.fields):568 unmodified lines803 804 fields = ("op", "expr")805 806 812-if __debug__:813- Operand.__doc__ += "\nThe following operators are available: " + ", ".join(814- sorted(815- "``%s``" % x816- for x in set(_binop_to_func) | set(_uaop_to_func) | set(_cmpop_to_func)817- )818- )819-820-807 class Mul(BinExpr):808 """Multiplies the left with the right node."""809 810 operator = "*"242 unmodified linesmodified:src/jinja2/optimizer.py+1 added-2 removed
1-# -*- coding: utf-8 -*-1 """The optimizer tries to constant fold expressions and modify the AST2 in place so that it should be faster to evaluate.3 4 Because the AST does not contain all the scoping information and the17 unmodified lines22 def __init__(self, environment):23 self.environment = environment24 25 def generic_visit(self, node, *args, **kwargs):27- node = super(Optimizer, self).generic_visit(node, *args, **kwargs)26+ node = super().generic_visit(node, *args, **kwargs)27 28 # Do constant folding. Some other nodes besides Expr have29 # as_const, but folding them causes errors later on.30 if isinstance(node, nodes.Expr):10 unmodified linesmodified:src/jinja2/parser.py+15 added-19 removed
1-# -*- coding: utf-8 -*-1 """Parse tokens from the lexer into nodes for the compiler."""2 from . import nodes3 from .exceptions import TemplateAssertionError4 from .exceptions import TemplateSyntaxError27 unmodified lines32 "mod": nodes.Mod,33 }34 35 37-class Parser(object):36+class Parser:37 """This is the central parsing class Jinja uses. It's passed to38 extensions and can be used to parse expressions or statements.39 """40 25 unmodified lines66 for exprs in end_token_stack:67 expected.extend(map(describe_token_expr, exprs))68 if end_token_stack:69 currently_looking = " or ".join(71- "'%s'" % describe_token_expr(expr) for expr in end_token_stack[-1]70+ map(repr, map(describe_token_expr, end_token_stack[-1]))71 )72 else:73 currently_looking = None74 75 if name is None:76 message = ["Unexpected end of template."]77 else:79- message = ["Encountered unknown tag '%s'." % name]78+ message = [f"Encountered unknown tag {name!r}."]79 80 if currently_looking:81 if name is not None and name in expected:82 message.append(84- "You probably made a nesting mistake. Jinja "85- "is expecting this tag, but currently looking "86- "for %s." % currently_looking83+ "You probably made a nesting mistake. Jinja is expecting this tag,"84+ f" but currently looking for {currently_looking}."85 )86 else:87 message.append(90- "Jinja was looking for the following tags: "91- "%s." % currently_looking88+ f"Jinja was looking for the following tags: {currently_looking}."89 )90 91 if self._tag_stack:92 message.append(96- "The innermost block that needs to be "97- "closed is '%s'." % self._tag_stack[-1]93+ "The innermost block that needs to be closed is"94+ f" {self._tag_stack[-1]!r}."95 )96 97 self.fail(" ".join(message), lineno)98 22 unmodified lines121 def free_identifier(self, lineno=None):122 """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""123 self._last_identifier += 1124 rv = object.__new__(nodes.InternalName)128- nodes.Node.__init__(rv, "fi%d" % self._last_identifier, lineno=lineno)125+ nodes.Node.__init__(rv, f"fi{self._last_identifier}", lineno=lineno)126 return rv127 128 def parse_statement(self):129 """Parse a single statement."""130 unmodified lines260 # to jinja. we do not support hyphens in block names, so let's261 # raise a nicer error message in that case.262 if self.stream.current.type == "sub":263 self.fail(267- "Block names in Jinja have to be valid Python "268- "identifiers and may not contain hyphens, use an "269- "underscore instead."264+ "Block names in Jinja have to be valid Python identifiers and may not"265+ " contain hyphens, use an underscore instead."266 )267 268 node.body = self.parse_statements(("name:endblock",), drop_needle=True)269 self.stream.skip_if("name:" + node.name)159 unmodified lines429 target = self.parse_primary()430 target.set_ctx("store")431 if not target.can_assign():432 self.fail(437- "can't assign to %r" % target.__class__.__name__.lower(), target.lineno433+ f"can't assign to {target.__class__.__name__.lower()!r}", target.lineno434 )435 return target436 437 def parse_expression(self, with_condexpr=True):152 unmodified lines590 node = self.parse_list()591 elif token.type == "lbrace":592 node = self.parse_dict()593 else:598- self.fail("unexpected '%s'" % describe_token(token), token.lineno)594+ self.fail(f"unexpected {describe_token(token)!r}", token.lineno)595 return node596 597 def parse_tuple(598 self,53 unmodified lines652 # nothing) in the spot of an expression would be an empty653 # tuple.654 if not explicit_parentheses:655 self.fail(660- "Expected an expression, got '%s'"661- % describe_token(self.stream.current)656+ "Expected an expression,"657+ f" got {describe_token(self.stream.current)!r}"658 )659 660 return nodes.Tuple(args, "load", lineno=lineno)661 273 unmodified linesmodified:src/jinja2/runtime.py+46 added-69 removed
1-# -*- coding: utf-8 -*-1 """The runtime functions and state used by compiled templates."""2 import sys3 from collections import abc4 from itertools import chain46 unmodified lines51 iterator = map(soft_str, seq)52 for arg in iterator:53 buf.append(arg)54 if hasattr(arg, "__html__"):56- return Markup(u"").join(chain(buf, iterator))55+ return Markup("").join(chain(buf, iterator))56 return concat(buf)57 58 59 def str_join(seq):39 unmodified lines99 parent[key] = value100 return environment.context_class(environment, parent, template_name, blocks)101 102 104-class TemplateReference(object):103+class TemplateReference:104 """The `self` in templates."""105 106 def __init__(self, context):107 self.__context = context2 unmodified lines110 blocks = self.__context.blocks[name]111 return BlockReference(name, self.__context, blocks, 0)112 113 def __repr__(self):115- return "<%s %r>" % (self.__class__.__name__, self.__context.name)114+ return f"<{self.__class__.__name__} {self.__context.name!r}>"115 116 117 def _get_func(x):118 return getattr(x, "__func__", x)85 unmodified lines204 index = blocks.index(current) + 1205 blocks[index]206 except LookupError:207 return self.environment.undefined(209- "there is no parent block called %r." % name, name="super"208+ f"there is no parent block called {name!r}.", name="super"209 )210 return BlockReference(name, self, blocks, index)211 212 def get(self, key, default=None):29 unmodified lines242 return resolve_or_missing(self, key)243 244 def get_exported(self):245 """Get a new dict with the exported variables."""247- return dict((k, self.vars[k]) for k in self.exported_vars)246+ return {k: self.vars[k] for k in self.exported_vars}247 248 def get_all(self):249 """Return the complete context as dict including the exported250 variables. For optimizations reasons this might not return an37 unmodified lines288 try:289 return __obj(*args, **kwargs)290 except StopIteration:291 return __self.environment.undefined(293- "value was undefined because "294- "a callable raised a "295- "StopIteration exception"292+ "value was undefined because a callable raised a"293+ " StopIteration exception"294 )295 296 def derived(self, locals=None):297 """Internal helper function to create a derived context. This is32 unmodified lines330 raise KeyError(key)331 return item332 333 def __repr__(self):336- return "<%s %s of %r>" % (337- self.__class__.__name__,338- repr(self.get_all()),339- self.name,340- )334+ return f"<{self.__class__.__name__} {self.get_all()!r} of {self.name!r}>"335 336 343-class BlockReference(object):337+class BlockReference:338 """One block on a template reference."""339 340 def __init__(self, name, context, stack, depth):341 self.name = name5 unmodified lines347 def super(self):348 """Super the block."""349 if self._depth + 1 >= len(self._stack):350 return self._context.environment.undefined(357- "there is no parent block called %r." % self.name, name="super"351+ f"there is no parent block called {self.name!r}.", name="super"352 )353 return BlockReference(self.name, self._context, self._stack, self._depth + 1)354 355 @internalcode191 unmodified lines547 548 return self._recurse(iterable, self._recurse, depth=self.depth)549 550 def __repr__(self):557- return "<%s %d/%d>" % (self.__class__.__name__, self.index, self.length)551+ return f"<{self.__class__.__name__} {self.index}/{self.length}>"552 553 560-class Macro(object):554+class Macro:555 """Wraps a macro function."""556 557 def __init__(558 self,80 unmodified lines639 arguments.append(kwargs)640 elif kwargs:641 if "caller" in kwargs:642 raise TypeError(649- "macro %r was invoked with two values for "650- "the special caller argument. This is "651- "most likely a bug." % self.name643+ f"macro {self.name!r} was invoked with two values for the special"644+ " caller argument. This is most likely a bug."645 )646 raise TypeError(654- "macro %r takes no keyword argument %r"655- % (self.name, next(iter(kwargs)))647+ f"macro {self.name!r} takes no keyword argument {next(iter(kwargs))!r}"648 )649 if self.catch_varargs:650 arguments.append(args[self._argument_count :])651 elif len(args) > self._argument_count:652 raise TypeError(661- "macro %r takes not more than %d argument(s)"662- % (self.name, len(self.arguments))653+ f"macro {self.name!r} takes not more than"654+ f" {len(self.arguments)} argument(s)"655 )656 657 return self._invoke(arguments, autoescape)658 4 unmodified lines663 rv = Markup(rv)664 return rv665 666 def __repr__(self):675- return "<%s %s>" % (676- self.__class__.__name__,677- self.name is None and "anonymous" or repr(self.name),678- )667+ name = "anonymous" if self.name is None else repr(self.name)668+ return f"<{self.__class__.__name__} {name}>"669 670 681-class Undefined(object):671+class Undefined:672 """The default undefined type. This undefined type can be printed and673 iterated over, but every other access will raise an :exc:`UndefinedError`:674 675 >>> foo = Undefined(name='foo')28 unmodified lines704 if self._undefined_hint:705 return self._undefined_hint706 707 if self._undefined_obj is missing:718- return "%r is undefined" % self._undefined_name708+ return f"{self._undefined_name!r} is undefined"709 710 if not isinstance(self._undefined_name, str):721- return "%s has no element %r" % (722- object_type_repr(self._undefined_obj),723- self._undefined_name,711+ return (712+ f"{object_type_repr(self._undefined_obj)} has no"713+ f" element {self._undefined_name!r}"714 )715 726- return "%r has no attribute %r" % (727- object_type_repr(self._undefined_obj),728- self._undefined_name,716+ return (717+ f"{object_type_repr(self._undefined_obj)!r} has no"718+ f" attribute {self._undefined_name!r}"719 )720 721 @internalcode722 def _fail_with_undefined_error(self, *args, **kwargs):28 unmodified lines751 def __hash__(self):752 return id(type(self))753 754 def __str__(self):765- return u""755+ return ""756 757 def __len__(self):758 return 0759 36 unmodified lines796 if base is None:797 base = Undefined798 799 def _log_message(undef):810- if undef._undefined_hint is None:811- if undef._undefined_obj is missing:812- hint = "%s is undefined" % undef._undefined_name813- elif not isinstance(undef._undefined_name, str):814- hint = "%s has no element %s" % (815- object_type_repr(undef._undefined_obj),816- undef._undefined_name,817- )818- else:819- hint = "%s has no attribute %s" % (820- object_type_repr(undef._undefined_obj),821- undef._undefined_name,822- )823- else:824- hint = undef._undefined_hint825- logger.warning("Template variable warning: %s", hint)800+ logger.warning("Template variable warning: %s", undef._undefined_message)801 802 class LoggingUndefined(base):803 def _fail_with_undefined_error(self, *args, **kwargs):804 try:830- return base._fail_with_undefined_error(self, *args, **kwargs)805+ return super()._fail_with_undefined_error(*args, **kwargs)806 except self._undefined_exception as e:832- logger.error("Template variable error: %s", str(e))807+ logger.error(f"Template variable error: %s", e)808 raise e809 810 def __str__(self):836- rv = base.__str__(self)811 _log_message(self)838- return rv812+ return super().__str__()813 814 def __iter__(self):841- rv = base.__iter__(self)815 _log_message(self)843- return rv816+ return super().__iter__()817 818 def __bool__(self):846- rv = base.__bool__(self)819 _log_message(self)848- return rv820+ return super().__bool__()821 822 return LoggingUndefined823 824 40 unmodified lines865 866 __slots__ = ()867 868 def __str__(self):897- if self._undefined_hint is None:898- if self._undefined_obj is missing:899- return u"{{ %s }}" % self._undefined_name900- return "{{ no such element: %s[%r] }}" % (901- object_type_repr(self._undefined_obj),902- self._undefined_name,869+ if self._undefined_hint:870+ message = f"undefined value printed: {self._undefined_hint}"871+872+ elif self._undefined_obj is missing:873+ message = self._undefined_name874+875+ else:876+ message = (877+ f"no such element: {object_type_repr(self._undefined_obj)}"878+ f"[{self._undefined_name!r}]"879 )904- return u"{{ undefined value printed: %s }}" % self._undefined_hint880 881+ return f"{{{{ {message} }}}}"882 883+884 class StrictUndefined(Undefined):885 """An undefined that barks on print and iteration as well as boolean886 tests and all kinds of comparisons. In other words: you can do nothing887 with it except checking if it's defined using the `defined` test.29 unmodified linesmodified:src/jinja2/sandbox.py+8 added-9 removed
1-# -*- coding: utf-8 -*-1 """A sandbox layer that ensures unsafe operations cannot be performed.2 Useful when the template itself comes from an untrusted source.3 """4 import operator119 unmodified lines124 125 if len(rng) > MAX_RANGE:126 raise OverflowError(127 "Range too big. The sandbox blocks ranges larger than"129- " MAX_RANGE (%d)." % MAX_RANGE128+ f" MAX_RANGE ({MAX_RANGE})."129 )130 131 return rng132 133 134 def unsafe(f):135 """Marks a function or method as unsafe.136 138- ::137+ .. code-block: python138 139 @unsafe140 def delete(self):141 pass226 unmodified lines368 369 def unsafe_undefined(self, obj, attribute):370 """Return an undefined object for unsafe attributes."""371 return self.undefined(373- "access to attribute %r of %r "374- "object is unsafe." % (attribute, obj.__class__.__name__),372+ f"access to attribute {attribute!r} of"373+ f" {obj.__class__.__name__!r} object is unsafe.",374 name=attribute,375 obj=obj,376 exc=SecurityError,377 )9 unmodified lines387 388 if format_func is not None and format_func.__name__ == "format_map":389 if len(args) != 1 or kwargs:390 raise TypeError(392- "format_map() takes exactly one argument %d given"393- % (len(args) + (kwargs is not None))391+ "format_map() takes exactly one argument"392+ f" {len(args) + (kwargs is not None)} given"393 )394 395 kwargs = args[0]396 args = None10 unmodified lines407 408 # the double prefixes are to avoid double keyword argument409 # errors when proxying the call.410 if not __self.is_safe_callable(__obj):412- raise SecurityError("%r is not safely callable" % (__obj,))411+ raise SecurityError(f"{__obj!r} is not safely callable")412 return __context.call(__obj, *args, **kwargs)413 414 415 class ImmutableSandboxedEnvironment(SandboxedEnvironment):7 unmodified lines423 return False424 return not modifies_known_mutable(obj, attr)425 426 428-class SandboxedFormatterMixin(object):427+class SandboxedFormatterMixin:428 def __init__(self, env):429 self._env = env430 431 def get_field(self, field_name, args, kwargs):20 unmodified linesmodified:src/jinja2/tests.py-1 removed
1-# -*- coding: utf-8 -*-1 """Built-in template tests used with the ``is`` operator."""2 import operator3 import re4 from collections import abc207 unmodified linesmodified:src/jinja2/utils.py+39 added-45 removed
1-# -*- coding: utf-8 -*-1 import json2 import os3 import re4 from collections import abc6 unmodified lines11 from markupsafe import escape12 from markupsafe import Markup13 14 _word_split_re = re.compile(r"(\s+)")15+_lead_pattern = "|".join(map(re.escape, ("(", "<", "<")))16+_trail_pattern = "|".join(map(re.escape, (".", ",", ")", ">", "\n", ">")))17 _punctuation_re = re.compile(17- "^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$"18- % (19- "|".join(map(re.escape, ("(", "<", "<"))),20- "|".join(map(re.escape, (".", ",", ")", ">", "\n", ">"))),21- )18+ fr"^(?P<lead>(?:{_lead_pattern})*)(?P<middle>.*?)(?P<trail>(?:{_trail_pattern})*)$"19 )20 _simple_email_re = re.compile(r"^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$")21 _striptags_re = re.compile(r"(<!--.*?-->|<[^>]*>)")22 _entity_re = re.compile(r"&([^;]+);")5 unmodified lines28 29 # internal code30 internal_code = set()31 35-concat = u"".join32+concat = "".join33 34 _slash_escape = "\\/" not in json.dumps("/")35 36 124 unmodified lines161 # __builtin__ in 2.x, builtins in 3.x162 if obj.__class__.__module__ in ("__builtin__", "builtins"):163 name = obj.__class__.__name__164 else:168- name = obj.__class__.__module__ + "." + obj.__class__.__name__169- return "%s object" % name165+ name = f"{obj.__class__.__module__}.{obj.__class__.__name__}"166+ return f"{name} object"167 168 169 def pformat(obj):170 """Format an object using :func:`pprint.pformat`.16 unmodified lines187 attribute.188 189 If target is not None, a target attribute will be added to the link.190 """194- trim_url = (195- lambda x, limit=trim_url_limit: limit is not None196- and (x[:limit] + (len(x) >= limit and "..." or ""))197- or x198- )191+192+ def trim_url(x, limit=trim_url_limit):193+ if limit is not None:194+ return x[:limit] + ("..." if len(x) >= limit else "")195+196+ return x197+198 words = _word_split_re.split(str(escape(text)))200- rel_attr = rel and ' rel="%s"' % str(escape(rel)) or ""201- target_attr = target and ' target="%s"' % escape(target) or ""199+ rel_attr = f' rel="{escape(rel)}"' if rel else ""200+ target_attr = f' target="{escape(target)}"' if target else ""201 202 for i, word in enumerate(words):203 match = _punctuation_re.match(word)204 if match:9 unmodified lines214 or middle.endswith(".net")215 or middle.endswith(".com")216 )217 ):219- middle = '<a href="http://%s"%s%s>%s</a>' % (220- middle,221- rel_attr,222- target_attr,223- trim_url(middle),218+ middle = (219+ f'<a href="http://{middle}"{rel_attr}{target_attr}>'220+ f"{trim_url(middle)}</a>"221 )222 if middle.startswith("http://") or middle.startswith("https://"):226- middle = '<a href="%s"%s%s>%s</a>' % (227- middle,228- rel_attr,229- target_attr,230- trim_url(middle),223+ middle = (224+ f'<a href="{middle}"{rel_attr}{target_attr}>{trim_url(middle)}</a>'225 )226 if (227 "@" in middle228 and not middle.startswith("www.")229 and ":" not in middle230 and _simple_email_re.match(middle)231 ):238- middle = '<a href="mailto:%s">%s</a>' % (middle, middle)232+ middle = f'<a href="mailto:{middle}">{middle}</a>'233 if lead + middle + trail != word:234 words[i] = lead + middle + trail241- return u"".join(words)235+ return "".join(words)236 237 238 def generate_lorem_ipsum(n=5, html=True, min=20, max=100):239 """Generate some lorem ipsum for the template."""31 unmodified lines271 next_capitalized = True272 p.append(word)273 274 # ensure that the paragraph ends with a dot.281- p = u" ".join(p)275+ p = " ".join(p)276 if p.endswith(","):277 p = p[:-1] + "."278 elif not p.endswith("."):279 p += "."280 result.append(p)281 282 if not html:289- return u"\n\n".join(result)290- return Markup(u"\n".join(u"<p>%s</p>" % escape(x) for x in result))283+ return "\n\n".join(result)284+ return Markup("\n".join(f"<p>{escape(x)}</p>" for x in result))285 286 287 def url_quote(obj, charset="utf-8", for_qs=False):288 """Quote a string for use in a URL using the given charset.33 unmodified lines322 return url_quote(obj, charset=charset, for_qs=for_qs)323 324 325 @abc.MutableMapping.register332-class LRUCache(object):326+class LRUCache:327 """A simple LRU Cache implementation."""328 329 # this is fast for small capacities (something below 1000) but doesn't330 # scale. But as long as it's only used as storage for templates this68 unmodified lines399 """Return the current size of the cache."""400 return len(self._mapping)401 402 def __repr__(self):409- return "<%s %r>" % (self.__class__.__name__, self._mapping)403+ return f"<{self.__class__.__name__} {self._mapping!r}>"404 405 def __getitem__(self, key):406 """Get an item from the cache. Moves the item up so that it has the407 highest priority then.110 unmodified lines518 For security reasons this function operates case insensitive.519 520 .. versionadded:: 2.9521 """528- enabled_patterns = tuple("." + x.lstrip(".").lower() for x in enabled_extensions)529- disabled_patterns = tuple("." + x.lstrip(".").lower() for x in disabled_extensions)522+ enabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in enabled_extensions)523+ disabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in disabled_extensions)524 525 def autoescape(template_name):526 if template_name is None:527 return default_for_string28 unmodified lines556 if dumper is None:557 dumper = json.dumps558 rv = (559 dumper(obj, **kwargs)566- .replace(u"<", u"\\u003c")567- .replace(u">", u"\\u003e")568- .replace(u"&", u"\\u0026")569- .replace(u"'", u"\\u0027")560+ .replace("<", "\\u003c")561+ .replace(">", "\\u003e")562+ .replace("&", "\\u0026")563+ .replace("'", "\\u0027")564 )565 return Markup(rv)566 567 574-class Cycler(object):568+class Cycler:569 """Cycle through values by yield them one at a time, then restarting570 once the end is reached. Available as ``cycler`` in templates.571 572 Similar to ``loop.cycle``, but can be used outside loops or across45 unmodified lines618 619 __next__ = next620 621 628-class Joiner(object):622+class Joiner:623 """A joining helper for templates."""624 631- def __init__(self, sep=u", "):625+ def __init__(self, sep=", "):626 self.sep = sep627 self.used = False628 629 def __call__(self):630 if not self.used:631 self.used = True638- return u""632+ return ""633 return self.sep634 635 642-class Namespace(object):636+class Namespace:637 """A namespace object that can hold arbitrary attributes. It may be638 initialized from a dictionary or with keyword arguments."""639 640 def __init__(*args, **kwargs): # noqa: B90211 unmodified lines652 def __setitem__(self, name, value):653 self.__attrs[name] = value654 655 def __repr__(self):662- return "<Namespace %r>" % self.__attrs656+ return f"<Namespace {self.__attrs!r}>"657 658 659 # does this python version support async for in and async generators?660 try:4 unmodified linesmodified:src/jinja2/visitor.py+2 added-4 removed
1-# -*- coding: utf-8 -*-1 """API for traversing the AST nodes. Implemented by the compiler and2 meta introspection.3 """4 from .nodes import Node5 6 8-class NodeVisitor(object):7+class NodeVisitor:8 """Walks the abstract syntax tree and call visitor functions for every9 node found. The visitor functions may return values which will be10 forwarded by the `visit` method.11 8 unmodified lines20 """Return the visitor function for this node or `None` if no visitor21 exists for this node. In that case the generic visit function is22 used instead.23 """25- method = "visit_" + node.__class__.__name__26- return getattr(self, method, None)24+ return getattr(self, f"visit_{node.__class__.__name__}", None)25 26 def visit(self, node, *args, **kwargs):27 """Visit a node."""28 f = self.get_visitor(node)51 unmodified linesmodified:tests/conftest.py-1 removed
1-# -*- coding: utf-8 -*-1 import os2 3 import pytest4 96 unmodified linesmodified:tests/test_api.py+26 added-29 removed
1-# -*- coding: utf-8 -*-1 import os2 import shutil3 import tempfile4 20 unmodified lines25 26 27 @pytest.mark.api28 @pytest.mark.extended30-class TestExtendedAPI(object):29+class TestExtendedAPI:30 def test_item_and_attribute(self, env):31 from jinja2.sandbox import SandboxedEnvironment32 33 for env in Environment(), SandboxedEnvironment():128 unmodified lines162 163 164 @pytest.mark.api165 @pytest.mark.meta167-class TestMeta(object):166+class TestMeta:167 def test_find_undeclared_variables(self, env):168 ast = env.parse("{% set foo = 42 %}{{ bar + foo }}")169 x = meta.find_undeclared_variables(ast)171- assert x == set(["bar"])170+ assert x == {"bar"}171 172 ast = env.parse(173 "{% set foo = 42 %}{{ bar + foo }}"174 "{% macro meh(x) %}{{ x }}{% endmacro %}"175 "{% for item in seq %}{{ muh(item) + meh(seq) }}"176 "{% endfor %}"177 )178 x = meta.find_undeclared_variables(ast)180- assert x == set(["bar", "seq", "muh"])179+ assert x == {"bar", "seq", "muh"}180 181 ast = env.parse("{% for x in range(5) %}{{ x }}{% endfor %}{{ foo }}")182 x = meta.find_undeclared_variables(ast)184- assert x == set(["foo"])183+ assert x == {"foo"}184 185 def test_find_refererenced_templates(self, env):186 ast = env.parse('{% extends "layout.html" %}{% include helper %}')187 i = meta.find_referenced_templates(ast)29 unmodified lines217 218 219 @pytest.mark.api220 @pytest.mark.streaming222-class TestStreaming(object):221+class TestStreaming:222 def test_basic_streaming(self, env):223 t = env.from_string(224 "<ul>{% for item in seq %}<li>{{ loop.index }} - {{ item }}</li>"225 "{%- endfor %}</ul>"8 unmodified lines234 "{%- endfor %}</ul>"235 )236 stream = tmpl.stream(seq=list(range(3)))237 stream.enable_buffering(size=3)239- assert next(stream) == u"<ul><li>1"240- assert next(stream) == u" - 0</li>"238+ assert next(stream) == "<ul><li>1"239+ assert next(stream) == " - 0</li>"240 241 def test_streaming_behavior(self, env):242 tmpl = env.from_string("")243 stream = tmpl.stream()5 unmodified lines249 250 def test_dump_stream(self, env):251 tmp = tempfile.mkdtemp()252 try:254- tmpl = env.from_string(u"\u2713")253+ tmpl = env.from_string("\u2713")254 stream = tmpl.stream()255 stream.dump(os.path.join(tmp, "dump.txt"), "utf-8")256 with open(os.path.join(tmp, "dump.txt"), "rb") as f:257 assert f.read() == b"\xe2\x9c\x93"2 unmodified lines260 261 262 @pytest.mark.api263 @pytest.mark.undefined265-class TestUndefined(object):264+class TestUndefined:265 def test_stopiteration_is_undefined(self):266 def test():267 raise StopIteration()268 8 unmodified lines277 278 def test_logging_undefined(self):279 _messages = []280 282- class DebugLogger(object):281+ class DebugLogger:282 def warning(self, msg, *args):283 _messages.append("W:" + msg % args)284 285 def error(self, msg, *args):286 _messages.append("E:" + msg % args)287 288 logging_undefined = make_logging_undefined(DebugLogger())289 env = Environment(undefined=logging_undefined)291- assert env.from_string("{{ missing }}").render() == u""290+ assert env.from_string("{{ missing }}").render() == ""291 pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)292 assert env.from_string("{{ missing|list }}").render() == "[]"293 assert env.from_string("{{ missing is not defined }}").render() == "True"294 assert env.from_string("{{ foo.missing }}").render(foo=42) == ""295 assert env.from_string("{{ not missing }}").render() == "True"296 assert _messages == [298- "W:Template variable warning: missing is undefined",297+ "W:Template variable warning: 'missing' is undefined",298 "E:Template variable error: 'missing' is undefined",300- "W:Template variable warning: missing is undefined",301- "W:Template variable warning: int object has no attribute missing",302- "W:Template variable warning: missing is undefined",299+ "W:Template variable warning: 'missing' is undefined",300+ "W:Template variable warning: 'int object' has no attribute 'missing'",301+ "W:Template variable warning: 'missing' is undefined",302 ]303 304 def test_default_undefined(self):305 env = Environment(undefined=Undefined)307- assert env.from_string("{{ missing }}").render() == u""306+ assert env.from_string("{{ missing }}").render() == ""307 pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)308 assert env.from_string("{{ missing|list }}").render() == "[]"309 assert env.from_string("{{ missing is not defined }}").render() == "True"310 assert env.from_string("{{ foo.missing }}").render(foo=42) == ""9 unmodified lines320 321 def test_chainable_undefined(self):322 env = Environment(undefined=ChainableUndefined)323 # The following tests are copied from test_default_undefined325- assert env.from_string("{{ missing }}").render() == u""324+ assert env.from_string("{{ missing }}").render() == ""325 assert env.from_string("{{ missing|list }}").render() == "[]"326 assert env.from_string("{{ missing is not defined }}").render() == "True"327 assert env.from_string("{{ foo.missing }}").render(foo=42) == ""328 assert env.from_string("{{ not missing }}").render() == "True"1 unmodified line330 with pytest.raises(AttributeError):331 getattr(ChainableUndefined, "__slots__") # noqa: B009332 333 # The following tests ensure subclass functionality works as expected335- assert env.from_string('{{ missing.bar["baz"] }}').render() == u""334+ assert env.from_string('{{ missing.bar["baz"] }}').render() == ""335+ assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() == "foo"336 assert (337- env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() == u"foo"338- )339- assert (337 env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(foo=42)341- == u"bar"338+ == "bar"339 )340 assert (341 env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(342 foo={"bar": 42}343 )347- == u"baz"344+ == "baz"345 )346 347 def test_debug_undefined(self):348 env = Environment(undefined=DebugUndefined)2 unmodified lines351 assert env.from_string("{{ missing|list }}").render() == "[]"352 assert env.from_string("{{ missing is not defined }}").render() == "True"353 assert (354 env.from_string("{{ foo.missing }}").render(foo=42)358- == u"{{ no such element: int object['missing'] }}"355+ == "{{ no such element: int object['missing'] }}"356 )357 assert env.from_string("{{ not missing }}").render() == "True"358 undefined_hint = "this is testing undefined hint of DebugUndefined"359 assert (360 str(DebugUndefined(hint=undefined_hint))364- == u"{{ undefined value printed: %s }}" % undefined_hint361+ == f"{{{{ undefined value printed: {undefined_hint} }}}}"362 )363 with pytest.raises(AttributeError):364 getattr(DebugUndefined, "__slots__") # noqa: B009365 31 unmodified lines397 398 399 @pytest.mark.api400 @pytest.mark.lowlevel404-class TestLowLevel(object):401+class TestLowLevel:402 def test_custom_code_generator(self):403 class CustomCodeGenerator(CodeGenerator):404 def visit_Const(self, node, frame=None):405 # This method is pure nonsense, but works fine for testing...406 if node.value == "foo":407 self.write(repr("bar"))408 else:412- super(CustomCodeGenerator, self).visit_Const(node, frame)409+ super().visit_Const(node, frame)410 411 class CustomEnvironment(Environment):412 code_generator_class = CustomCodeGenerator413 15 unmodified linesmodified:tests/test_async.py+4 added-5 removed
129 unmodified lines130 return env131 132 133 @pytest.mark.imports134-class TestAsyncImports(object):134+class TestAsyncImports:135 def test_context_imports(self, test_env_async):136 t = test_env_async.from_string('{% import "module" as m %}{{ m.test() }}')137 assert t.render(foo=42) == "[|23]"138 t = test_env_async.from_string(42 unmodified lines181 182 183 @pytest.mark.imports184 @pytest.mark.includes185-class TestAsyncIncludes(object):185+class TestAsyncIncludes:186 def test_context_include(self, test_env_async):187 t = test_env_async.from_string('{% include "header" %}')188 assert t.render(foo=42) == "[42|23]"189 t = test_env_async.from_string('{% include "header" with context %}')90 unmodified lines280 281 282 @pytest.mark.core_tags283 @pytest.mark.for_loop284-class TestAsyncForLoop(object):284+class TestAsyncForLoop:285 def test_simple(self, test_env_async):286 tmpl = test_env_async.from_string("{% for item in seq %}{{ item }}{% endfor %}")287 assert tmpl.render(seq=list(range(10))) == "0123456789"288 55 unmodified lines344 assert not output345 346 def test_varlen(self, test_env_async):347 def inner():348- for item in range(5):349- yield item348+ yield from range(5)349 350 tmpl = test_env_async.from_string(351 "{% for item in iter %}{{ item }}{% endfor %}"352 )232 unmodified linesmodified:tests/test_bytecode_cache.py+3 added-4 removed
1-# -*- coding: utf-8 -*-1 import pytest2 3 from jinja2 import Environment4 from jinja2.bccache import Bucket8 unmodified lines13 return Environment(loader=package_loader, bytecode_cache=bytecode_cache)14 15 16 @pytest.mark.byte_code_cache18-class TestByteCodeCache(object):17+class TestByteCodeCache:18 def test_simple(self, env):19 tmpl = env.get_template("test.html")20 assert tmpl.render().strip() == "BAR"21 pytest.raises(TemplateNotFound, env.get_template, "missing.html")22 23 25-class MockMemcached(object):24+class MockMemcached:25 class Error(Exception):26 pass27 28 key = None14 unmodified lines43 def set_side_effect(self, *args):44 raise self.Error()45 46 48-class TestMemcachedBytecodeCache(object):47+class TestMemcachedBytecodeCache:48 def test_dump_load(self):49 memcached = MockMemcached()50 m = MemcachedBytecodeCache(memcached)51 27 unmodified linesmodified:tests/test_core_tags.py+11 added-18 removed
1-# -*- coding: utf-8 -*-1 import pytest2 3 from jinja2 import DictLoader4 from jinja2 import Environment8 unmodified lines13 14 15 @pytest.mark.core_tags16 @pytest.mark.for_loop18-class TestForLoop(object):17+class TestForLoop:18 def test_simple(self, env):19 tmpl = env.from_string("{% for item in seq %}{{ item }}{% endfor %}")20 assert tmpl.render(seq=list(range(10))) == "0123456789"21 79 unmodified lines101 output = tmpl.render(seq=list(range(10)))102 assert not output103 104 def test_varlen(self, env):106- def inner():107- for item in range(5):108- yield item109-105 tmpl = env.from_string("{% for item in iter %}{{ item }}{% endfor %}")111- output = tmpl.render(iter=inner())106+ output = tmpl.render(iter=range(5))107 assert output == "01234"108 109 def test_noniter(self, env):110 tmpl = env.from_string("{% for item in none %}...{% endfor %}")190 unmodified lines301 302 303 @pytest.mark.core_tags304 @pytest.mark.if_condition310-class TestIfCondition(object):305+class TestIfCondition:306 def test_simple(self, env):307 tmpl = env.from_string("""{% if true %}...{% endif %}""")308 assert tmpl.render() == "..."309 4 unmodified lines314 )315 assert tmpl.render() == "..."316 317 def test_elif_deep(self, env):323- elifs = "\n".join("{{% elif a == {0} %}}{0}".format(i) for i in range(1, 1000))324- tmpl = env.from_string(325- "{{% if a == 0 %}}0{0}{{% else %}}x{{% endif %}}".format(elifs)326- )318+ elifs = "\n".join(f"{{% elif a == {i} %}}{i}" for i in range(1, 1000))319+ tmpl = env.from_string(f"{{% if a == 0 %}}0{elifs}{{% else %}}x{{% endif %}}")320 for x in (0, 10, 999):321 assert tmpl.render(a=x).strip() == str(x)322 assert tmpl.render(a=1000).strip() == "x"323 19 unmodified lines343 344 345 @pytest.mark.core_tags346 @pytest.mark.macros354-class TestMacros(object):347+class TestMacros:348 def test_simple(self, env_trim):349 tmpl = env_trim.from_string(350 """\351 {% macro say_hello(name) %}Hello {{ name }}!{% endmacro %}117 unmodified lines469 470 471 @pytest.mark.core_tags472 @pytest.mark.set480-class TestSet(object):473+class TestSet:474 def test_normal(self, env_trim):475 tmpl = env_trim.from_string("{% set foo = 1 %}{{ foo }}")476 assert tmpl.render() == "1"477 assert tmpl.module.foo == 1478 479 def test_block(self, env_trim):480 tmpl = env_trim.from_string("{% set foo %}42{% endset %}{{ foo }}")481 assert tmpl.render() == "42"489- assert tmpl.module.foo == u"42"482+ assert tmpl.module.foo == "42"483 484 def test_block_escaping(self):485 env = Environment(autoescape=True)486 tmpl = env.from_string(70 unmodified lines557 tmpl = env_trim.from_string(558 "{% set foo | trim | length | string %} 42 {% endset %}{{ foo }}"559 )560 assert tmpl.render() == "2"568- assert tmpl.module.foo == u"2"561+ assert tmpl.module.foo == "2"562 563 def test_block_filtered_set(self, env_trim):564 def _myfilter(val, arg):565 assert arg == " xxx "7 unmodified lines573 "{% endset %}"574 "{{ foo }}"575 )576 assert tmpl.render() == "11"584- assert tmpl.module.foo == u"11"577+ assert tmpl.module.foo == "11"578 579 580 @pytest.mark.core_tags581 @pytest.mark.with_589-class TestWith(object):582+class TestWith:583 def test_with(self, env):584 tmpl = env.from_string(585 """\586 {% with a=42, b=23 -%}19 unmodified linesmodified:tests/test_debug.py+4 added-6 removed
1-# -*- coding: utf-8 -*-1 import pickle2 import re3 from traceback import format_exception4 11 unmodified lines16 return Environment(loader=filesystem_loader)17 18 19 @pytest.mark.debug21-class TestDebug(object):20+class TestDebug:21 def assert_traceback_matches(self, callback, expected_tb):22 with pytest.raises(Exception) as exc_info:23 callback()24 25 tb = format_exception(exc_info.type, exc_info.value, exc_info.tb)26 m = re.search(expected_tb.strip(), "".join(tb))28- assert m is not None, "Traceback did not match:\n\n%s\nexpected:\n%s" % (29- "".join(tb),30- expected_tb,31- )27+ assert (28+ m is not None29+ ), "Traceback did not match:\n\n{''.join(tb)}\nexpected:\n{expected_tb}"30 31 def test_runtime_error(self, fs_env):32 def test():33 tmpl.render(fail=lambda: 1 / 0)82 unmodified linesmodified:tests/test_ext.py+43 added-48 removed
1-# -*- coding: utf-8 -*-1 import re2 from io import BytesIO3 4 import pytest45 unmodified lines50 51 52 languages = {53 "de": {55- "missing": u"fehlend",56- "watch out": u"pass auf",57- "One user online": u"Ein Benutzer online",58- "%(user_count)s users online": u"%(user_count)s Benutzer online",59- "User: %(num)s": u"Benutzer: %(num)s",60- "User: %(count)s": u"Benutzer: %(count)s",61- "%(num)s apple": u"%(num)s Apfel",62- "%(num)s apples": u"%(num)s Äpfel",54+ "missing": "fehlend",55+ "watch out": "pass auf",56+ "One user online": "Ein Benutzer online",57+ "%(user_count)s users online": "%(user_count)s Benutzer online",58+ "User: %(num)s": "Benutzer: %(num)s",59+ "User: %(count)s": "Benutzer: %(count)s",60+ "%(num)s apple": "%(num)s Apfel",61+ "%(num)s apples": "%(num)s Äpfel",62 }63 }64 65 27 unmodified lines93 newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)94 95 96 class ExampleExtension(Extension):98- tags = set(["test"])97+ tags = {"test"}98 ext_attr = 4299 context_reference_node_cls = nodes.ContextReference100 101 def parse(self, parser):11 unmodified lines113 ]114 ).set_lineno(next(parser.stream).lineno)115 116 def _dump(self, sandboxed, ext_attr, imported_object, context):118- return "%s|%s|%s|%s|%s" % (119- sandboxed,120- ext_attr,121- imported_object,122- context.blocks,123- context.get("test_var"),117+ return (118+ f"{sandboxed}|{ext_attr}|{imported_object}|{context.blocks}"119+ f"|{context.get('test_var')}"120 )121 122 123 class DerivedExampleExtension(ExampleExtension):8 unmodified lines132 class StreamFilterExtension(Extension):133 def filter_stream(self, stream):134 for token in stream:135 if token.type == "data":140- for t in self.interpolate(token):141- yield t136+ yield from self.interpolate(token)137 else:138 yield token139 140 def interpolate(self, token):19 unmodified lines160 yield Token(lineno, "data", token.value[pos:])161 162 163 @pytest.mark.ext169-class TestExtensions(object):164+class TestExtensions:165 def test_extend_late(self):166 env = Environment()167 env.add_extension("jinja2.ext.autoescape")168 t = env.from_string('{% autoescape true %}{{ "<test>" }}{% endautoescape %}')87 unmodified lines256 t = env.from_string("Hello\n{% debug %}\nGoodbye")257 out = t.render()258 259 for value in ("context", "cycler", "filters", "abs", "tests", "!="):265- assert "'{}'".format(value) in out260+ assert f"'{value}'" in out261 262 263 @pytest.mark.ext269-class TestInternationalization(object):264+class TestInternationalization:265 def test_trans(self):266 tmpl = i18n_env.get_template("child.html")267 assert tmpl.render(LANGUAGE="de") == "<title>fehlend</title>pass auf"268 72 unmodified lines341 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}342 """343 )344 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], {})) == [350- (2, "gettext", u"Hello World", []),351- (3, "gettext", u"Hello World", []),352- (4, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),345+ (2, "gettext", "Hello World", []),346+ (3, "gettext", "Hello World", []),347+ (4, "ngettext", ("%(users)s user", "%(users)s users", None), []),348 ]349 350 def test_extract_trimmed(self):351 from jinja2.ext import babel_extract6 unmodified lines358 {%- pluralize %}{{ users }} \n users{% endtrans %}359 """360 )361 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], {})) == [367- (2, "gettext", u" Hello \n World", []),368- (4, "gettext", u"Hello World", []),369- (6, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),362+ (2, "gettext", " Hello \n World", []),363+ (4, "gettext", "Hello World", []),364+ (6, "ngettext", ("%(users)s user", "%(users)s users", None), []),365 ]366 367 def test_extract_trimmed_option(self):368 from jinja2.ext import babel_extract7 unmodified lines376 """377 )378 opts = {"trimmed": "true"}379 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], opts)) == [385- (2, "gettext", u" Hello \n World", []),386- (4, "gettext", u"Hello World", []),387- (6, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),380+ (2, "gettext", " Hello \n World", []),381+ (4, "gettext", "Hello World", []),382+ (6, "ngettext", ("%(users)s user", "%(users)s users", None), []),383 ]384 385 def test_comment_extract(self):386 from jinja2.ext import babel_extract9 unmodified lines396 )397 assert list(398 babel_extract(source, ("gettext", "ngettext", "_"), ["trans", ":"], {})399 ) == [405- (3, "gettext", u"Hello World", ["first"]),406- (4, "gettext", u"Hello World", ["second"]),407- (6, "ngettext", (u"%(users)s user", u"%(users)s users", None), ["third"]),400+ (3, "gettext", "Hello World", ["first"]),401+ (4, "gettext", "Hello World", ["second"]),402+ (6, "ngettext", ("%(users)s user", "%(users)s users", None), ["third"]),403 ]404 405 406 @pytest.mark.ext412-class TestScope(object):407+class TestScope:408 def test_basic_scope_behavior(self):409 # This is what the old with statement compiled down to410 class ScopeExt(Extension):416- tags = set(["scope"])411+ tags = {"scope"}412 413 def parse(self, parser):414 node = nodes.Scope(lineno=next(parser.stream).lineno)415 assignments = []21 unmodified lines437 assert tmpl.render(b=3, e=4) == "1|2|2|4|5"438 439 440 @pytest.mark.ext446-class TestNewstyleInternationalization(object):441+class TestNewstyleInternationalization:442 def test_trans(self):443 tmpl = newstyle_i18n_env.get_template("child.html")444 assert tmpl.render(LANGUAGE="de") == "<title>fehlend</title>pass auf"445 20 unmodified lines466 467 def test_newstyle_plural(self):468 tmpl = newstyle_i18n_env.get_template("ngettext.html")469 assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apfel"475- assert tmpl.render(LANGUAGE="de", apples=5) == u"5 Äpfel"470+ assert tmpl.render(LANGUAGE="de", apples=5) == "5 Äpfel"471 472 def test_autoescape_support(self):473 env = Environment(extensions=["jinja2.ext.autoescape", "jinja2.ext.i18n"])474 env.install_gettext_callables(480- lambda x: u"<strong>Wert: %(name)s</strong>",475+ lambda x: "<strong>Wert: %(name)s</strong>",476 lambda s, p, n: s,477 newstyle=True,478 )479 t = env.from_string(12 unmodified lines492 assert env.from_string(template).render() == "<html>"493 494 def test_num_used_twice(self):495 tmpl = newstyle_i18n_env.get_template("ngettext_long.html")501- assert tmpl.render(apples=5, LANGUAGE="de") == u"5 Äpfel"496+ assert tmpl.render(apples=5, LANGUAGE="de") == "5 Äpfel"497 498 def test_num_called_num(self):499 source = newstyle_i18n_env.compile(500 """6 unmodified lines507 # that the generated code does not pass num twice (although that508 # would work) for better performance. This only works on the509 # newstyle gettext of course510 assert (516- re.search(r"u?'\%\(num\)s apple', u?'\%\(num\)s " r"apples', 3", source)511+ re.search(r"u?'%\(num\)s apple', u?'%\(num\)s apples', 3", source)512 is not None513 )514 515 def test_trans_vars(self):13 unmodified lines529 assert t.render() == "%(foo)s"530 531 532 @pytest.mark.ext538-class TestAutoEscape(object):533+class TestAutoEscape:534 def test_scoped_setting(self):535 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)536 tmpl = env.from_string(537 """4 unmodified lines542 {{ "<HelloWorld>" }}543 """544 )545 assert tmpl.render().split() == [551- u"<HelloWorld>",552- u"<HelloWorld>",553- u"<HelloWorld>",546+ "<HelloWorld>",547+ "<HelloWorld>",548+ "<HelloWorld>",549 ]550 551 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=False)552 tmpl = env.from_string(5 unmodified lines558 {{ "<HelloWorld>" }}559 """560 )561 assert tmpl.render().split() == [567- u"<HelloWorld>",568- u"<HelloWorld>",569- u"<HelloWorld>",562+ "<HelloWorld>",563+ "<HelloWorld>",564+ "<HelloWorld>",565 ]566 567 def test_nonvolatile(self):568 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)48 unmodified lines617 assert "<testing>\\n" in pysource618 619 def test_overlay_scopes(self):620 class MagicScopeExtension(Extension):626- tags = set(["overlay"])621+ tags = {"overlay"}622 623 def parse(self, parser):624 node = nodes.OverlayScope(lineno=next(parser.stream).lineno)625 node.body = list(20 unmodified linesmodified:tests/test_features.py+2 added-1 removed
1 unmodified line2 3 from jinja2 import Template4 5 6+# Python < 3.77 def test_generator_stop():7- class X(object):8+ class X:9 def __getattr__(self, name):10 raise StopIteration()11 12 t = Template("a{{ bad.bar() }}b")2 unmodified linesmodified:tests/test_filters.py+20 added-22 removed
1-# -*- coding: utf-8 -*-1 import random2 from collections import namedtuple3 4 import pytest1 unmodified line6 from jinja2 import Environment7 from jinja2 import Markup8 9 11-class Magic(object):10+class Magic:11 def __init__(self, value):12 self.value = value13 14 def __str__(self):15 return str(self.value)16 17 19-class Magic2(object):18+class Magic2:19 def __init__(self, value1, value2):20 self.value1 = value121 self.value2 = value222 23 def __str__(self):25- return u"(%s,%s)" % (str(self.value1), str(self.value2))24+ return f"({self.value1},{self.value2})"25 26 27 @pytest.mark.filter29-class TestFilter(object):28+class TestFilter:29 def test_filter_calling(self, env):30 rv = env.call_filter("sum", [1, 2, 3])31 assert rv == 632 21 unmodified lines54 ("reverse=true", "[('c', 2), ('b', 1), ('AB', 3), ('aa', 0)]"),55 ),56 )57 def test_dictsort(self, env, args, expect):59- t = env.from_string("{{{{ foo|dictsort({args}) }}}}".format(args=args))58+ t = env.from_string(f"{{{{ foo|dictsort({args}) }}}}")59 out = t.render(foo={"aa": 0, "b": 1, "c": 2, "AB": 3})60 assert out == expect61 62 def test_batch(self, env):74 unmodified lines137 out = tmpl.render(foo=list(range(10)))138 assert out == "0"139 140 @pytest.mark.parametrize(142- ("value", "expect"), (("42", "42.0"), ("abc", "0.0"), ("32.32", "32.32"),)141+ ("value", "expect"), (("42", "42.0"), ("abc", "0.0"), ("32.32", "32.32"))142 )143 def test_float(self, env, value, expect):145- t = env.from_string("{{ '%s'|float }}" % value)146- assert t.render() == expect144+ t = env.from_string("{{ value|float }}")145+ assert t.render(value=value) == expect146 147 def test_float_default(self, env):148 t = env.from_string("{{ value|float(default=1.0) }}")149 assert t.render(value="abc") == "1.0"150 151 def test_format(self, env):153- tmpl = env.from_string("""{{ "%s|%s"|format("a", "b") }}""")152+ tmpl = env.from_string("{{ '%s|%s'|format('a', 'b') }}")153 out = tmpl.render()154 assert out == "a|b"155 156 @staticmethod34 unmodified lines191 ("12345678901234567890", "12345678901234567890"),192 ),193 )194 def test_int(self, env, value, expect):196- t = env.from_string("{{ '%s'|int }}" % value)197- assert t.render() == expect195+ t = env.from_string("{{ value|int }}")196+ assert t.render(value=value) == expect197 198 @pytest.mark.parametrize(199 ("value", "base", "expect"),200 (("0x4d32", 16, "19762"), ("011", 8, "9"), ("0x33Z", 16, "0"),),201 )202 def test_int_base(self, env, value, base, expect):204- t = env.from_string("{{ '%s'|int(base=%d) }}" % (value, base))205- assert t.render() == expect203+ t = env.from_string("{{ value|int(base=base) }}")204+ assert t.render(value=value, base=base) == expect205 206 def test_int_default(self, env):207 t = env.from_string("{{ value|int(default=1) }}")208 assert t.render(value="abc") == "1"209 210 def test_int_special_method(self, env):212- class IntIsh(object):211+ class IntIsh:212 def __int__(self):213 return 42214 215 t = env.from_string("{{ value|int }}")100 unmodified lines316 '{{ data|truncate(15, false, ">>>") }}|'317 "{{ smalldata|truncate(15) }}"318 )319 out = tmpl.render(data="foobar baz bar" * 1000, smalldata="foobar baz bar")321- msg = "Current output: %s" % out322- assert out == "foobar baz b>>>|foobar baz>>>|foobar baz bar", msg320+ assert out == "foobar baz b>>>|foobar baz>>>|foobar baz bar"321 322 def test_truncate_very_short(self, env):323 tmpl = env.from_string(324 '{{ "foo bar baz"|truncate(9) }}|{{ "foo bar baz"|truncate(9, true) }}'325 )326 out = tmpl.render()329- assert out == "foo bar baz|foo bar baz", out327+ assert out == "foo bar baz|foo bar baz"328 329 def test_truncate_end_length(self, env):330 tmpl = env.from_string('{{ "Joel is a slug"|truncate(7, true) }}')331 out = tmpl.render()334- assert out == "Joel...", "Current output: %s" % out332+ assert out == "Joel..."333 334 def test_upper(self, env):335 tmpl = env.from_string('{{ "foo"|upper }}')336 assert tmpl.render() == "FOO"240 unmodified lines577 assert tmpl.render(string=Markup("foo")) == "f>x<>x<"578 579 def test_forceescape(self, env):580 tmpl = env.from_string("{{ x|forceescape }}")583- assert tmpl.render(x=Markup("<div />")) == u"<div />"581+ assert tmpl.render(x=Markup("<div />")) == "<div />"582 583 def test_safe(self, env):584 env = Environment(autoescape=True)585 tmpl = env.from_string('{{ "<div>foo</div>"|safe }}')4 unmodified lines590 @pytest.mark.parametrize(591 ("value", "expect"),592 [593 ("Hello, world!", "Hello%2C%20world%21"),596- (u"Hello, world\u203d", "Hello%2C%20world%E2%80%BD"),594+ ("Hello, world\u203d", "Hello%2C%20world%E2%80%BD"),595 ({"f": 1}, "f=1"),596 ([("f", 1), ("z", 2)], "f=1&z=2"),599- ({u"\u203d": 1}, "%E2%80%BD=1"),597+ ({"\u203d": 1}, "%E2%80%BD=1"),598 ({0: 1}, "0=1"),599 ([("a b/c", "a b/c")], "a+b%2Fc=a+b%2Fc"),600 ("a b/c", "a%20b/c"),601 ],138 unmodified linesmodified:tests/test_idtracking.py+19 added-19 removed
36 unmodified lines37 38 39 def test_complex():40 title_block = nodes.Block(41- "title", [nodes.Output([nodes.TemplateData(u"Page Title")])], False41+ "title", [nodes.Output([nodes.TemplateData("Page Title")])], False42 )43 44 render_title_macro = nodes.Macro(45 "render_title",1 unmodified line47 [],48 [49 nodes.Output(50 [51- nodes.TemplateData(u'\n <div class="title">\n <h1>'),51+ nodes.TemplateData('\n <div class="title">\n <h1>'),52 nodes.Name("title", "load"),53- nodes.TemplateData(u"</h1>\n <p>"),53+ nodes.TemplateData("</h1>\n <p>"),54 nodes.Name("subtitle", "load"),55- nodes.TemplateData(u"</p>\n "),55+ nodes.TemplateData("</p>\n "),56 ]57 ),58 nodes.Assign(59 nodes.Name("subtitle", "store"), nodes.Const("something else")60 ),61 nodes.Output(62 [63- nodes.TemplateData(u"\n <p>"),63+ nodes.TemplateData("\n <p>"),64 nodes.Name("subtitle", "load"),65- nodes.TemplateData(u"</p>\n </div>\n"),65+ nodes.TemplateData("</p>\n </div>\n"),66 nodes.If(67 nodes.Name("something", "load"),68 [69 nodes.Assign(33 unmodified lines103 nodes.Name("seq", "load"),104 [105 nodes.Output(106 [107- nodes.TemplateData(u"\n <li>"),107+ nodes.TemplateData("\n <li>"),108 nodes.Name("item", "load"),109- nodes.TemplateData(u"</li>\n <span>"),109+ nodes.TemplateData("</li>\n <span>"),110 ]111 ),112 nodes.Include(nodes.Const("helper.html"), True, False),113- nodes.Output([nodes.TemplateData(u"</span>\n ")]),113+ nodes.Output([nodes.TemplateData("</span>\n ")]),114 ],115 [],116 None,117 False,3 unmodified lines121 "body",122 [123 nodes.Output(124 [125- nodes.TemplateData(u"\n "),125+ nodes.TemplateData("\n "),126 nodes.Call(127 nodes.Name("render_title", "load"),128 [nodes.Name("item", "load")],129 [],130 None,131 None,132 ),133- nodes.TemplateData(u"\n <ul>\n "),133+ nodes.TemplateData("\n <ul>\n "),134 ]135 ),136 for_loop,137- nodes.Output([nodes.TemplateData(u"\n </ul>\n")]),137+ nodes.Output([nodes.TemplateData("\n </ul>\n")]),138 ],139 False,140 )141 12 unmodified lines154 }155 assert tmpl_sym.loads == {156 "l_0_render_title": ("undefined", None),157 }158- assert tmpl_sym.stores == set(["render_title"])158+ assert tmpl_sym.stores == {"render_title"}159 assert tmpl_sym.dump_stores() == {160 "render_title": "l_0_render_title",161 }162 9 unmodified lines172 "l_1_something": ("resolve", "something"),173 "l_1_title": ("param", None),174 "l_1_title_upper": ("resolve", "title_upper"),175 }176- assert macro_sym.stores == set(["title", "title_upper", "subtitle"])176+ assert macro_sym.stores == {"title", "title_upper", "subtitle"}177 assert macro_sym.find_ref("render_title") == "l_0_render_title"178 assert macro_sym.dump_stores() == {179 "title": "l_1_title",180 "title_upper": "l_1_title_upper",11 unmodified lines192 "l_0_item": ("resolve", "item"),193 "l_0_seq": ("resolve", "seq"),194 "l_0_render_title": ("resolve", "render_title"),195 }196- assert body_sym.stores == set([])196+ assert body_sym.stores == set()197 198 for_sym = symbols_for_node(for_loop, body_sym)199 assert for_sym.refs == {200 "item": "l_1_item",201 }202 assert for_sym.loads == {203 "l_1_item": ("param", None),204 }205- assert for_sym.stores == set(["item"])205+ assert for_sym.stores == {"item"}206 assert for_sym.dump_stores() == {207 "item": "l_1_item",208 }209 11 unmodified lines221 )222 223 sym = symbols_for_node(tmpl)224 assert sym.refs == {"variable": "l_0_variable", "expression": "l_0_expression"}225- assert sym.stores == set(["variable"])225+ assert sym.stores == {"variable"}226 assert sym.loads == {227 "l_0_variable": ("resolve", "variable"),228 "l_0_expression": ("resolve", "expression"),229 }16 unmodified lines246 )247 248 sym = symbols_for_node(tmpl)249 assert sym.refs == {"variable": "l_0_variable", "expression": "l_0_expression"}250- assert sym.stores == set(["variable"])250+ assert sym.stores == {"variable"}251 assert sym.loads == {252 "l_0_variable": ("undefined", None),253 "l_0_expression": ("resolve", "expression"),254 }25 unmodified lines280 )281 282 tmpl_sym = symbols_for_node(tmpl)283 for_sym = symbols_for_node(for_loop, tmpl_sym)284- assert for_sym.stores == set(["item", "x"])284+ assert for_sym.stores == {"item", "x"}285 assert for_sym.loads == {286 "l_1_x": ("alias", "l_0_x"),287 "l_1_item": ("param", None),288 "l_1_expression": ("resolve", "expression"),1 unmodified linemodified:tests/test_imports.py+11 added-5 removed
1-# -*- coding: utf-8 -*-1 import pytest2 4-from jinja2 import DictLoader5-from jinja2 import Environment3+from jinja2.environment import Environment4 from jinja2.exceptions import TemplateNotFound5 from jinja2.exceptions import TemplatesNotFound6 from jinja2.exceptions import TemplateSyntaxError7+from jinja2.exceptions import UndefinedError8+from jinja2.loaders import DictLoader9 10 11 @pytest.fixture12 def test_env():10 unmodified lines23 return env24 25 26 @pytest.mark.imports27-class TestImports(object):27+class TestImports:28 def test_context_imports(self, test_env):29 t = test_env.from_string('{% import "module" as m %}{{ m.test() }}')30 assert t.render(foo=42) == "[|23]"31 t = test_env.from_string(60 unmodified lines92 assert not hasattr(m, "__missing")93 assert m.variable == 4294 assert not hasattr(m, "notthere")95 96+ def test_not_exported(self, test_env):97+ t = test_env.from_string("{% from 'module' import nothing %}{{ nothing() }}")98 99+ with pytest.raises(UndefinedError, match="does not export the requested name"):100+ t.render()101+102+103 @pytest.mark.imports104 @pytest.mark.includes99-class TestIncludes(object):105+class TestIncludes:106 def test_context_include(self, test_env):107 t = test_env.from_string('{% include "header" %}')108 assert t.render(foo=42) == "[42|23]"109 t = test_env.from_string('{% include "header" with context %}')76 unmodified linesmodified:tests/test_inheritance.py+4 added-5 removed
1-# -*- coding: utf-8 -*-1 import pytest2 3 from jinja2 import DictLoader4 from jinja2 import Environment68 unmodified lines73 )74 75 76 @pytest.mark.inheritance78-class TestInheritance(object):77+class TestInheritance:78 def test_layout(self, env):79 tmpl = env.get_template("layout")80 assert tmpl.render() == (81 "|block 1 from layout|block 2 from layout|nested block 4 from layout|"74 unmodified lines156 )157 )158 tmpl = env.get_template("child")159 for m in range(1, 3):161- assert tmpl.render(master="master%d" % m) == "MASTER%dCHILD" % m160+ assert tmpl.render(master=f"master{m}") == f"MASTER{m}CHILD"161 162 def test_multi_inheritance(self, env):163 env = Environment(164 loader=DictLoader(67 unmodified lines232 assert rv == ["43", "44", "45"]233 234 235 @pytest.mark.inheritance237-class TestBugFix(object):236+class TestBugFix:237 def test_fixed_macro_scoping_bug(self, env):238 assert (239 Environment(240 loader=DictLoader(33 unmodified lines274 )275 .get_template("test.html")276 .render()277 .split()279- == [u"outer_box", u"my_macro"]278+ == ["outer_box", "my_macro"]279 )280 281 def test_double_extends(self, env):282 """Ensures that a template with more than 1 {% extends ... %} usage4 unmodified linesmodified:tests/test_lexnparse.py+42 added-53 removed
1-# -*- coding: utf-8 -*-1 import pytest2 3 from jinja2 import Environment4 from jinja2 import nodes8 unmodified lines13 14 15 @pytest.mark.lexnparse16 @pytest.mark.tokenstream18-class TestTokenStream(object):17+class TestTokenStream:18 test_tokens = [19 Token(1, TOKEN_BLOCK_BEGIN, ""),20 Token(2, TOKEN_BLOCK_END, ""),21 ]21 unmodified lines43 44 45 @pytest.mark.lexnparse46 @pytest.mark.lexer48-class TestLexer(object):47+class TestLexer:48 def test_raw1(self, env):49 tmpl = env.from_string(50 "{% raw %}foo{% endraw %}|"51 "{%raw%}{{ bar }}|{% baz %}{% endraw %}"42 unmodified lines94 "<ul>\n <li>0</li>\n <li>1</li>\n <li>2</li>\n</ul>"95 )96 97 def test_string_escapes(self, env):99- for char in u"\0", u"\u2668", u"\xe4", u"\t", u"\r", u"\n":100- tmpl = env.from_string("{{ %s }}" % repr(char))98+ for char in "\0", "\u2668", "\xe4", "\t", "\r", "\n":99+ tmpl = env.from_string(f"{{{{ {char!r} }}}}")100 assert tmpl.render() == char102- assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == u"\u2668"101+ assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == "\u2668"102 103 def test_bytefallback(self, env):104 from pprint import pformat105 107- tmpl = env.from_string(u"""{{ 'foo'|pprint }}|{{ 'bär'|pprint }}""")108- assert tmpl.render() == pformat("foo") + "|" + pformat(u"bär")106+ tmpl = env.from_string("""{{ 'foo'|pprint }}|{{ 'bär'|pprint }}""")107+ assert tmpl.render() == pformat("foo") + "|" + pformat("bär")108 109 def test_operators(self, env):110 from jinja2.lexer import operators111 112 for test, expect in operators.items():113 if test in "([{}])":114 continue116- stream = env.lexer.tokenize("{{ %s }}" % test)115+ stream = env.lexer.tokenize(f"{{{{ {test} }}}}")116 next(stream)117 assert stream.current.type == expect118 119 def test_normalizing(self, env):19 unmodified lines139 140 @pytest.mark.parametrize(141 ("name", "valid"),142 [144- (u"foo", True),145- (u"föö", True),146- (u"き", True),147- (u"_", True),148- (u"1a", False), # invalid ascii start149- (u"a-", False), # invalid ascii continue150- (u"🐍", False), # invalid unicode start151- (u"a🐍", False), # invalid unicode continue143+ ("foo", True),144+ ("föö", True),145+ ("き", True),146+ ("_", True),147+ ("1a", False), # invalid ascii start148+ ("a-", False), # invalid ascii continue149+ ("\U0001f40da", False), # invalid unicode start150+ ("a🐍\U0001f40d", False), # invalid unicode continue151 # start characters not matched by \w153- (u"\u1885", True),154- (u"\u1886", True),155- (u"\u2118", True),156- (u"\u212e", True),152+ ("\u1885", True),153+ ("\u1886", True),154+ ("\u2118", True),155+ ("\u212e", True),156 # continue character not matched by \w158- (u"\xb7", False),159- (u"a\xb7", True),157+ ("\xb7", False),158+ ("a\xb7", True),159 ],160 )161 def test_name(self, env, name, valid):163- t = u"{{ " + name + u" }}"162+ t = "{{ " + name + " }}"163 164 if valid:165 # valid for version being tested, shouldn't raise166 env.from_string(t)2 unmodified lines169 170 171 @pytest.mark.lexnparse172 @pytest.mark.parser174-class TestParser(object):173+class TestParser:174 def test_php_syntax(self, env):175 env = Environment("<?", "?>", "<?=", "?>", "<!--", "-->")176 tmpl = env.from_string(177 """\126 unmodified lines304 305 306 @pytest.mark.lexnparse307 @pytest.mark.syntax309-class TestSyntax(object):308+class TestSyntax:309 def test_call(self, env):310 env = Environment()311 env.globals["foo"] = lambda a, b, c, e, g: a + b + c + e + g312 tmpl = env.from_string("{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}")42 unmodified lines355 (4, "!=", 5),356 ],357 )358 def test_compare(self, env, a, op, b):360- t = env.from_string("{{ %d %s %d }}" % (a, op, b))359+ t = env.from_string(f"{{{{ {a} {op} {b} }}}}")360 assert t.render() == "True"361 362 def test_compare_parens(self, env):363 t = env.from_string("{{ i * (j < 5) }}")19 unmodified lines383 assert tmpl.render() == "True|False"384 385 @pytest.mark.parametrize("value", ("[]", "{}", "()"))386 def test_collection_literal(self, env, value):388- t = env.from_string("{{ %s }}" % value)387+ t = env.from_string(f"{{{{ {value} }}}}")388 assert t.render() == value389 390 @pytest.mark.parametrize(391 ("value", "expect"),12 unmodified lines404 ("1_2.3_4e5_6", "1.234e+57"),405 ),406 )407 def test_numeric_literal(self, env, value, expect):409- t = env.from_string("{{ %s }}" % value)408+ t = env.from_string(f"{{{{ {value} }}}}")409 assert t.render() == expect410 411 def test_bool(self, env):412 tmpl = env.from_string(45 unmodified lines458 (False, "foo, *args, bar=23, **baz"),459 ]460 for should_fail, sig in tests:461 if should_fail:463- pytest.raises(464- TemplateSyntaxError, env.from_string, "{{ foo(%s) }}" % sig465- )462+ with pytest.raises(TemplateSyntaxError):463+ env.from_string(f"{{{{ foo({sig}) }}}}")464 else:467- env.from_string("foo(%s)" % sig)465+ env.from_string(f"foo({sig})")466 467 def test_tuple_expr(self, env):468 for tmpl in [469 "{{ () }}",18 unmodified lines488 )489 490 def test_constant_casing(self, env):491 for const in True, False, None:492+ const = str(const)493 tmpl = env.from_string(495- "{{ %s }}|{{ %s }}|{{ %s }}"496- % (str(const), str(const).lower(), str(const).upper())494+ f"{{{{ {const} }}}}|{{{{ {const.lower()} }}}}|{{{{ {const.upper()} }}}}"495 )498- assert tmpl.render() == "%s|%s|" % (const, const)496+ assert tmpl.render() == f"{const}|{const}|"497 498 def test_test_chaining(self, env):499 pytest.raises(500 TemplateSyntaxError, env.from_string, "{{ foo is string is sequence }}"13 unmodified lines514 tmpl = env.from_string("""{{ 2 * 3 + 4 % 2 + 1 - 2 }}""")515 assert tmpl.render() == "5"516 517 def test_implicit_subscribed_tuple(self, env):520- class Foo(object):518+ class Foo:519 def __getitem__(self, x):520 return x521 522 t = env.from_string("{{ foo[1, 2] }}")525- assert t.render(foo=Foo()) == u"(1, 2)"523+ assert t.render(foo=Foo()) == "(1, 2)"524 525 def test_raw2(self, env):526 tmpl = env.from_string("{% raw %}{{ FOO }} and {% BAR %}{% endraw %}")527 assert tmpl.render() == "{{ FOO }} and {% BAR %}"32 unmodified lines560 561 562 @pytest.mark.lexnparse563 @pytest.mark.lstripblocks566-class TestLstripBlocks(object):564+class TestLstripBlocks:565 def test_lstrip(self, env):566 env = Environment(lstrip_blocks=True, trim_blocks=False)567 tmpl = env.from_string(""" {% if True %}\n {% endif %}""")568 assert tmpl.render() == "\n"111 unmodified lines680 <% for item in seq %>681 ${item} ## the rest of the stuff682 <% endfor %>"""683 )686- assert tmpl.render(seq=range(5)) == "".join("%s\n" % x for x in range(5))684+ assert tmpl.render(seq=range(5)) == "".join(f"{x}\n" for x in range(5))685 686 def test_lstrip_angle_bracket_compact(self, env):687 env = Environment(688 "<%",13 unmodified lines702 <%for item in seq%>703 ${item} ## the rest of the stuff704 <%endfor%>"""705 )708- assert tmpl.render(seq=range(5)) == "".join("%s\n" % x for x in range(5))706+ assert tmpl.render(seq=range(5)) == "".join(f"{x}\n" for x in range(5))707 708 def test_php_syntax_with_manual(self, env):709 env = Environment(710 "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True17 unmodified lines728 <? for item in seq ?>729 <?= item ?>730 <? endfor ?>"""731 )734- assert tmpl.render(seq=range(5)) == "".join(735- " %s\n" % x for x in range(5)736- )732+ assert tmpl.render(seq=range(5)) == "".join(f" {x}\n" for x in range(5))733 734 def test_php_syntax_compact(self, env):735 env = Environment(736 "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True4 unmodified lines741 <?for item in seq?>742 <?=item?>743 <?endfor?>"""744 )749- assert tmpl.render(seq=range(5)) == "".join(750- " %s\n" % x for x in range(5)751- )745+ assert tmpl.render(seq=range(5)) == "".join(f" {x}\n" for x in range(5))746 747 def test_erb_syntax(self, env):748 env = Environment(749 "<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True750 )757- # env.from_string('')758- # for n,r in env.lexer.rules.iteritems():759- # print n760- # print env.lexer.rules['root'][0][0].pattern761- # print "'%s'" % tmpl.render(seq=range(5))751 tmpl = env.from_string(752 """\753 <%# I'm a comment, I'm not interesting %>754 <% for item in seq %>755 <%= item %>756 <% endfor %>757 """758 )770- assert tmpl.render(seq=range(5)) == "".join(" %s\n" % x for x in range(5))759+ assert tmpl.render(seq=range(5)) == "".join(f" {x}\n" for x in range(5))760 761 def test_erb_syntax_with_manual(self, env):762 env = Environment(763 "<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True42 unmodified linesmodified:tests/test_loader.py+7 added-8 removed
1-# -*- coding: utf-8 -*-1 import os2 import platform3 import shutil4 import sys10 unmodified lines15 from jinja2.loaders import split_template_path16 17 18 @pytest.mark.loaders20-class TestLoaders(object):19+class TestLoaders:20 def test_dict_loader(self, dict_loader):21 env = Environment(loader=dict_loader)22 tmpl = env.get_template("justdict.html")23 assert tmpl.render().strip() == "FOO"41 unmodified lines65 changed = False66 67 class TestLoader(loaders.BaseLoader):68 def get_source(self, environment, template):70- return u"foo", None, lambda: not changed69+ return "foo", None, lambda: not changed70 71 env = Environment(loader=TestLoader(), cache_size=-1)72 tmpl = env.get_template("template")73 assert tmpl is env.get_template("template")42 unmodified lines116 117 118 @pytest.mark.loaders119 @pytest.mark.filesystemloader121-class TestFileSystemLoader(object):120+class TestFileSystemLoader:121 searchpath = os.path.join(122 os.path.dirname(os.path.abspath(__file__)), "res", "templates"123 )124 41 unmodified lines166 167 @pytest.mark.parametrize(168 ("encoding", "expect"),169 [171- ("utf-8", u"文字化け"),172- ("iso-8859-1", u"æ\x96\x87\xe5\xad\x97\xe5\x8c\x96\xe3\x81\x91"),170+ ("utf-8", "文字化け"),171+ ("iso-8859-1", "æ\x96\x87\xe5\xad\x97\xe5\x8c\x96\xe3\x81\x91"),172 ],173 )174 def test_uses_specified_encoding(self, encoding, expect):175 loader = loaders.FileSystemLoader(self.searchpath, encoding=encoding)3 unmodified lines179 180 181 @pytest.mark.loaders182 @pytest.mark.moduleloader184-class TestModuleLoader(object):183+class TestModuleLoader:184 archive = None185 186 def compile_down(self, prefix_loader, zip="deflated"):187 log = []158 unmodified lines346 347 348 @pytest.mark.xfail(349 platform.python_implementation() == "PyPy",351- reason="PyPy's zipimporter doesn't have a _files attribute.",350+ reason="PyPy's zipimporter doesn't have a '_files' attribute.",351 raises=TypeError,352 )353 def test_package_zip_list(package_zip_loader):354 assert package_zip_loader.list_templates() == ["foo/test.html", "test.html"]modified:tests/test_regression.py+12 added-13 removed
1-# -*- coding: utf-8 -*-1 import pytest2 3 from jinja2 import DictLoader4 from jinja2 import Environment4 unmodified lines9 from jinja2 import TemplateSyntaxError10 11 12 @pytest.mark.regression14-class TestCorner(object):13+class TestCorner:14 def test_assigned_scoping(self, env):15 t = env.from_string(16 """17 {%- for item in (1, 2, 3, 4) -%}63 unmodified lines81 assert t.render(wrapper=23) == "[1][2][3][4]23"82 83 84 @pytest.mark.regression86-class TestBug(object):85+class TestBug:86 def test_keyword_folding(self, env):87 env = Environment()88 env.filters["testing"] = lambda value, some: value + some89 assert (100 unmodified lines190 {{ x }}191 """192 )193 rv = t.render(foo=[1]).strip()195- assert rv == u"1"194+ assert rv == "1"195 196 def test_call_with_args(self, env):197 t = Template(198 """{% macro dump_users(users) -%}25 unmodified lines224 }225 ]226 ).splitlines()227 ] == [229- u"<ul><li><p>apo</p><dl>",230- u"<dl>Realname</dl>",231- u"<dd>something else</dd>",232- u"<dl>Description</dl>",233- u"<dd>test</dd>",234- u"</dl>",235- u"</li></ul>",228+ "<ul><li><p>apo</p><dl>",229+ "<dl>Realname</dl>",230+ "<dd>something else</dd>",231+ "<dl>Description</dl>",232+ "<dd>test</dd>",233+ "</dl>",234+ "</li></ul>",235 ]236 237 def test_empty_if_condition_fails(self, env):238 pytest.raises(TemplateSyntaxError, Template, "{% if %}....{% endif %}")53 unmodified lines292 293 def test_contextfunction_callable_classes(self, env):294 from jinja2.utils import contextfunction295 297- class CallableClass(object):296+ class CallableClass:297 @contextfunction298 def __call__(self, ctx):299 return ctx.resolve("hello")300 292 unmodified lines593 class MyContext(Context):594 def resolve(self, name):595 if name == "foo":596 return 42598- return super(MyContext, self).resolve(name)597+ return super().resolve(name)598 599 x = MyContext(env, parent={"bar": 23}, name="foo", blocks={})600 assert x._legacy_resolve_mode601 assert x.resolve_or_missing("foo") == 4214 unmodified linesmodified:tests/test_runtime.py+1 added-1 removed
60 unmodified lines61 values for arbitrary attrs, it should not be incorrectly identified62 as a ``contextfunction``.63 """64 65- class Calc(object):65+ class Calc:66 def __getattr__(self, item):67 return object()68 69 def __call__(self, *args, **kwargs):6 unmodified linesmodified:tests/test_security.py+9 added-10 removed
1-# -*- coding: utf-8 -*-1 import pytest2 3 from jinja2 import Environment4 from jinja2 import escape5 unmodified lines10 from jinja2.sandbox import SandboxedEnvironment11 from jinja2.sandbox import unsafe12 13 15-class PrivateStuff(object):14+class PrivateStuff:15 def bar(self):16 return 2317 18 @unsafe3 unmodified lines22 def __repr__(self):23 return "PrivateStuff"24 25 27-class PublicStuff(object):26+class PublicStuff:27 def bar(self):28 return 2329 30 def _foo(self):3 unmodified lines34 return "PublicStuff"35 36 37 @pytest.mark.sandbox39-class TestSandbox(object):38+class TestSandbox:39 def test_unsafe(self, env):40 env = SandboxedEnvironment()41 pytest.raises(42 SecurityError, env.from_string("{{ foo.foo() }}").render, foo=PrivateStuff()60 unmodified lines103 104 for expr, ctx, rv in ("1 + 2", {}, "3"), ("a + 2", {"a": 2}, "4"):105 env = SandboxedEnvironment()106 env.binop_table["+"] = disable_op108- t = env.from_string("{{ %s }}" % expr)107+ t = env.from_string(f"{{{{ {expr} }}}}")108 assert t.render(ctx) == rv109 env.intercepted_binops = frozenset(["+"])111- t = env.from_string("{{ %s }}" % expr)110+ t = env.from_string(f"{{{{ {expr} }}}}")111 with pytest.raises(TemplateRuntimeError):112 t.render(ctx)113 114 def test_unary_operator_intercepting(self, env):2 unmodified lines117 118 for expr, ctx, rv in ("-1", {}, "-1"), ("-a", {"a": 2}, "-2"):119 env = SandboxedEnvironment()120 env.unop_table["-"] = disable_op122- t = env.from_string("{{ %s }}" % expr)121+ t = env.from_string(f"{{{{ {expr} }}}}")122 assert t.render(ctx) == rv123 env.intercepted_unops = frozenset(["-"])125- t = env.from_string("{{ %s }}" % expr)124+ t = env.from_string(f"{{{{ {expr} }}}}")125 with pytest.raises(TemplateRuntimeError):126 t.render(ctx)127 128 129 @pytest.mark.sandbox131-class TestStringFormat(object):130+class TestStringFormat:131 def test_basic_format_safety(self):132 env = SandboxedEnvironment()133 t = env.from_string('{{ "a{0.__class__}b".format(42) }}')134 assert t.render() == "ab"14 unmodified lines149 assert t.render() == "a42b<foo>"150 151 152 @pytest.mark.sandbox154-class TestStringFormatMap(object):153+class TestStringFormatMap:154 def test_basic_format_safety(self):155 env = SandboxedEnvironment()156 t = env.from_string('{{ "a{x.__class__}b".format_map({"x":42}) }}')157 assert t.render() == "ab"12 unmodified linesmodified:tests/test_tests.py+3 added-4 removed
1-# -*- coding: utf-8 -*-1 import pytest2 3 from jinja2 import Environment4 from jinja2 import Markup3 unmodified lines8 pass9 10 11 @pytest.mark.test_tests13-class TestTestsCase(object):12+class TestTestsCase:13 def test_defined(self, env):14 tmpl = env.from_string("{{ missing is defined }}|{{ true is defined }}")15 assert tmpl.render() == "False|True"16 92 unmodified lines109 ("range is callable", True),110 ),111 )112 def test_types(self, env, op, expect):114- t = env.from_string("{{{{ {op} }}}}".format(op=op))113+ t = env.from_string(f"{{{{ {op} }}}}")114 assert t.render(mydict=MyDict(), complex=complex(1, 2)) == str(expect)115 116 def test_upper(self, env):117 tmpl = env.from_string('{{ "FOO" is upper }}|{{ "foo" is upper }}')32 unmodified lines150 ("ge 3", False),151 ),152 )153 def test_compare_aliases(self, env, op, expect):155- t = env.from_string("{{{{ 2 is {op} }}}}".format(op=op))154+ t = env.from_string(f"{{{{ 2 is {op} }}}}")155 assert t.render() == str(expect)156 157 def test_sameas(self, env):158 tmpl = env.from_string("{{ foo is sameas false }}|{{ 0 is sameas false }}")51 unmodified linesmodified:tests/test_utils.py+8 added-9 removed
1-# -*- coding: utf-8 -*-1 import pickle2 import random3 from collections import deque4 from copy import copy as shallow_copy11 unmodified lines16 17 18 @pytest.mark.utils19 @pytest.mark.lrucache21-class TestLRUCache(object):20+class TestLRUCache:21 def test_simple(self):22 d = LRUCache(3)23 d["a"] = 124 d["b"] = 253 unmodified lines78 d["a"] = 179 d["b"] = 280 d["c"] = 381 # Sort the strings - mapping is unordered83- assert sorted(repr(d)) == sorted(u"<LRUCache {'a': 1, 'b': 2, 'c': 3}>")82+ assert sorted(repr(d)) == sorted("<LRUCache {'a': 1, 'b': 2, 'c': 3}>")83 84 def test_items(self):85 """Test various items, keys, values and iterators of LRUCache."""86 d = LRUCache(3)24 unmodified lines111 112 113 @pytest.mark.utils114 @pytest.mark.helpers116-class TestHelpers(object):115+class TestHelpers:116 def test_object_type_repr(self):118- class X(object):117+ class X:118 pass119 120 assert object_type_repr(42) == "int object"121 assert object_type_repr([]) == "list object"19 unmodified lines141 142 143 @pytest.mark.utils144 @pytest.mark.escapeUrlizeTarget146-class TestEscapeUrlizeTarget(object):145+class TestEscapeUrlizeTarget:146 def test_escape_urlize_target(self):147 url = "http://example.org"148 target = "<script>"149 assert urlize(url, target=target) == (4 unmodified lines154 155 156 @pytest.mark.utils157 @pytest.mark.loremIpsum159-class TestLoremIpsum(object):158+class TestLoremIpsum:159 def test_lorem_ipsum_markup(self):160 """Test that output of lorem_ipsum is Markup by default."""161 assert isinstance(generate_lorem_ipsum(), Markup)162 2 unmodified lines165 assert isinstance(generate_lorem_ipsum(html=False), str)166 167 def test_lorem_ipsum_n(self):168 """Test that the n (number of lines) works as expected."""170- assert generate_lorem_ipsum(n=0, html=False) == u""169+ assert generate_lorem_ipsum(n=0, html=False) == ""170 for n in range(1, 50):171 assert generate_lorem_ipsum(n=n, html=False).count("\n") == (n - 1) * 2172 173 def test_lorem_ipsum_min(self):12 unmodified lines186 187 188 def test_missing():189 """Test the repr of missing."""191- assert repr(missing) == u"missing"190+ assert repr(missing) == "missing"191 192 193 def test_consume():194 """Test that consume consumes an iterator."""4 unmodified lines