Merge pull request #1136 from pallets/drop-python2
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Drop Python 2
authored by David Lord · committed by GitHub · parents 0c75d48, 27a5c4e · Browse files · 68 files·+1066 added−2077 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
68 files+1066 added−2077 removed
- tests:+279 added−454 removed
- other:+787 added−1623 removed
Provenance
- Commit
3915eb5- Tree
be53783- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
0c75d48- Parent 2
27a5c4e
68 files changed+1066 added−2077 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+32 added-96 removed
58 unmodified lines59 for security reasons. As such you are encouraged to explicitly60 configure autoescaping now instead of relying on the default.61 62 63-Unicode64--------65-66-Jinja is using Unicode internally which means that you have to pass Unicode67-objects to the render function or bytestrings that only consist of ASCII68-characters. Additionally newlines are normalized to one end of line69-sequence which is per default UNIX style (``\n``).70-71-Python 2.x supports two ways of representing string objects. One is the72-`str` type and the other is the `unicode` type, both of which extend a type73-called `basestring`. Unfortunately the default is `str` which should not74-be used to store text based information unless only ASCII characters are75-used. With Python 2.6 it is possible to make `unicode` the default on a per76-module level and with Python 3 it will be the default.77-78-To explicitly use a Unicode string you have to prefix the string literal79-with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will80-store the string as Unicode by decoding the string with the character81-encoding from the current Python module. If no encoding is specified this82-defaults to 'ASCII' which means that you can't use any non ASCII identifier.83-84-To set a better module encoding add the following comment to the first or85-second line of the Python module using the Unicode literal::86-87- # -*- coding: utf-8 -*-88-89-We recommend utf-8 as Encoding for Python modules and templates as it's90-possible to represent every Unicode character in utf-8 and because it's91-backwards compatible to ASCII. For Jinja the default encoding of templates92-is assumed to be utf-8.93-94-It is not possible to use Jinja to process non-Unicode data. The reason95-for this is that Jinja uses Unicode already on the language level. For96-example Jinja treats the non-breaking space as valid whitespace inside97-expressions which requires knowledge of the encoding or operating on an98-Unicode string.99-100-For more details about Unicode in Python have a look at the excellent101-`Unicode documentation`_.102-103-Another important thing is how Jinja is handling string literals in104-templates. A naive implementation would be using Unicode strings for105-all string literals but it turned out in the past that this is problematic106-as some libraries are typechecking against `str` explicitly. For example107-`datetime.strftime` does not accept Unicode arguments. To not break it108-completely Jinja is returning `str` for strings that fit into ASCII and109-for everything else `unicode`:110-111->>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module112->>> m.a113-'foo'114->>> m.b115-u'f\xf6\xf6'116-117-118-.. _Unicode documentation: https://docs.python.org/3/howto/unicode.html119-63 High Level API64 --------------65 66 The high-level API is the API you will use in the application to load and176 unmodified lines243 Notes on Identifiers244 --------------------245 246 Jinja uses Python naming rules. Valid identifiers can be any combination304-of Unicode characters accepted by Python.247+of characters accepted by Python.248 249 Filters and tests are looked up in separate namespaces and have slightly250 modified identifier syntax. Filters and tests may contain dots to group251 filters and tests by topic. For example it's perfectly valid to add a309-function into the filter dict and call it `to.unicode`. The regular252+function into the filter dict and call it `to.str`. The regular253 expression for filter and test identifiers is254 ``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.255 256 13 unmodified lines270 .. autoclass:: jinja2.Undefined()271 272 .. attribute:: _undefined_hint273 331- Either `None` or an unicode string with the error message for332- the undefined object.274+ Either `None` or a string with the error message for the275+ undefined object.276 277 .. attribute:: _undefined_obj278 279 Either `None` or the owner object that caused the undefined object29 unmodified lines309 Undefined objects are created by calling :attr:`undefined`.310 311 .. admonition:: Implementation312 370- :class:`Undefined` objects are implemented by overriding the special371- `__underscore__` methods. For example the default :class:`Undefined`372- class implements `__unicode__` in a way that it returns an empty373- string, however `__int__` and others still fail with an exception. To374- allow conversion to int by returning ``0`` you can implement your own::313+ :class:`Undefined` is implemented by overriding the special314+ ``__underscore__`` methods. For example the default315+ :class:`Undefined` class implements ``__str__`` to returns an empty316+ string, while ``__int__`` and others fail with an exception. To317+ allow conversion to int by returning ``0`` you can implement your318+ own subclass.319 320+ .. code-block:: python321+322 class NullUndefined(Undefined):323 def __int__(self):324 return 0325+326 def __float__(self):327 return 0.0328 382- To disallow a method, just override it and raise383- :attr:`~Undefined._undefined_exception`. Because this is a very common384- idiom in undefined objects there is the helper method385- :meth:`~Undefined._fail_with_undefined_error` that does the error raising386- automatically. Here a class that works like the regular :class:`Undefined`387- but chokes on iteration::329+ To disallow a method, override it and raise330+ :attr:`~Undefined._undefined_exception`. Because this is very331+ common there is the helper method332+ :meth:`~Undefined._fail_with_undefined_error` that raises the error333+ with the correct information. Here's a class that works like the334+ regular :class:`Undefined` but fails on iteration::335 336 class NonIterableUndefined(Undefined):390- __iter__ = Undefined._fail_with_undefined_error337+ def __iter__(self):338+ self._fail_with_undefined_error()339 340 341 The Context342 -----------179 unmodified lines522 Example::523 524 env.policies['urlize.rel'] = 'nofollow noopener'525 578-``compiler.ascii_str``:579- This boolean controls on Python 2 if Jinja should store ASCII only580- literals as bytestring instead of unicode strings. This used to be581- always enabled for Jinja versions below 2.9 and now can be changed.582- Traditionally it was done this way since some APIs in Python 2 failed583- badly for unicode strings (for instance the datetime strftime API).584- Now however sometimes the inverse is true (for instance str.format).585- If this is set to False then all strings are stored as unicode586- internally.587-526 ``truncate.leeway``:527 Configures the leeway default for the `truncate` filter. Leeway as528 introduced in 2.9 but to restore compatibility with older templates529 it can be configured to `0` to get the old behavior back. The default83 unmodified lines613 .. autoexception:: jinja2.TemplateSyntaxError614 615 .. attribute:: message616 679- The error message as utf-8 bytestring.617+ The error message.618 619 .. attribute:: lineno620 683- The line number where the error occurred621+ The line number where the error occurred.622 623 .. attribute:: name624 687- The load name for the template as unicode string.625+ The load name for the template.626 627 .. attribute:: filename628 691- The filename that loaded the template as bytestring in the encoding692- of the file system (most likely utf-8 or mbcs on Windows systems).629+ The filename that loaded the template in the encoding of the630+ file system (most likely utf-8, or mbcs on Windows systems).631 694- The reason why the filename and error message are bytestrings and not695- unicode strings is that Python 2.x is not using unicode for exceptions696- and tracebacks as well as the compiler. This will change with Python 3.697-632 .. autoexception:: jinja2.TemplateRuntimeError633 634 .. autoexception:: jinja2.TemplateAssertionError635 38 unmodified lines674 675 import re676 from jinja2 import evalcontextfilter, Markup, escape677 744- _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):748- result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n'))749- 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 139 unmodified lines829 This is the low level render function. It's passed a :class:`Context`830 that has to be created by :meth:`new_context` of the same template or831 a compatible template. This render function is generated by the832 compiler from the template code and returns a generator that yields897- unicode strings.833+ strings.834 835 If an exception in the template code happens the template engine will836 not rewrite the exception but pass through the original one. As a837 matter of fact this function should only be called from within a32 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:docs/extensions.rst+4 added-6 removed
42 unmodified lines43 44 .. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)45 46 Installs a translation globally for the environment. The47- ``translations`` object must implement ``gettext`` and ``ngettext``48- (or ``ugettext`` and ``ungettext`` for Python 2).47+ ``translations`` object must implement ``gettext`` and ``ngettext``.48 :class:`gettext.NullTranslations`, :class:`gettext.GNUTranslations`,49 and `Babel`_\s ``Translations`` are supported.50 51 .. versionchanged:: 2.5 Added new-style gettext support.9 unmodified lines61 .. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)62 63 Install the given ``gettext`` and ``ngettext`` callables into the64 environment. They should behave exactly like66- :func:`gettext.gettext` and :func:`gettext.ngettext` (or67- ``ugettext`` and ``ungettext`` for Python 2).65+ :func:`gettext.gettext` and :func:`gettext.ngettext`.66 67 If ``newstyle`` is activated, the callables are wrapped to work like68 newstyle callables. See :ref:`newstyle-gettext` for more information.69 13 unmodified lines83 - ``lineno`` is the number of the line on which the string was84 found.85 - ``function`` is the name of the ``gettext`` function used (if86 the string was extracted from embedded Python code).89- - ``message`` is the string itself (``unicode`` on Python 2), or a90- tuple of strings for functions with multiple arguments.87+ - ``message`` is the string itself, or a tuple of strings for88+ functions with multiple arguments.89 90 If `Babel`_ is installed, see :ref:`babel-integration` to extract91 the strings.92 310 unmodified linesmodified:docs/faq.rst+10 added-30 removed
123 unmodified lines124 instead that one can assign to a variable by using set::125 126 {% set comments = get_latest_comments() %}127 128-My tracebacks look weird. What's happening?129---------------------------------------------128+My tracebacks look weird. What's happening?129+-------------------------------------------130 131-If the debugsupport module is not compiled and you are using a Python132-installation without ctypes (Python 2.4 without ctypes, Jython or Google's133-AppEngine) Jinja is unable to provide correct debugging information and134-the traceback may be incomplete. There is currently no good workaround135-for Jython or the AppEngine as ctypes is unavailable there and it's not136-possible to use the debugsupport extension.131+Jinja can rewrite tracebacks so they show the template lines numbers and132+source rather than the underlying compiled code, but this requires133+special Python support. CPython <3.7 requires ``ctypes``, and PyPy134+requires transparent proxy support.135 138-If you are working in the Google AppEngine development server you can139-whitelist the ctypes module to restore the tracebacks. This however won't140-work in production environments::136+If you are using Google App Engine, ``ctypes`` is not available. You can137+make it available in development, but not in production.138 139+.. code-block:: python140+141 import os142 if os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'):143 from google.appengine.tools.devappserver2.python import sandbox144 sandbox._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt']145 146 Credit for this snippet goes to `Thomas Johansson147 <https://stackoverflow.com/questions/3086091/debug-jinja2-in-google-app-engine/3694434#3694434>`_148 150-Why is there no Python 2.3/2.4/2.5/2.6/3.1/3.2/3.3 support?151------------------------------------------------------------152-153-Python 2.3 is missing a lot of features that are used heavily in Jinja. This154-decision was made as with the upcoming Python 2.6 and 3.0 versions it becomes155-harder to maintain the code for older Python versions. If you really need156-Python 2.3 support you either have to use Jinja 1 or other templating157-engines that still support 2.3.158-159-Python 2.4/2.5/3.1/3.2 support was removed when we switched to supporting160-Python 2 and 3 by the same sourcecode (without using 2to3). It was required to161-drop support because only Python 2.6/2.7 and >=3.3 support byte and unicode162-literals in a way compatible to each other version. If you really need support163-for older Python 2 (or 3) versions, you can just use Jinja 2.6.164-165-Python 2.6/3.3 support was dropped because it got dropped in various upstream166-projects (such as wheel or pytest), which would make it difficult to continue167-supporting it. Jinja 2.10 was the last version supporting Python 2.6/3.3.168-149 My Macros are overridden by something150 -------------------------------------151 152 In some situations the Jinja scoping appears arbitrary:23 unmodified linesmodified:docs/index.rst+3 added-26 removed
5 unmodified lines6 .. image:: _static/jinja-logo.png7 :align: center8 :target: https://palletsprojects.com/p/jinja/9 10-Jinja is a modern and designer-friendly templating language for Python,11-modelled after Django's templates. It is fast, widely used and secure12-with the optional sandboxed template execution environment:10+Jinja is a fast, expressive, extensible templating engine. Special11+placeholders in the template allow writing code similar to Python12+syntax. Then the template is passed data to render the final document.13 14-.. sourcecode:: html+jinja15-16- <title>{% block title %}{% endblock %}</title>17- <ul>18- {% for user in users %}19- <li><a href="{{ user.url }}">{{ user.username }}</a></li>20- {% endfor %}21- </ul>22-23-Features:24-25-- sandboxed execution26-- powerful automatic HTML escaping system for XSS prevention27-- template inheritance28-- compiles down to the optimal python code just in time29-- optional ahead-of-time template compilation30-- easy to debug. Line numbers of exceptions directly point to31- the correct line in the template.32-- configurable syntax33-14 .. toctree::15 :maxdepth: 216 :caption: Contents:17 7 unmodified lines25 switching26 tricks27 faq28 changelog49-50-* :ref:`genindex`51-* :ref:`search`modified:docs/intro.rst+37 added-56 removed
1 Introduction2 ============3 4-This is the documentation for the Jinja general purpose templating language.5-Jinja is a library for Python that is designed to be flexible, fast and secure.4+Jinja is a fast, expressive, extensible templating engine. Special5+placeholders in the template allow writing code similar to Python6+syntax. Then the template is passed data to render the final document.7 7-If you have any exposure to other text-based template languages, such as Smarty or8-Django, you should feel right at home with Jinja. It's both designer and9-developer friendly by sticking to Python's principles and adding functionality10-useful for templating environments.8+It includes:9 12-Prerequisites13--------------10+- Template inheritance and inclusion.11+- Define and import macros within templates.12+- HTML templates can use autoescaping to prevent XSS from untrusted13+ user input.14+- A sandboxed environment can safely render untrusted templates.15+- AsyncIO support for generating templates and calling async16+ functions.17+- I18N support with Babel.18+- Templates are compiled to optimized Python code just-in-time and19+ cached, or can be compiled ahead-of-time.20+- Exceptions point to the correct line in templates to make debugging21+ easier.22+- Extensible filters, tests, functions, and even syntax.23 15-Jinja works with Python 2.7.x and >= 3.5. If you are using Python16-3.2 you can use an older release of Jinja (2.6) as support for Python 3.217-was dropped in Jinja version 2.7. The last release which supported Python 2.618-and 3.3 was Jinja 2.10.24+Jinja's philosophy is that while application logic belongs in Python if25+possible, it shouldn't make the template designer's job difficult by26+restricting functionality too much.27 20-If you wish to use the :class:`~jinja2.PackageLoader` class, you will also21-need `setuptools`_ or `distribute`_ installed at runtime.28 29 Installation30 ------------31 26-You can install the most recent Jinja version using `pip`_::32+We recommend using the latest version of Python. Jinja supports Python33+3.6 and newer. We also recommend using a `virtual environment`_ in order34+to isolate your project dependencies from other projects and the system.35 28- pip install Jinja236+.. _virtual environment: https://packaging.python.org/tutorials/installing-packages/#creating-virtual-environments37 30-This will install Jinja in your Python installation's site-packages directory.38+Install the most recent Jinja version using pip:39 32-Installing the development version33-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~40+.. code-block:: text41 35-1. Install `git`_36-2. ``git clone git://github.com/pallets/jinja.git``37-3. ``cd jinja2``38-4. ``ln -s jinja2 /usr/lib/python2.X/site-packages``42+ $ pip install Jinja243 40-As an alternative to steps 4 you can also do ``python setup.py develop``41-which will install the package via `distribute` in development mode. This also42-has the advantage that the C extensions are compiled.44 44-.. _distribute: https://pypi.org/project/distribute/45-.. _setuptools: https://pypi.org/project/setuptools/46-.. _pip: https://pypi.org/project/pip/47-.. _git: https://git-scm.com/45+Dependencies46+~~~~~~~~~~~~47 48+These will be installed automatically when installing Jinja.49 50-MarkupSafe Dependency51-~~~~~~~~~~~~~~~~~~~~~50+- `MarkupSafe`_ escapes untrusted input when rendering templates to51+ avoid injection attacks.52 53-As of version 2.7 Jinja depends on the `MarkupSafe`_ module. If you install54-Jinja via ``pip`` it will be installed automatically for you.55-53 .. _MarkupSafe: https://markupsafe.palletsprojects.com/54 58-Basic API Usage59----------------55 61-This section gives you a brief introduction to the Python API for Jinja62-templates.56+Optional Dependencies57+~~~~~~~~~~~~~~~~~~~~~58 64-The most basic way to create a template and render it is through65-:class:`~jinja2.Template`. This however is not the recommended way to66-work with it if your templates are not loaded from strings but the file67-system or another data source:59+These distributions will not be installed automatically.60 69->>> from jinja2 import Template70->>> template = Template('Hello {{ name }}!')71->>> template.render(name='John Doe')72-u'Hello John Doe!'61+- `Babel`_ provides translation support in templates.62 74-By creating an instance of :class:`~jinja2.Template` you get back a new template75-object that provides a method called :meth:`~jinja2.Template.render` which when76-called with a dict or keyword arguments expands the template. The dict77-or keywords arguments passed to the template are the so-called "context"78-of the template.79-80-What you can see here is that Jinja is using unicode internally and the81-return value is an unicode string. So make sure that your application is82-indeed using unicode internally.63+.. _Babel: http://babel.pocoo.org/modified:docs/switching.rst+6 added-6 removed
30 unmodified lines31 provides a :class:`Template` class that can be used to do the same, but32 with optional additional configuration.33 34 Automatic unicode conversion35- Jinja 1 performed automatic conversion of bytestrings in a given encoding36- into unicode objects. This conversion is no longer implemented as it37- was inconsistent as most libraries are using the regular Python ASCII38- bytestring to Unicode conversion. An application powered by Jinja 239- *has to* use unicode internally everywhere or make sure that Jinja 2 only40- gets unicode strings passed.35+ Jinja 1 performed automatic conversion of bytes in a given encoding36+ into unicode objects. This conversion is no longer implemented as it37+ was inconsistent as most libraries are using the regular Python38+ ASCII bytes to Unicode conversion. An application powered by Jinja 239+ *has to* use unicode internally everywhere or make sure that Jinja 240+ only gets unicode strings passed.41 42 i18n43 Jinja 1 used custom translators for internationalization. i18n is now44 available as Jinja 2 extension and uses a simpler, more gettext friendly182 unmodified linesmodified:docs/templates.rst+2 added-3 removed
600 unmodified lines601 602 Jinja functions (macros, `super`, `self.BLOCKNAME`) always return template603 data that is marked as safe.604 605-String literals in templates with automatic escaping are considered unsafe606-because native Python strings (``str``, ``unicode``, ``basestring``) are not607-`MarkupSafe.Markup` strings with an ``__html__`` attribute.605+String literals in templates with automatic escaping are considered606+unsafe because native Python strings are not safe.607 608 .. _list-of-control-structures:609 610 List of Control Structures1209 unmodified linesmodified: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 linedeleted:src/jinja2/_compat.py-132 removed
1-# -*- coding: utf-8 -*-2-# flake8: noqa3-import marshal4-import sys5-6-PY2 = sys.version_info[0] == 27-PYPY = hasattr(sys, "pypy_translation_info")8-_identity = lambda x: x9-10-if not PY2:11- unichr = chr12- range_type = range13- text_type = str14- string_types = (str,)15- integer_types = (int,)16-17- iterkeys = lambda d: iter(d.keys())18- itervalues = lambda d: iter(d.values())19- iteritems = lambda d: iter(d.items())20-21- import pickle22- from io import BytesIO, StringIO23-24- NativeStringIO = StringIO25-26- def reraise(tp, value, tb=None):27- if value.__traceback__ is not tb:28- raise value.with_traceback(tb)29- raise value30-31- ifilter = filter32- imap = map33- izip = zip34- intern = sys.intern35-36- implements_iterator = _identity37- implements_to_string = _identity38- encode_filename = _identity39-40- marshal_dump = marshal.dump41- marshal_load = marshal.load42-43-else:44- unichr = unichr45- text_type = unicode46- range_type = xrange47- string_types = (str, unicode)48- integer_types = (int, long)49-50- iterkeys = lambda d: d.iterkeys()51- itervalues = lambda d: d.itervalues()52- iteritems = lambda d: d.iteritems()53-54- import cPickle as pickle55- from cStringIO import StringIO as BytesIO, StringIO56-57- NativeStringIO = BytesIO58-59- exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")60-61- from itertools import imap, izip, ifilter62-63- intern = intern64-65- def implements_iterator(cls):66- cls.next = cls.__next__67- del cls.__next__68- return cls69-70- def implements_to_string(cls):71- cls.__unicode__ = cls.__str__72- cls.__str__ = lambda x: x.__unicode__().encode("utf-8")73- return cls74-75- def encode_filename(filename):76- if isinstance(filename, unicode):77- return filename.encode("utf-8")78- return filename79-80- def marshal_dump(code, f):81- if isinstance(f, file):82- marshal.dump(code, f)83- else:84- f.write(marshal.dumps(code))85-86- def marshal_load(f):87- if isinstance(f, file):88- return marshal.load(f)89- return marshal.loads(f.read())90-91-92-def with_metaclass(meta, *bases):93- """Create a base class with a metaclass."""94- # This requires a bit of explanation: the basic idea is to make a95- # dummy metaclass for one level of class instantiation that replaces96- # itself with the actual metaclass.97- class metaclass(type):98- def __new__(cls, name, this_bases, d):99- return meta(name, bases, d)100-101- return type.__new__(metaclass, "temporary_class", (), {})102-103-104-try:105- from urllib.parse import quote_from_bytes as url_quote106-except ImportError:107- from urllib import quote as url_quote108-109-110-try:111- from collections import abc112-except ImportError:113- import collections as abc114-115-116-try:117- from os import fspath118-except ImportError:119- try:120- from pathlib import PurePath121- except ImportError:122- PurePath = None123-124- def fspath(path):125- if hasattr(path, "__fspath__"):126- return path.__fspath__()127-128- # Python 3.5 doesn't have __fspath__ yet, use str.129- if PurePath is not None and isinstance(path, PurePath):130- return str(path)131-132- return pathmodified:src/jinja2/asyncfilters.py+2 added-3 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)53 unmodified lines145 "first": do_first,146 "groupby": do_groupby,147 "join": do_join,148 "list": do_list,149- # we intentionally do not support do_last because that would be150- # ridiculous149+ # we intentionally do not support do_last because it may not be safe in async150 "reject": do_reject,151 "rejectattr": do_rejectattr,152 "map": do_map,153 "select": do_select,4 unmodified linesmodified:src/jinja2/asyncsupport.py+1 added-16 removed
1-# -*- coding: utf-8 -*-2-"""The code for async support. Importing this patches Jinja on supported1+"""The code for async support. Importing this patches Jinja."""3-Python versions.4-"""2 import asyncio3 import inspect4 from functools import update_wrapper5 239 unmodified lines245 self._current = rv246 return rv, self247 248 252-async def make_async_loop_context(iterable, undefined, recurse=None, depth0=0):253- import warnings254-255- warnings.warn(256- "This template must be recompiled with at least Jinja 2.11, or"257- " it will fail in 3.0.",258- DeprecationWarning,259- stacklevel=2,260- )261- return AsyncLoopContext(iterable, undefined, recurse, depth0)262-263-249 patch_all()modified:src/jinja2/bccache.py+14 added-19 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 1 unmodified line6 are initialized on the first request.7 """8 import errno9 import fnmatch10+import marshal11 import os12+import pickle13 import stat14 import sys15 import tempfile16 from hashlib import sha116-from os import listdir17-from os import path17+from io import BytesIO18 19-from ._compat import BytesIO20-from ._compat import marshal_dump21-from ._compat import marshal_load22-from ._compat import pickle23-from ._compat import text_type19 from .utils import open_if_exists20 26-bc_version = 421+bc_version = 522 # Magic bytes to identify Jinja bytecode cache files. Contains the23 # Python major and minor version to avoid loading incompatible bytecode24 # if a project upgrades its Python version.25 bc_magic = (2 unmodified lines28 + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1], 2)29 )30 31 37-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 this24 unmodified lines61 self.reset()62 return63 # if marshal_load fails then we need to reload64 try:70- self.code = marshal_load(f)65+ self.code = marshal.load(f)66 except (EOFError, ValueError, TypeError):67 self.reset()68 return69 2 unmodified lines72 if self.code is None:73 raise TypeError("can't write empty bucket")74 f.write(bc_magic)75 pickle.dump(self.checksum, f, 2)81- marshal_dump(self.code, f)76+ marshal.dump(self.code, f)77 78 def bytecode_from_string(self, string):79 """Load bytecode from a string."""80 self.load_bytecode(BytesIO(string))4 unmodified lines85 self.write_bytecode(out)86 return out.getvalue()87 88 94-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 45 unmodified lines139 """Returns the unique hash key for this template name."""140 hash = sha1(name.encode("utf-8"))141 if filename is not None:142 filename = "|" + filename148- if isinstance(filename, text_type):143+ if isinstance(filename, str):144 filename = filename.encode("utf-8")145 hash.update(filename)146 return hash.hexdigest()147 55 unmodified lines203 return tmpdir204 if not hasattr(os, "getuid"):205 _unsafe_dir()206 212- 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):244- return 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 267- files = fnmatch.filter(listdir(self.directory), self.pattern % "*")262+ files = fnmatch.filter(os.listdir(self.directory), self.pattern % ("*",))263 for filename in files:264 try:270- remove(path.join(self.directory, filename))265+ remove(os.path.join(self.directory, filename))266 except OSError:267 pass268 269 8 unmodified lines278 - `cachelib <https://github.com/pallets/cachelib>`_279 - `python-memcached <https://pypi.org/project/python-memcached/>`_280 281 (Unfortunately the django cache interface is not compatible because it287- does not support storing binary data, only unicode. You can however pass282+ does not support storing binary data, only text. You can however pass283 the underlying cache client to the bytecode cache which is available284 as `django.core.cache.cache._client`.)285 286 The minimal interface for the client passed to the constructor is this:59 unmodified linesmodified:src/jinja2/compiler.py+176 added-265 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 StringIO5 from itertools import chain6 from keyword import iskeyword as is_python_keyword7 8 from markupsafe import escape9 from markupsafe import Markup10 11 from . import nodes12-from ._compat import imap13-from ._compat import iteritems14-from ._compat import izip15-from ._compat import NativeStringIO16-from ._compat import range_type17-from ._compat import string_types18-from ._compat import text_type12 from .exceptions import TemplateAssertionError13 from .idtracking import Symbols14 from .idtracking import VAR_LOAD_ALIAS15 from .idtracking import VAR_LOAD_PARAMETER14 unmodified lines30 "in": "in",31 "notin": "not in",32 }33 41-# what method to iterate over items do we want to use for dict iteration42-# in generated code? on 2.x let's go with iteritems, on 3.x with items43-if hasattr(dict, "iteritems"):44- dict_item_iter = "iteritems"45-else:46- dict_item_iter = "items"34 48-code_features = ["division"]49-50-# does this python version support generator stops? (PEP 0479)51-try:52- exec("from __future__ import generator_stop")53- code_features.append("generator_stop")54-except SyntaxError:55- pass56-57-# does this python version support yield from?58-try:59- exec("def f(): yield from x()")60-except SyntaxError:61- supports_yield_from = False62-else:63- supports_yield_from = True64-65-35 def optimizeconst(f):36 def new_func(self, node, frame, **kwargs):37 # Only optimize if the frame is not volatile38 if self.optimized and not frame.eval_ctx.volatile:22 unmodified lines61 def has_safe_repr(value):62 """Does the node have a safe representation?"""63 if value is None or value is NotImplemented or value is Ellipsis:64 return True96- if type(value) in (bool, int, float, complex, range_type, Markup) + string_types:65+66+ if type(value) in {bool, int, float, complex, range, str, Markup}:67 return True98- if type(value) in (tuple, list, set, frozenset):99- for item in value:100- if not has_safe_repr(item):101- return False102- return True103- elif type(value) is dict:104- for key, value in iteritems(value):105- if not has_safe_repr(key):106- return False107- if not has_safe_repr(value):108- return False109- return True68+69+ if type(value) in {tuple, list, set, frozenset}:70+ return all(has_safe_repr(v) for v in value)71+72+ if type(value) is dict:73+ return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items())74+75 return False76 77 78 def find_undeclared(nodes, names):8 unmodified lines87 pass88 return visitor.undeclared89 90 126-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 134-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_ctx139- 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.160- 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 83 unmodified lines213 def __init__(214 self, environment, name, filename, stream=None, defer_init=False, optimized=True215 ):216 if stream is None:252- stream = NativeStringIO()217+ stream = StringIO()218 self.environment = environment219 self.name = name220 self.filename = filename221 self.stream = stream62 unmodified lines284 285 def temporary_identifier(self):286 """Get a new unique identifier."""287 self._last_identifier += 1323- 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()328- 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()336- 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()340- 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:344- self.writeline("return Markup(concat(%s))" % frame.buffer)309+ self.writeline(f"return Markup(concat({frame.buffer}))")310 return346- 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:361- 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:65 unmodified lines396 for kwarg in node.kwargs:397 self.write(", ")398 self.visit(kwarg, frame)399 if extra_kwargs is not None:435- for key, value in iteritems(extra_kwargs):436- self.write(", %s=%s" % (key, value))400+ for key, value in extra_kwargs.items():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:447- 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:451- for key, value in iteritems(extra_kwargs):452- self.write("%r: %s, " % (key, value))416+ for key, value in extra_kwargs.items():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()474- self.writeline(475- "%s = environment.%s[%r]" % (mapping[name], dependency, name)476- )439+ self.writeline(f"{mapping[name]} = environment.{dependency}[{name!r}]")440 441 def enter_frame(self, frame):442 undefs = []480- for target, (action, param) in iteritems(frame.symbols.loads):443+ for target, (action, param) in frame.symbols.loads.items():444 if action == VAR_LOAD_PARAMETER:445 pass446 elif action == VAR_LOAD_RESOLVE:484- 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:486- 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:492- 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 = []497- for target, _ in iteritems(frame.symbols.loads):460+ for target in frame.symbols.loads:461 undefs.append(target)462 if undefs:500- 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:504- return "async def %s" % name505- 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)555- 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)564- 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(570- "%s = undefined(%r, name=%r)"571- % (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:574- 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(594- "Macro(environment, macro, %r, (%s), %r, %r, %r, "595- "context.eval_ctx.autoescape)"596- % (597- name,598- arg_tuple,599- macro_ref.accesses_kwargs,600- macro_ref.accesses_varargs,601- macro_ref.accesses_caller,602- )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."""607- rv = "line %d" % node.lineno564+ rv = f"line {node.lineno}"565 if self.name is not None:609- rv += " in " + repr(self.name)566+ rv = f"{rv} in {self.name!r}"567 return rv568 569 def dump_local_context(self, frame):613- return "{%s}" % ", ".join(614- "%r: %s" % (name, target)615- for name, target in iteritems(frame.symbols.dump_stores())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"663- return "%s.resolve" % target621+ return f"{target}.resolve"622 623 def derive_context(self, frame):666- return "%s.derived(%s)" % (667- self.get_context_ref(),668- self.dump_local_context(frame),669- )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)692- 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)699- 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:703- self.writeline("context.exported_vars.add(%r)" % public_names[0])658+ self.writeline(f"context.exported_vars.add({public_names[0]!r})")659 else:705- self.writeline(706- "context.exported_vars.update((%s))"707- % ", ".join(imap(repr, public_names))708- )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):1 unmodified line667 eval_ctx = EvalContext(self.environment, self.name)668 669 from .runtime import exported670 718- self.writeline("from __future__ import %s" % ", ".join(code_features))671+ self.writeline("from __future__ import generator_stop") # Python < 3.7672 self.writeline("from jinja2.runtime import " + ", ".join(exported))673 674 if self.environment.is_async:675 self.writeline(2 unmodified lines678 )679 680 # if we want a deferred initialization we cannot move the681 # environment into a local name729- 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:738- 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)748- self.writeline("from %s import %s as %s" % (module, obj, alias))701+ self.writeline(f"from {module} import {obj} as {alias}")702 else:750- self.writeline("import %s as %s" % (imp, alias))703+ self.writeline(f"import {imp} as {alias}")704 705 # add the load name753- self.writeline("name = %r" % self.name)706+ self.writeline(f"name = {self.name!r}")707 708 # generate the root render function.709 self.writeline(757- "%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")766- 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:9 unmodified lines733 if not self.has_known_extends:734 self.indent()735 self.writeline("if parent_template is not None:")736 self.indent()784- if supports_yield_from and not self.environment.is_async: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(788- "%sfor event in parent_template."789- "root_render_func(context):"790- % (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()747 self.outdent(1 + (not self.has_known_extends))748 749 # at this point we now have the blocks collected and can visit them too.798- for name, block in iteritems(self.blocks):750+ for name, block in self.blocks.items():751 self.writeline(800- "%s(context, missing=missing%s):"801- % (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")814- 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")817- 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 826- self.writeline(827- "blocks = {%s}" % ", ".join("%r: block_%s" % (x, x) for x in self.blocks),828- extra=1,829- )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 831- # add a function that returns the debug info832- self.writeline(833- "debug_info = %r" % "&".join("%s=%s" % x for x in self.debug_info)834- )835-782 def visit_Block(self, node, frame):783 """Call a block and register it for the template."""784 level = 0785 if frame.toplevel:10 unmodified lines796 context = self.derive_context(frame)797 else:798 context = self.get_context_ref()799 854- if (855- supports_yield_from856- and not self.environment.is_async857- and frame.buffer is None858- ):800+ if not self.environment.is_async and frame.buffer is None:801 self.writeline(860- "yield from context.blocks[%r][0](%s)" % (node.name, context), node802+ f"yield from context.blocks[{node.name!r}][0]({context})", node803 )804 else:863- loop = self.environment.is_async and "async for" or "for"805+ loop = "async for" if self.environment.is_async else "for"806 self.writeline(865- "%s event in context.blocks[%r][0](%s):" % (loop, node.name, context),866- 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()891- 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)902- self.write(", %r)" % self.name)903- self.writeline(904- "for name, parent_block in parent_template.blocks.%s():" % dict_item_iter905- )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()848 13 unmodified lines862 self.indent()863 864 func_name = "get_or_select_template"865 if isinstance(node.template, nodes.Const):927- if isinstance(node.template.value, string_types):866+ if isinstance(node.template.value, str):867 func_name = "get_template"868 elif isinstance(node.template.value, (tuple, list)):869 func_name = "select_template"870 elif isinstance(node.template, (nodes.Tuple, nodes.List)):871 func_name = "select_template"872 934- self.writeline("template = environment.%s(" % func_name, node)873+ self.writeline(f"template = environment.{func_name}(", node)874 self.visit(node.template, frame)936- 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:948- loop = self.environment.is_async and "async for" or "for"887+ loop = "async for" if self.environment.is_async else "for"888 self.writeline(950- "%s event in template.root_render_func("951- "template.new_context(context.get_all(), True, "952- "%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(956- "for event in (await "957- "template._get_default_module_async())"895+ "for event in (await template._get_default_module_async())"896 "._body_stream:"897 )898 else:961- if supports_yield_from:962- self.writeline("yield from template._get_default_module()._body_stream")963- skip_event_yield = True899+ self.writeline("yield from template._get_default_module()._body_stream")900+ skip_event_yield = True964- else:965- self.writeline(966- "for event in template._get_default_module()._body_stream:"967- )901 902 if not skip_event_yield:903 self.indent()904 self.simple_write("event", frame)3 unmodified lines908 self.outdent()909 910 def visit_Import(self, node, frame):911 """Visit regular imports."""979- self.writeline("%s = " % frame.symbols.ref(node.target), node)912+ self.writeline(f"{frame.symbols.ref(node.target)} = ", node)913 if frame.toplevel:981- 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)986- 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(989- "make_module%s(context.get_all(), True, %s)"990- % (991- self.environment.is_async and "_async" or "",992- self.dump_local_context(frame),993- )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("_"):1000- 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)1005- self.write(1006- "included_template = %senvironment.get_template("1007- % (self.environment.is_async and "await " or "")1008- )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)1010- 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(1013- "make_module%s(context.get_all(), True, %s)"1014- % (1015- self.environment.is_async and "_async" or "",1016- self.dump_local_context(frame),1017- )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(1032- "%s = getattr(included_template, "1033- "%r, missing)" % (frame.symbols.ref(alias), name)957+ f"{frame.symbols.ref(alias)} ="958+ f" getattr(included_template, {name!r}, missing)"959 )1035- 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(1038- "%s = undefined(%r %% "1039- "included_template.__name__, "1040- "name=%r)"1041- % (1042- frame.symbols.ref(alias),1043- "the template %%r (imported on %s) does "1044- "not export the requested name %s"1045- % (self.position(node), repr(name)),1046- name,1047- )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]1058- self.writeline(1059- "context.vars[%r] = %s" % (name, frame.symbols.ref(name))1060- )979+ self.writeline(f"context.vars[{name!r}] = {frame.symbols.ref(name)}")980 else:1062- self.writeline(1063- "context.vars.update({%s})"1064- % ", ".join(1065- "%r: %s" % (name, frame.symbols.ref(name)) for name in var_names1066- )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:1070- 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(1073- "context.exported_vars.difference_"1074- "update((%s))" % ", ".join(imap(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")1100- 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)1103- 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 ")1106- 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(1123- "%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:1134- 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()1145- self.writeline("%s = 1" % iteration_indicator)1062+ self.writeline(f"{iteration_indicator} = 1")1063 1147- 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:1150- if self.environment.is_async:1151- self.write(", %s in AsyncLoopContext(" % loop_ref)1152- else:1153- 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:1158- 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:1173- 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_:1180- 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_:1187- 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("_"):1237- self.write("context.exported_vars.add(%r)" % node.name)1238- self.writeline("context.vars[%r] = " % node.name)1239- 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)17 unmodified lines1176 def visit_With(self, node, frame):1177 with_frame = frame.inner()1178 with_frame.symbols.analyze_node(node)1179 self.enter_frame(with_frame)1265- for target, expr in izip(node.targets, node.values):1180+ for target, expr in zip(node.targets, node.values):1181 self.newline()1182 self.visit(target, with_frame)1183 self.write(" = ")1184 self.visit(expr, frame)7 unmodified lines1192 _FinalizeInfo = namedtuple("_FinalizeInfo", ("const", "src"))1193 #: The default finalize function if the environment isn't configured1194 #: with one. Or if the environment has one, this is called on that1195 #: function's output for constants.1281- _default_finalize = text_type1196+ _default_finalize = str1197 _finalize = None1198 1199 def _make_finalize(self):1200 """Build the finalize function to be used on constants and at57 unmodified lines1258 const = escape(const)1259 1260 # Template data doesn't go through finalize.1261 if isinstance(node, nodes.TemplateData):1347- return text_type(const)1262+ return str(const)1263 1264 return finalize.const(const)1265 1266 def _output_child_pre(self, node, frame, finalize):1267 """Output extra source code before visiting a child of an1268 ``Output`` node.1269 """1270 if frame.eval_ctx.volatile:1356- self.write("(escape if context.eval_ctx.autoescape else to_string)(")1271+ self.write("(escape if context.eval_ctx.autoescape else str)(")1272 elif frame.eval_ctx.autoescape:1273 self.write("escape(")1274 else:1360- self.write("to_string(")1275+ self.write("str(")1276 1277 if finalize.src is not None:1278 self.write(finalize.src)1279 48 unmodified lines1328 body.append([const])1329 1330 if frame.buffer is not None:1331 if len(body) == 1:1417- self.writeline("%s.append(" % frame.buffer)1332+ self.writeline(f"{frame.buffer}.append(")1333 else:1419- 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:1478- 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(1502- "(undefined(name=%r) if %s is missing else %s)"1503- % (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)1514- self.writeline("if not isinstance(%s, Namespace):" % ref)1428+ self.writeline(f"if not isinstance({ref}, Namespace):")1429 self.indent()1430 self.writeline(1517- "raise TemplateRuntimeError(%r)"1518- % "cannot assign attribute on non-namespace object"1431+ "raise TemplateRuntimeError"1432+ '("cannot assign attribute on non-namespace object")'1433 )1434 self.outdent()1521- 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(1535- "(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)1545- 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 ):1572- 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)1579- 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 ):1592- 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:1618- func_name = "(context.eval_ctx.volatile and markup_join or unicode_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:1622- func_name = "unicode_join"1623- self.write("%s((" % func_name)1536+ func_name = "str_join"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):1638- 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)1648- 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:1691- 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(1705- "(context.eval_ctx.autoescape and"1706- " 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:1709- self.write("Markup(concat(%s))" % frame.buffer)1623+ self.write(f"Markup(concat({frame.buffer}))")1624 else:1711- 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:1721- 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(1732- "cond_expr_undefined(%r)"1733- % (1734- "the inline if-"1735- "expression on %s evaluated to false and "1736- "no else section was defined." % self.position(node)1737- )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)1757- 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):1775- 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):1783- 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()1812- self.writeline("%s = %s" % (ctx, self.derive_context(frame)))1813- 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:1826- 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()1838- 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)1843- 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+10 added-17 removed
1+import platform2 import sys3 from types import CodeType4 5 from . import TemplateSyntaxError5-from ._compat import PYPY6 from .utils import internal_code7 from .utils import missing8 9 3 unmodified lines13 came from the template source.14 15 This must be called within an ``except`` block.16 17- :param exc_info: A :meth:`sys.exc_info` tuple. If not provided,18- the current ``exc_info`` is used.17 :param source: For ``TemplateSyntaxError``, the original source if18 known.21- :return: A :meth:`sys.exc_info` tuple that can be re-raised.19+ :return: The original exception with the rewritten traceback.20 """23- exc_type, exc_value, tb = sys.exc_info()21+ _, exc_value, tb = sys.exc_info()22 23 if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:24 exc_value.translated = True25 exc_value.source = source28-29- try:30- # Remove the old traceback on Python 3, otherwise the frames31- # from the compiler still show up.32- exc_value.with_traceback(None)26+ # Remove the old traceback, otherwise the frames from the27+ # compiler still show up.28+ exc_value.with_traceback(None)33- except AttributeError:34- pass35-29 # Outside of runtime, so the frame isn't executing template30 # code, but it still needs to point at the template.31 tb = fake_traceback(32 exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno29 unmodified lines62 # Assign tb_next in reverse to avoid circular references.63 for tb in reversed(stack):64 tb_next = tb_set_next(tb, tb_next)65 73- return exc_type, exc_value, tb_next66+ return exc_value.with_traceback(tb_next)67 68 69 def fake_traceback(exc_value, tb, filename, lineno):70 """Produce a new traceback object that looks like it came from the34 unmodified lines105 106 if function == "root":107 location = "top-level template code"108 elif function.startswith("block_"):116- 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.1 unmodified line115 116 for attr in (117 "argcount",118 "posonlyargcount", # Python 3.8126- "kwonlyargcount", # Python 3119+ "kwonlyargcount",120 "nlocals",121 "stacksize",122 "flags",123 "code", # codestring83 unmodified lines207 tb.tb_next = tb_next208 return tb209 210 218-elif PYPY:211+elif platform.python_implementation() == "PyPy":212 # PyPy might have special support, and won't work with ctypes.213 try:214 import tputil215 except ImportError:49 unmodified linesmodified:src/jinja2/defaults.py+1 added-3 removed
1-# -*- coding: utf-8 -*-2-from ._compat import range_type1 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_ipsum16 unmodified lines21 22 # default filters, tests and namespace23 24 DEFAULT_NAMESPACE = {27- "range": range_type,25+ "range": range,26 "dict": dict,27 "lipsum": generate_lorem_ipsum,28 "cycler": Cycler,29 "joiner": Joiner,13 unmodified linesmodified:src/jinja2/environment.py+49 added-97 removed
1-# -*- coding: utf-8 -*-1 """Classes for managing templates and their runtime and compile time2 options.3 """4 import os4 unmodified lines9 10 from markupsafe import Markup11 12 from . import nodes14-from ._compat import encode_filename15-from ._compat import implements_iterator16-from ._compat import implements_to_string17-from ._compat import iteritems18-from ._compat import PY219-from ._compat import PYPY20-from ._compat import reraise21-from ._compat import string_types22-from ._compat import text_type13 from .compiler import CodeGenerator14 from .compiler import generate15 from .defaults import BLOCK_END_STRING16 from .defaults import BLOCK_START_STRING76 unmodified lines93 Returns a dict of instantiated environments.94 """95 result = {}96 for extension in extensions:107- if isinstance(extension, string_types):97+ if isinstance(extension, str):98 extension = import_string(extension)99 result[extension.identifier] = extension(environment)100 return result101 102 113-def fail_for_missing_callable(string, name):114- 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:119- 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"133- assert environment.newline_sequence in (124+ assert environment.newline_sequence in {125 "\r",126 "\r\n",127 "\n",137- ), "newline_sequence set to unknown line ending string."128+ }, "newline_sequence set to unknown line ending string."129 return environment130 131 141-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.109 unmodified lines246 247 See :ref:`bytecode-cache` for more information.248 249 `enable_async`259- If set to true this enables async template execution which allows260- you to take advantage of newer Python features. This requires261- Python 3.6 or later.250+ If set to true this enables async template execution which251+ allows using async functions and generators.252 """253 254 #: if this environment is sandboxed. Modifying this variable won't make255 #: the environment sandboxed though. For a real sandboxed environment111 unmodified lines367 """Add the items to the instance of the environment if they do not exist368 yet. This is used by :ref:`extensions <writing-extensions>` to register369 callbacks and configuration values without breaking inheritance.370 """381- for key, value in iteritems(attributes):371+ for key, value in attributes.items():372 if not hasattr(self, key):373 setattr(self, key, value)374 375 def overlay(36 unmodified lines412 rv.__dict__.update(self.__dict__)413 rv.overlayed = True414 rv.linked_to = self415 426- for key, value in iteritems(args):416+ for key, value in args.items():417 if value is not missing:418 setattr(rv, key, value)419 420 if cache_size is not missing:1 unmodified line422 else:423 rv.cache = copy_cache(self.cache)424 425 rv.extensions = {}436- for key, value in iteritems(self.extensions):426+ for key, value in self.extensions.items():427 rv.extensions[key] = value.bind(rv)428 if extensions is not missing:429 rv.extensions.update(load_extensions(rv, extensions))430 9 unmodified lines440 """Get an item or attribute of an object but prefer the item."""441 try:442 return obj[argument]443 except (AttributeError, TypeError, LookupError):454- if isinstance(argument, string_types):444+ if isinstance(argument, str):445 try:446 attr = str(argument)447 except Exception:448 pass19 unmodified lines468 469 def call_filter(470 self, name, value, args=None, kwargs=None, context=None, eval_ctx=None471 ):482- """Invokes a filter on a value the same way the compiler does it.472+ """Invokes a filter on a value the same way the compiler does.473 484- Note that on Python 3 this might return a coroutine in case the485- filter is running from an environment in async mode and the filter486- supports async execution. It's your responsibility to await this487- if needed.474+ This might return a coroutine if the filter is running from an475+ environment in async mode and the filter supports async476+ execution. It's your responsibility to await this if needed.477 478 .. versionadded:: 2.7479 """480 func = self.filters.get(name)481 if func is None:493- 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:519- 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):11 unmodified lines524 self.handle_exception(source=source)525 526 def _parse(self, source, name, filename):527 """Internal parsing function used by `parse` and `compile`."""539- return Parser(self, source, name, encode_filename(filename)).parse()528+ return Parser(self, source, name, filename).parse()529 530 def lex(self, source, name=None, filename=None):531 """Lex the given sourcecode and return a generator that yields532 tokens as tuples in the form ``(lineno, token_type, value)``.3 unmodified lines536 This does not perform preprocessing. If you want the preprocessing537 of the extensions to be applied you have to filter source through538 the :meth:`preprocess` method.539 """551- source = text_type(source)540+ source = str(source)541 try:542 return self.lexer.tokeniter(source, name, filename)543 except TemplateSyntaxError:544 self.handle_exception(source=source)5 unmodified lines550 """551 return reduce(552 lambda s, e: e.preprocess(s, name, filename),553 self.iter_extensions(),565- text_type(source),554+ str(source),555 )556 557 def _tokenize(self, source, name, filename=None, state=None):558 """Called by the parser to do the preprocessing and filtering52 unmodified lines611 `defer_init` parameter added.612 """613 source_hint = None614 try:626- if isinstance(source, string_types):615+ if isinstance(source, str):616 source_hint = source617 source = self._parse(source, name, filename)618 source = self._generate(source, name, filename, defer_init=defer_init)619 if raw:620 return source621 if filename is None:622 filename = "<template>"634- else:635- filename = encode_filename(filename)623 return self._compile(source, filename)624 except TemplateSyntaxError:625 self.handle_exception(source=source_hint)626 48 unmodified lines675 filter_func=None,676 zip="deflated",677 log_function=None,678 ignore_errors=True,692- py_compile=False,679 ):680 """Finds all the templates the loader can find, compiles them681 and stores them in `target`. If `zip` is `None`, instead of in a682 zipfile, the templates will be stored in a directory.8 unmodified lines691 log function is provided, errors are logged. If you want template692 syntax errors to abort the compilation you can set `ignore_errors`693 to `False` and you will get an exception on syntax errors.694 709- If `py_compile` is set to `True` .pyc files will be written to the710- target instead of standard .py files. This flag does not do anything711- on pypy and Python 3 where pyc files are not picked up by itself and712- don't give much benefit.713-695 .. versionadded:: 2.4696 """697 from .loaders import ModuleLoader698 1 unmodified line700 701 def log_function(x):702 pass703 723- if py_compile:724- if not PY2 or PYPY:725- import warnings726-727- warnings.warn(728- "'py_compile=True' has no effect on PyPy or Python"729- " 3 and will be removed in version 3.0",730- DeprecationWarning,731- stacklevel=2,732- )733- py_compile = False734- else:735- import imp736- import marshal737-738- py_header = imp.get_magic() + u"\xff\xff\xff\xff".encode("iso-8859-15")739-740- # Python 3.3 added a source filesize to the header741- if sys.version_info >= (3, 3):742- py_header += u"\x00\x00\x00\x00".encode("iso-8859-15")743-704 def write_file(filename, data):705 if zip:706 info = ZipInfo(filename)707 info.external_attr = 0o755 << 16708 zip_file.writestr(info, data)709 else:750- if isinstance(data, text_type):710+ if isinstance(data, str):711 data = data.encode("utf8")712 713 with open(os.path.join(target, filename), "wb") as f:714 f.write(data)3 unmodified lines718 719 zip_file = ZipFile(720 target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]721 )762- 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)766- 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 raise776- 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 781- if py_compile:782- c = self._compile(code, encode_filename(filename))783- write_file(filename + "c", py_header + marshal.dumps(c))784- log_function('Byte-compiled "%s" as %s' % (name, filename + "c"))785- else:786- write_file(filename, code)787- log_function('Compiled "%s" as %s' % (name, filename))741+ write_file(filename, code)742+ log_function(f'Compiled "{name}" as {filename}')743 finally:744 if zip:745 zip_file.close()746 36 unmodified lines783 rewritten exceptions or return a rendered traceback for the template.784 """785 from .debug import rewrite_traceback_stack786 832- reraise(*rewrite_traceback_stack(source=source))787+ raise rewrite_traceback_stack(source=source)788 789 def join_path(self, template, parent):790 """Join a template with the parent. By default all the lookups are791 relative to the loader root so this method returns the `template`66 unmodified lines858 names._fail_with_undefined_error()859 860 if not names:861 raise TemplatesNotFound(907- 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):13 unmodified lines880 :meth:`get_template`.881 882 .. versionadded:: 2.3883 """929- if isinstance(template_name_or_list, (string_types, Undefined)):884+ if isinstance(template_name_or_list, (str, Undefined)):885 return self.get_template(template_name_or_list, parent, globals)886 elif isinstance(template_name_or_list, Template):887 return template_name_or_list888 return self.select_template(template_name_or_list, parent, globals)12 unmodified lines901 return self.globals902 return dict(self.globals, **d)903 904 950-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` but125 unmodified lines1035 1036 template.render(knights='that say nih')1037 template.render({'knights': 'that say nih'})1038 1084- This will return the rendered template as unicode string.1039+ This will return the rendered template as a string.1040 """1041 vars = dict(*args, **kwargs)1042 try:1043 return concat(self.root_render_func(self.new_context(vars)))23 unmodified lines1067 def generate(self, *args, **kwargs):1068 """For very large templates it can be useful to not render the whole1069 template at once but evaluate each statement after another and yield1070 piece for piece. This method basically does exactly that and returns1116- a generator that yields one item after another as unicode strings.1071+ a generator that yields one item after another as strings.1072 1073 It accepts the same arguments as :meth:`render`.1074 """1075 vars = dict(*args, **kwargs)1076 try:1122- for event in self.root_render_func(self.new_context(vars)):1123- 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:1216- name = "memory:%x" % id(self)1170+ name = f"memory:{id(self):x}"1171 else:1172 name = repr(self.name)1219- return "<%s %s>" % (self.__class__.__name__, name)1173+ return f"<{self.__class__.__name__} {name}>"1174 1175 1222-@implements_to_string1223-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. Additionally1226- converting it into an unicode- or bytestrings renders the contents.1179+ converting it into a string renders the contents.1180 """1181 1182 def __init__(self, template, context, body_stream=None):1183 if body_stream is None:16 unmodified lines1200 return concat(self._body_stream)1201 1202 def __repr__(self):1203 if self.__name__ is None:1251- name = "memory:%x" % id(self)1204+ name = f"memory:{id(self):x}"1205 else:1206 name = repr(self.__name__)1254- return "<%s %s>" % (self.__class__.__name__, name)1207+ return f"<{self.__class__.__name__} {name}>"1208 1209 1257-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 1276-@implements_iterator1277-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 unbuffered1281- instruction in the template one unicode string is yielded.1233+ instruction in the template one string is yielded.1234 1235 If buffering is enabled with a buffer size of 5, five items are combined1284- into a new unicode string. This is mainly useful if you are streaming1236+ into a new string. This is mainly useful if you are streaming1237 big templates to a client via WSGI which flushes after each iteration.1238 """1239 1240 def __init__(self, gen):1 unmodified line1242 self.disable_buffering()1243 1244 def dump(self, fp, encoding=None, errors="strict"):1245 """Dump the complete stream into a file or file-like object.1294- Per default unicode strings are written, if you want to encode1246+ Per default strings are written, if you want to encode1247 before writing specify an `encoding`.1248 1249 Example usage::1250 1251 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1252 """1253 close = False1302- if isinstance(fp, string_types):1254+ if isinstance(fp, str):1255 if encoding is None:1256 encoding = "utf-8"1257 fp = open(fp, "wb")1258 close = True56 unmodified linesmodified:src/jinja2/exceptions.py+14 added-44 removed
1-# -*- coding: utf-8 -*-2-from ._compat import imap3-from ._compat import implements_to_string4-from ._compat import PY25-from ._compat import text_type6-7-1 class TemplateError(Exception):2 """Baseclass for all template errors."""3 11- if PY2:4+ def __init__(self, message=None):5+ super().__init__(message)6 13- def __init__(self, message=None):14- if message is not None:15- message = text_type(message).encode("utf-8")16- Exception.__init__(self, message)7+ @property8+ def message(self):9+ if self.args:10+ return self.args[0]11 18- @property19- def message(self):20- if self.args:21- message = self.args[0]22- if message is not None:23- return message.decode("utf-8", "replace")12 25- def __unicode__(self):26- return self.message or u""27-28- else:29-30- def __init__(self, message=None):31- Exception.__init__(self, message)32-33- @property34- def message(self):35- if self.args:36- message = self.args[0]37- if message is not None:38- return message39-40-41-@implements_to_string13 class TemplateNotFound(IOError, LookupError, TemplateError):14 """Raised if a template does not exist.15 16 .. versionchanged:: 2.1117 If the given name is :class:`Undefined` and no message was18 provided, an :exc:`UndefinedError` is raised.19 """20 50- # looks weird, but removes the warning descriptor that just51- # bogusly warns us about message being deprecated21+ # Silence the Python warning about message being deprecated since22+ # it's not valid here.23 message = None24 25 def __init__(self, name, message=None):26 IOError.__init__(self, name)37 unmodified lines64 parts.append(name._undefined_message)65 else:66 parts.append(name)67 97- message = u"none of the templates given were found: " + u", ".join(98- imap(text_type, parts)68+ message = "none of the templates given were found: " + ", ".join(69+ map(str, parts)70 )100- 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 104-@implements_to_string75 class TemplateSyntaxError(TemplateError):76 """Raised to tell the user that there is a problem with the template."""77 78 def __init__(self, message, lineno, name=None, filename=None):12 unmodified lines91 if self.translated:92 return self.message93 94 # otherwise attach some stuff125- location = "line %d" % self.lineno95+ location = f"line {self.lineno}"96 name = self.filename or self.name97 if name:128- 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 140- 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+18 added-22 removed
1-# -*- coding: utf-8 -*-1 """Extension API for adding custom tags and behavior."""2 import pprint3 import re4 from sys import version_info5 6 from markupsafe import Markup7 8 from . import nodes10-from ._compat import iteritems11-from ._compat import string_types12-from ._compat import with_metaclass9 from .defaults import BLOCK_END_STRING10 from .defaults import BLOCK_START_STRING11 from .defaults import COMMENT_END_STRING12 from .defaults import COMMENT_START_STRING12 unmodified lines25 from .runtime import concat26 from .utils import contextfunction27 from .utils import import_string28 33-# the only real useful gettext functions for a Jinja template. Note34-# that ugettext must be assigned to gettext as Jinja doesn't support35-# non unicode strings.29+# I18N functions available in Jinja templates. If the I18N library30+# provides ugettext, it will be assigned to gettext.31 GETTEXT_FUNCTIONS = ("_", "gettext", "ngettext")37-32 _ws_re = re.compile(r"\s*\n\s*")33 34 35 class ExtensionRegistry(type):36 """Gives the extension an unique identifier."""37 38 def __new__(mcs, name, bases, d):39 rv = type.__new__(mcs, name, bases, d)46- rv.identifier = rv.__module__ + "." + rv.__name__40+ rv.identifier = f"{rv.__module__}.{rv.__name__}"41 return rv42 43 50-class Extension(with_metaclass(ExtensionRegistry, object)):44+class Extension(metaclass=ExtensionRegistry):45 """Extensions can be used to add extra functionality to the Jinja template46 system at the parser level. Custom extensions are bound to an environment47 but may not store environment specific data on `self`. The reason for48 this is that an extension can be bound to another environment (for140 unmodified lines189 newstyle_gettext=False,190 )191 192 def _install(self, translations, newstyle=None):193+ # ugettext and ungettext are preferred in case the I18N library194+ # is providing compatibility with older Python versions.195 gettext = getattr(translations, "ugettext", None)196 if gettext is None:197 gettext = translations.gettext198 ngettext = getattr(translations, "ungettext", None)2 unmodified lines201 self._install_callables(gettext, ngettext, newstyle)202 203 def _install_null(self, newstyle=None):204 self._install_callables(209- 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:7 unmodified lines217 for key in "gettext", "ngettext":218 self.environment.globals.pop(key, None)219 220 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):225- if isinstance(source, string_types):221+ if isinstance(source, str):222 source = self.environment.parse(source)223 return extract_from_ast(source, gettext_functions)224 225 def parse(self, parser):18 unmodified lines244 245 name = parser.stream.expect("name")246 if name.value in variables:247 parser.fail(252- "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(300- "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)359- 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"):44 unmodified lines404 # in case newstyle gettext is used, the method is powerful405 # enough to handle the variable expansion and autoescape406 # handling itself407 if self.environment.newstyle_gettext:412- for key, value in iteritems(variables):408+ for key, value in variables.items():409 # the function adds that later anyways in case num was410 # called num, so just skip it.411 if num_called_num and key == "num":412 continue21 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 442- 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 453- tags = set(["break", "continue"])449+ tags = {"break", "continue"}450 451 def parse(self, parser):452 token = next(parser.stream)453 if token.value == "break":79 unmodified lines533 534 * ``lineno`` is the number of the line on which the string was found,535 * ``function`` is the name of the ``gettext`` function used (if the536 string was extracted from embedded Python code), and541- * ``message`` is the string itself (a ``unicode`` object, or a tuple542- of ``unicode`` objects for functions with multiple string arguments).537+ * ``message`` is the string, or a tuple of strings for functions538+ with multiple string arguments.539 540 This extraction function operates on the AST and is because of that unable541 to extract any comments. For comment support you have to use the babel542 extraction interface or extract comments yourself.6 unmodified lines549 continue550 551 strings = []552 for arg in node.args:557- if isinstance(arg, nodes.Const) and isinstance(arg.value, string_types):553+ if isinstance(arg, nodes.Const) and isinstance(arg.value, str):554 strings.append(arg.value)555 else:556 strings.append(None)557 15 unmodified lines573 strings = tuple(strings)574 yield node.lineno, node.node.name, strings575 576 581-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+64 added-85 removed
1-# -*- coding: utf-8 -*-1 """Built-in template filters used with the ``|`` operator."""2 import math3 import random4 import re6-import warnings5+from collections import abc6 from collections import namedtuple7 from itertools import chain8 from itertools import groupby9 10 from markupsafe import escape11 from markupsafe import Markup13-from markupsafe import soft_unicode12+from markupsafe import soft_str13 15-from ._compat import abc16-from ._compat import imap17-from ._compat import iteritems18-from ._compat import string_types19-from ._compat import text_type14 from .exceptions import FilterArgumentError15 from .runtime import Undefined16 from .utils import htmlsafe_json_dumps17 from .utils import pformat24-from .utils import unicode_urlencode18+from .utils import url_quote19 from .utils import urlize20 27-_word_re = re.compile(r"\w+", re.UNICODE)28-_word_beginning_split_re = re.compile(r"([-\s\(\{\[\<]+)", re.UNICODE)21+_word_re = re.compile(r"\w+")22+_word_beginning_split_re = re.compile(r"([-\s({\[<]+)")23 24 25 def contextfilter(f):26 """Decorator for marking context dependent filters. The current24 unmodified lines51 52 def ignore_case(value):53 """For use as a postprocessor for :func:`make_attrgetter`. Converts strings54 to lowercase and returns other types as-is."""61- return value.lower() if isinstance(value, string_types) else value55+ return value.lower() if isinstance(value, str) else value56 57 58 def make_attrgetter(environment, attribute, postprocess=None, default=None):59 """Returns a callable that looks up the given attribute from a29 unmodified lines89 90 Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.91 """92 attribute_parts = (99- attribute.split(",") if isinstance(attribute, string_types) else [attribute]93+ attribute.split(",") if isinstance(attribute, str) else [attribute]94 )95 attribute = [96 _prepare_attribute_parts(attribute_part) for attribute_part in attribute_parts97 ]16 unmodified lines114 115 def _prepare_attribute_parts(attr):116 if attr is None:117 return []124- elif isinstance(attr, string_types):118+ elif isinstance(attr, str):119 return [int(x) if x.isdigit() else x for x in attr.split(".")]120 else:121 return [attr]122 1 unmodified line124 def do_forceescape(value):125 """Enforce HTML escaping. This will probably double escape variables."""126 if hasattr(value, "__html__"):127 value = value.__html__()134- return escape(text_type(value))128+ return escape(str(value))129 130 131 def do_urlencode(value):132 """Quote data for use in a URL path or query using UTF-8.10 unmodified lines143 ``|replace("/", "%2F")`` filter.144 145 .. versionadded:: 2.7146 """153- if isinstance(value, string_types) or not isinstance(value, abc.Iterable):154- return unicode_urlencode(value)147+ if isinstance(value, str) or not isinstance(value, abc.Iterable):148+ return url_quote(value)149 150 if isinstance(value, dict):157- items = iteritems(value)151+ items = value.items()152 else:153 items = iter(value)154 161- return u"&".join(162- "%s=%s" % (unicode_urlencode(k, for_qs=True), unicode_urlencode(v, for_qs=True))163- 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 @evalcontextfilter14 unmodified lines175 """176 if count is None:177 count = -1178 if not eval_ctx.autoescape:186- return text_type(s).replace(text_type(old), text_type(new), count)179+ return str(s).replace(str(old), str(new), count)180 if (181 hasattr(old, "__html__")182 or hasattr(new, "__html__")183 and not hasattr(s, "__html__")184 ):185 s = escape(s)186 else:194- s = soft_unicode(s)195- return s.replace(soft_unicode(old), soft_unicode(new), count)187+ s = soft_str(s)188+ return s.replace(soft_str(old), soft_str(new), count)189 190 191 def do_upper(s):192 """Convert a value to uppercase."""200- return soft_unicode(s).upper()193+ return soft_str(s).upper()194 195 196 def do_lower(s):197 """Convert a value to lowercase."""205- return soft_unicode(s).lower()198+ return soft_str(s).lower()199 200 201 @evalcontextfilter202 def do_xmlattr(_eval_ctx, d, autospace=True):18 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 """232- rv = u" ".join(233- u'%s="%s"' % (escape(key), escape(value))234- for key, value in iteritems(d)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:238- rv = u" " + rv231+ rv = " " + rv232 if _eval_ctx.autoescape:233 rv = Markup(rv)234 return rv235 1 unmodified line237 def do_capitalize(s):238 """Capitalize a value. The first character will be uppercase, all others239 lowercase.240 """248- return soft_unicode(s).capitalize()241+ return soft_str(s).capitalize()242 243 244 def do_title(s):245 """Return a titlecased version of the value. I.e. words will start with1 unmodified line247 """248 return "".join(249 [250 item[0].upper() + item[1:].lower()258- for item in _word_beginning_split_re.split(soft_unicode(s))251+ for item in _word_beginning_split_re.split(soft_str(s))252 if item253 ]254 )255 156 unmodified lines412 """413 return _min_or_max(environment, value, max, case_sensitive, attribute)414 415 423-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 @evalcontextfilter452-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 14 unmodified lines464 .. versionadded:: 2.6465 The `attribute` parameter was added.466 """467 if attribute is not None:475- value = imap(make_attrgetter(eval_ctx.environment, attribute), value)468+ value = map(make_attrgetter(eval_ctx.environment, attribute), value)469 470 # no automatic escaping? joining is a lot easier then471 if not eval_ctx.autoescape:479- return text_type(d).join(imap(text_type, value))472+ return str(d).join(map(str, value))473 474 # if the delimiter doesn't have an html representation we check475 # if any of the items has. If yes we do a coercion to Markup476 if not hasattr(d, "__html__"):2 unmodified lines479 for idx, item in enumerate(value):480 if hasattr(item, "__html__"):481 do_escape = True482 else:490- value[idx] = text_type(item)483+ value[idx] = str(item)484 if do_escape:485 d = escape(d)486 else:494- d = text_type(d)487+ d = str(d)488 return d.join(value)489 490 # no html involved, to normal joining498- return soft_unicode(d).join(imap(soft_unicode, value))491+ return soft_str(d).join(map(soft_str, value))492 493 494 def do_center(value, width=80):495 """Centers the value in a field of a given width."""503- return text_type(value).center(width)496+ return str(value).center(width)497 498 499 @environmentfilter500 def do_first(environment, seq):37 unmodified lines538 Giga, etc.), if the second parameter is set to `True` the binary539 prefixes are used (Mebi, Gibi).540 """541 bytes = float(value)549- base = binary and 1024 or 1000542+ base = 1024 if binary else 1000543 prefixes = [551- (binary and "KiB" or "kB"),552- (binary and "MiB" or "MB"),553- (binary and "GiB" or "GB"),554- (binary and "TiB" or "TB"),555- (binary and "PiB" or "PB"),556- (binary and "EiB" or "EB"),557- (binary and "ZiB" or "ZB"),558- (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:563- 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:568- return "%.1f %s" % ((base * bytes / unit), prefix)569- 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 572-def do_pprint(value, verbose=False):573- """Pretty print a variable. Useful for debugging.565+def do_pprint(value):566+ """Pretty print a variable. Useful for debugging."""567+ return pformat(value)568 575- With Jinja 1.2 onwards you can pass it a parameter. If this parameter576- is truthy the output will be more verbose (this requires `pretty`)577- """578- return pformat(value, verbose=verbose)569 580-570 @evalcontextfilter571 def do_urlize(572 eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None573 ):14 unmodified lines588 .. sourcecode:: jinja589 590 {{ mytext|urlize(40, target='_blank') }}591 603- .. versionchanged:: 2.8+604- The *target* parameter was added.592+ .. versionchanged:: 2.8593+ The ``target`` parameter was added.594 """595 policies = eval_ctx.environment.policies596 rel = set((rel or "").split() or [])597 if nofollow:7 unmodified lines605 rv = Markup(rv)606 return rv607 608 620-def do_indent(s, width=4, first=False, blank=False, indentfirst=None):609+def do_indent(s, width=4, first=False, blank=False):610 """Return a copy of the string with each line indented by 4 spaces. The611 first line and blank lines are not indented by default.612 613 :param width: Number of spaces to indent by.4 unmodified lines618 Blank lines are not indented by default.619 620 Rename the ``indentfirst`` argument to ``first``.621 """633- if indentfirst is not None:634- warnings.warn(635- "The 'indentfirst' argument is renamed to 'first' and will"636- " be removed in version 3.0.",637- DeprecationWarning,638- stacklevel=2,639- )640- first = indentfirst622+ indention = " " * width623+ newline = "\n"624 642- indention = u" " * width643- newline = u"\n"644-625 if isinstance(s, Markup):626 indention = Markup(indention)627 newline = Markup(newline)628 42 unmodified lines671 can be reconfigured globally.672 """673 if leeway is None:674 leeway = env.policies["truncate.leeway"]695- assert length >= len(end), "expected length >= %s, got %s" % (len(end), length)696- 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)] + end72 unmodified lines753 0b, 0o and 0x for bases 2, 8 and 16 respectively.754 The base is ignored for decimal numbers and non-string values.755 """756 try:777- if isinstance(value, string_types):757+ if isinstance(value, str):758 return int(value, base)759 return int(value)760 except (TypeError, ValueError):761 # this quirk is necessary so that "42.23"|int gives 42.37 unmodified lines799 if args and kwargs:800 raise FilterArgumentError(801 "can't handle positional and keyword arguments at the same time"802 )823- return soft_unicode(value) % (kwargs or args)803+ return soft_str(value) % (kwargs or args)804 805 806 def do_trim(value, chars=None):807 """Strip leading and trailing characters, by default whitespace."""828- return soft_unicode(value).strip(chars)808+ return soft_str(value).strip(chars)809 810 811 def do_striptags(value):812 """Strip SGML/XML tags and replace adjacent whitespace by one space."""813 if hasattr(value, "__html__"):814 value = value.__html__()835- return Markup(text_type(value)).striptags()815+ return Markup(str(value)).striptags()816 817 818 def do_slice(value, slices, fill_with=None):819 """Slice an iterator and return a list of lists containing164 unmodified lines984 The `attribute` parameter was added to allow suming up over985 attributes. Also the `start` parameter was moved on to the right.986 """987 if attribute is not None:1008- iterable = imap(make_attrgetter(environment, attribute), iterable)988+ iterable = map(make_attrgetter(environment, attribute), iterable)989 return sum(iterable, start)990 991 992 def do_list(value):11 unmodified lines1004 1005 1006 def do_mark_unsafe(value):1007 """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""1028- return text_type(value)1008+ return str(value)1009 1010 1011 def do_reverse(value):1012 """Reverse the object or return an iterator that iterates over it the other1013 way round.1014 """1035- if isinstance(value, string_types):1015+ if isinstance(value, str):1016 return value[::-1]1017 try:1018 return reversed(value)1019 except TypeError:222 unmodified lines1242 1243 def prepare_map(args, kwargs):1244 context = args[0]1245 seq = args[1]1266- 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(1273- "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:86 unmodified lines1343 "select": do_select,1344 "selectattr": do_selectattr,1345 "slice": do_slice,1346 "sort": do_sort,1368- "string": soft_unicode,1347+ "string": soft_str,1348 "striptags": do_striptags,1349 "sum": do_sum,1350 "title": do_title,1351 "trim": do_trim,10 unmodified linesmodified:src/jinja2/idtracking.py+7 added-8 removed
1-from ._compat import iteritems1 from .visitor import NodeVisitor2 3 VAR_LOAD_PARAMETER = "param"4 VAR_LOAD_RESOLVE = "resolve"14 unmodified lines19 sym.analyze_node(node)20 return sym21 22 24-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):42- 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(64- "Tried to resolve a name to a reference that "65- "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):43 unmodified lines112 self.refs.update(sym.refs)113 self.loads.update(sym.loads)114 self.stores.update(sym.stores)115 117- for name, branch_count in iteritems(stores):116+ for name, branch_count in stores.items():117 if branch_count == len(branch_symbols):118 continue119 target = self.find_ref(name)120 assert target is not None, "should not happen"18 unmodified lines139 def dump_param_targets(self):140 rv = set()141 node = self142 while node is not None:144- for target, (instr, _) in iteritems(self.loads):143+ for target, (instr, _) in self.loads.items():144 if instr == VAR_LOAD_PARAMETER:145 rv.add(target)146 node = node.parent147 return rv50 unmodified lines198 self.sym_visitor.visit(child)199 200 def generic_visit(self, node, *args, **kwargs):201 raise NotImplementedError(203- "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+52 added-103 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.1 unmodified line6 import re7 from ast import literal_eval8 from collections import deque9 from operator import itemgetter10+from sys import intern11 12-from ._compat import implements_iterator13-from ._compat import intern14-from ._compat import iteritems15-from ._compat import text_type12+from ._identifier import pattern as name_re13 from .exceptions import TemplateSyntaxError14 from .utils import LRUCache15 16 # cache for the lexers. Exists in order to be able to have multiple17 # environments with the same lexer18 _lexer_cache = LRUCache(50)19 20 # static regular expressions24-whitespace_re = re.compile(r"\s+", re.U)21+whitespace_re = re.compile(r"\s+")22 newline_re = re.compile(r"(\r\n|\r|\n)")23 string_re = re.compile(24 r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S25 )11 unmodified lines37 """,38 re.IGNORECASE | re.VERBOSE,39 )40 44-try:45- # check if this Python supports Unicode identifiers46- compile("föö", "<unknown>", "eval")47-except SyntaxError:48- # Python 2, no Unicode support, use ASCII identifiers49- name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*")50- check_ident = False51-else:52- # Unicode support, import generated re pattern and set flag to use53- # str.isidentifier to validate during lexing.54- from ._identifier import pattern as name_re55-56- check_ident = True57-41 # internal the tokens and keep references to them42 TOKEN_ADD = intern("add")43 TOKEN_ASSIGN = intern("assign")44 TOKEN_COLON = intern("colon")73 unmodified lines118 ",": TOKEN_COMMA,119 ";": TOKEN_SEMICOLON,120 }121 139-reverse_operators = dict([(v, k) for k, v in iteritems(operators)])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(142- "(%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 246-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):296- 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 299-@implements_iterator300-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 320-@implements_iterator321-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(406- "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(412- "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):456- return super(OptionalLStrip, cls).__new__(cls, members)437+ return super().__new__(cls, members)438 439 459-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 enabled493- 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 (507- c(508- "(.*?)(?:%s)"509- % "|".join(510- [511- r"(?P<raw_begin>%s(\-|\+|)\s*raw\s*(?:\-%s\s*|%s))"512- % (513- e(environment.block_start_string),514- e(environment.block_end_string),515- e(environment.block_end_string),516- )517- ]518- + [519- r"(?P<%s>%s(\-|\+|))" % (n, r)520- for n, r in root_tag_rules521- ]522- )523- ),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(534- r"(.*?)((?:\-%s\s*|%s)%s)"535- % (536- e(environment.comment_end_string),537- e(environment.comment_end_string),538- block_suffix_re,539- )512+ fr"(.*?)((?:\-{comment_end_re}\s*"513+ fr"|{comment_end_re}){block_suffix_re})"514 ),515 (TOKEN_COMMENT, TOKEN_COMMENT_END),516 "#pop",517 ),544- (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 (549- c(550- r"(?:\-%s\s*|%s)%s"551- % (552- e(environment.block_end_string),553- e(environment.block_end_string),554- block_suffix_re,555- )556- ),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 (565- c(566- r"\-%s\s*|%s"567- % (568- e(environment.variable_end_string),569- e(environment.variable_end_string),570- )571- ),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(581- r"(.*?)((?:%s(\-|\+|))\s*endraw\s*(?:\-%s\s*|%s%s))"582- % (583- e(environment.block_start_string),584- e(environment.block_end_string),585- e(environment.block_end_string),586- block_suffix_re,587- )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 ),592- (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")9 unmodified lines562 ],563 }564 565 def _normalize_newlines(self, value):610- """Called for strings and template data to normalize it to unicode."""566+ """Replace all newlines with the configured sequence in strings567+ and template data.568+ """569 return newline_re.sub(self.newline_sequence, value)570 571 def tokenize(self, source, name=None, filename=None, state=None):572 """Calls tokeniter + tokenize and wraps it in a token stream."""19 unmodified lines592 elif token == "keyword":593 token = value594 elif token == TOKEN_NAME:595 value = str(value)638- if check_ident and not value.isidentifier():596+ if not value.isidentifier():597 raise TemplateSyntaxError(598 "Invalid character in identifier", lineno, name, filename599 )600 elif token == TOKEN_STRING:19 unmodified lines620 def tokeniter(self, source, name, filename=None, state=None):621 """This method tokenizes the text and returns the tokens in a622 generator. Use this method if you just want to tokenize a template.623 """666- source = text_type(source)624 lines = source.splitlines()625 if self.keep_trailing_newline and source:669- for newline in ("\r\n", "\r", "\n"):670- if source.endswith(newline):671- lines.append("")626+ if source.endswith(("\r\n", "\r", "\n")):627+ lines.append("")672- break628 source = "\n".join(lines)629 pos = 0630 lineno = 1631 stack = ["root"]64 unmodified lines696 # bygroup is a bit more complex, in that case we697 # yield for the current token the first named698 # group that matched699 elif token == "#bygroup":745- for key, value in iteritems(m.groupdict()):700+ for key, value in m.groupdict().items():701 if value is not None:702 yield lineno, key, value703 lineno += value.count("\n")704 break705 else:706 raise RuntimeError(752- "%r wanted to resolve "753- "the token dynamically"754- " 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(777- "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(782- "unexpected '%s', "783- "expected '%s'" % (data, expected_op),736+ f"unexpected '{data}', expected '{expected_op}'",737 lineno,738 name,739 filename,740 )13 unmodified lines754 if new_state == "#pop":755 stack.pop()756 # resolve the new state by group checking757 elif new_state == "#bygroup":805- for key, value in iteritems(m.groupdict()):758+ for key, value in m.groupdict().items():759 if value is not None:760 stack.append(key)761 break762 else:763 raise RuntimeError(811- "%r wanted to resolve the "812- "new state dynamically but"813- " 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(824- "%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(837- "unexpected char %r at %d" % (source[pos], pos),838- lineno,839- name,840- filename,789+ f"unexpected char {source[pos]!r} at {pos}", lineno, name, filename790 )modified:src/jinja2/loaders.py+25 added-35 removed
1-# -*- coding: utf-8 -*-1 """API and implementations for loading templates from different data2 sources.3 """4 import os5 import pkgutil6 import sys7 import weakref8+from collections import abc9 from hashlib import sha110 from importlib import import_module11-from os import path11 from types import ModuleType12 14-from ._compat import abc15-from ._compat import fspath16-from ._compat import iteritems17-from ._compat import string_types13 from .exceptions import TemplateNotFound14 from .utils import internalcode15 from .utils import open_if_exists16 4 unmodified lines21 """22 pieces = []23 for piece in template.split("/"):24 if (30- path.sep in piece31- or (path.altsep and path.altsep in piece)32- or piece == path.pardir25+ os.path.sep in piece26+ or (os.path.altsep and os.path.altsep in piece)27+ or piece == os.path.pardir28 ):29 raise TemplateNotFound(template)30 elif piece and piece != ".":31 pieces.append(piece)32 return pieces33 34 40-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.31 unmodified lines71 tuple in the form ``(source, filename, uptodate)`` or raise a72 `TemplateNotFound` error if it can't locate the template.73 74 The source part of the returned tuple must be the source of the80- template as unicode string or a ASCII bytestring. The filename should81- be the name of the file on the filesystem if it was loaded from there,82- otherwise `None`. The filename is used by python for the tracebacks75+ template as a string. The filename should be the name of the76+ file on the filesystem if it was loaded from there, otherwise77+ ``None``. The filename is used by Python for the tracebacks78 if no loader extension is used.79 80 The last item in the tuple is the `uptodate` function. If auto81 reloading is enabled it's always called to check if the template2 unmodified lines84 the template will be reloaded.85 """86 if not self.has_source_access:87 raise RuntimeError(93- "%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):64 unmodified lines157 The ``followlinks`` parameter was added.158 """159 160 def __init__(self, searchpath, encoding="utf-8", followlinks=False):166- if not isinstance(searchpath, abc.Iterable) or isinstance(167- searchpath, string_types168- ):161+ if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):162 searchpath = [searchpath]163 171- # In Python 3.5, os.path.join doesn't support Path. This can be172- # simplified to list(searchpath) when Python 3.5 is dropped.173- self.searchpath = [fspath(p) for p in searchpath]174-164+ self.searchpath = list(searchpath)165 self.encoding = encoding166 self.followlinks = followlinks167 168 def get_source(self, environment, template):169 pieces = split_template_path(template)170 for searchpath in self.searchpath:181- filename = path.join(searchpath, *pieces)171+ filename = os.path.join(searchpath, *pieces)172 f = open_if_exists(filename)173 if f is None:174 continue175 try:176 contents = f.read().decode(self.encoding)177 finally:178 f.close()179 190- mtime = path.getmtime(filename)180+ mtime = os.path.getmtime(filename)181 182 def uptodate():183 try:194- return path.getmtime(filename) == mtime184+ return os.path.getmtime(filename) == mtime185 except OSError:186 return False187 188 return contents, filename, uptodate86 unmodified lines275 break276 277 if self._template_root is None:278 raise ValueError(289- "The %r package was not installed in a way that"290- " 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))61 unmodified lines346 return results347 348 349 class DictLoader(BaseLoader):360- """Loads a template from a python dict. It's passed a dict of unicode361- strings bound to template names. This loader is useful for unittesting:350+ """Loads a template from a Python dict mapping template names to351+ template source. This loader is useful for unittesting:352 353 >>> loader = DictLoader({'index.html': 'source here'})354 355 Because auto reloading is rarely useful this is disabled per default.14 unmodified lines370 371 class FunctionLoader(BaseLoader):372 """A loader that is passed a function which does the loading. The373 function receives the name of the template and has to return either384- an unicode string with the template source, a tuple in the form ``(source,374+ a string with the template source, a tuple in the form ``(source,375 filename, uptodatefunc)`` or `None` if the template does not exist.376 377 >>> def load_template(name):378 ... if name == 'index.html':13 unmodified lines392 def get_source(self, environment, template):393 rv = self.load_func(template)394 if rv is None:395 raise TemplateNotFound(template)406- elif isinstance(rv, string_types):396+ elif isinstance(rv, str):397 return rv, None, None398 return rv399 400 44 unmodified lines445 raise TemplateNotFound(name)446 447 def list_templates(self):448 result = []459- for prefix, loader in iteritems(self.mapping):449+ for prefix, loader in self.mapping.items():450 for template in loader.list_templates():451 result.append(prefix + self.delimiter + template)452 return result453 58 unmodified lines512 513 has_source_access = False514 515 def __init__(self, path):526- 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)521 532- if not isinstance(path, abc.Iterable) or isinstance(path, string_types):522+ if not isinstance(path, abc.Iterable) or isinstance(path, str):523 path = [path]524 535- mod.__path__ = [fspath(p) for p in path]525+ mod.__path__ = [os.fspath(p) for p in path]526 527 sys.modules[package_name] = weakref.proxy(528 mod, lambda x: sys.modules.pop(package_name, None)529 )14 unmodified lines544 545 @internalcode546 def load(self, environment, name, globals=None):547 key = self.get_template_key(name)558- 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+5 added-8 removed
1-# -*- coding: utf-8 -*-1 """Functions that expose information about templates that might be2 interesting for introspection.3 """4 from . import nodes6-from ._compat import iteritems7-from ._compat import string_types5 from .compiler import CodeGenerator6 7 8 class TrackingCodeGenerator(CodeGenerator):8 unmodified lines17 18 def enter_frame(self, frame):19 """Remember all undeclared identifiers."""20 CodeGenerator.enter_frame(self, frame)24- for _, (action, param) in iteritems(frame.symbols.loads):21+ for _, (action, param) in frame.symbols.loads.items():22 if action == "resolve" and param not in self.environment.globals:23 self.undeclared_identifiers.add(param)24 25 5 unmodified lines31 32 >>> from jinja2 import Environment, meta33 >>> env = Environment()34 >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')38- >>> meta.find_undeclared_variables(ast) == set(['bar'])35+ >>> meta.find_undeclared_variables(ast) == {'bar'}36 True37 38 .. admonition:: Implementation39 31 unmodified lines71 for template_name in node.template.items:72 # something const, only yield the strings and ignore73 # non-string consts that really just make no sense74 if isinstance(template_name, nodes.Const):78- if isinstance(template_name.value, string_types):75+ if isinstance(template_name.value, str):76 yield template_name.value77 # something dynamic in there78 else:79 yield None1 unmodified line81 else:82 yield None83 continue84 # constant is a basestring, direct template name88- if isinstance(node.template.value, string_types):85+ if isinstance(node.template.value, str):86 yield node.template.value87 # a tuple or list (latter *should* not happen) made of consts,88 # yield the consts that are strings. We could warn here for89 # non string values90 elif isinstance(node, nodes.Include) and isinstance(91 node.template.value, (tuple, list)92 ):93 for template_name in node.template.value:97- if isinstance(template_name, string_types):94+ if isinstance(template_name, str):95 yield template_name96 # something else we don't care about, we could warn here97 else:98 yield Nonemodified:src/jinja2/nativetypes.py+4 added-4 removed
2 unmodified lines3 from itertools import chain4 from itertools import islice5 6 from . import nodes7-from ._compat import text_type7 from .compiler import CodeGenerator8 from .compiler import has_safe_repr9 from .environment import Environment10 from .environment import Template20 unmodified lines31 raw = head[0]32 else:33 if isinstance(nodes, types.GeneratorType):34 nodes = chain(head, nodes)36- raw = u"".join([text_type(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):48- return "{quote}{}{quote}".format(literal, quote=raw[0])47+ quote = raw[0]48+ return f"{quote}{literal}{quote}"49 50 return literal51 52 53 class NativeCodeGenerator(CodeGenerator):54 """A code generator which renders Python types by not adding55- ``to_string()`` around output nodes, and using :func:`native_concat`55+ ``str()`` around output nodes, and using :func:`native_concat`56 to convert complex strings back to Python types if possible.57 """58 59 @staticmethod52 unmodified linesmodified:src/jinja2/nodes.py+29 added-65 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 """1 unmodified line6 from collections import deque7 8 from markupsafe import Markup9 11-from ._compat import izip12-from ._compat import PY213-from ._compat import text_type14-from ._compat import with_metaclass15-10 _binop_to_func = {11 "*": operator.mul,12 "/": operator.truediv,13 "//": operator.floordiv,2 unmodified lines16 "+": operator.add,17 "-": operator.sub,18 }19 26-_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,17 unmodified lines46 47 def __new__(mcs, name, bases, d):48 for attr in "fields", "attributes":49 storage = []52- storage.extend(getattr(bases[0], attr, ()))50+ storage.extend(getattr(bases[0] if bases else object, attr, ()))51 storage.extend(d.get(attr, ()))54- assert len(bases) == 1, "multiple inheritance not allowed"52+ assert len(bases) <= 1, "multiple inheritance not allowed"53 assert len(storage) == len(set(storage)), "layout conflict"54 d[attr] = tuple(storage)55 d.setdefault("abstract", False)56 return type.__new__(mcs, name, bases, d)57 58 61-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(86- "if no eval context is passed, the "87- "node must have an attached "88- "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 90 94-class Node(with_metaclass(NodeType, object)):91+class Node(metaclass=NodeType):92 """Baseclass for all Jinja nodes. There are a number of nodes available93 of different types. There are four major types:94 95 - :class:`Stmt`: statements18 unmodified lines114 raise TypeError("abstract nodes are not instantiable")115 if fields:116 if len(fields) != len(self.fields):117 if not self.fields:121- raise TypeError("%r takes 0 arguments" % self.__class__.__name__)118+ raise TypeError(f"{self.__class__.__name__!r} takes 0 arguments")119 raise TypeError(123- "%r takes 0 or %d argument%s"124- % (125- self.__class__.__name__,126- len(self.fields),127- len(self.fields) != 1 and "s" or "",128- )120+ f"{self.__class__.__name__!r} takes 0 or {len(self.fields)}"121+ f" argument{'s' if len(self.fields) != 1 else ''}"122 )130- for name, arg in izip(self.fields, fields):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:135- 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 child182- for result in child.find_all(node_type):183- 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 the28 unmodified lines208 todo.extend(node.iter_child_nodes())209 return self210 211 def __eq__(self, other):220- return type(self) is type(other) and tuple(self.iter_fields()) == tuple(221- other.iter_fields()222- )212+ if type(self) is not type(other):213+ return NotImplemented214 224- def __ne__(self, other):225- return not self.__eq__(other)215+ return tuple(self.iter_fields()) == tuple(other.iter_fields())216 227- # Restore Python 2 hashing behavior on Python 3228- __hash__ = object.__hash__217+ def __hash__(self):218+ return hash(tuple(self.iter_fields()))219 220 def __repr__(self):231- return "%s(%s)" % (232- self.__class__.__name__,233- ", ".join("%s=%r" % (arg, getattr(self, arg, None)) for arg in self.fields),234- )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 242- 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):262 unmodified lines497 498 fields = ("value",)499 500 def as_const(self, eval_ctx=None):513- rv = self.value514- if (515- PY2516- and type(rv) is text_type517- and self.environment.policies["compiler.ascii_str"]518- ):519- try:520- rv = rv.encode("ascii")521- except UnicodeError:522- pass523- return rv501+ return self.value502 503 @classmethod504 def from_untrusted(cls, value, lineno=None, environment=None):505 """Return a const object if the value is representable as135 unmodified lines641 642 if eval_ctx.volatile or self.node is None:643 raise Impossible()644 667- # we have to be careful here because we call filter_ below.668- # if this variable would be called filter, 2to3 would wrap the669- # call in a list because it is assuming we are talking about the670- # builtin filter function here which no longer returns a list in671- # python 3. because of that, do not rename filter_ to filter!645 filter_ = self.environment.filters.get(self.name)646 647 if filter_ is None or getattr(filter_, "contextfilter", False) is True:648 raise Impossible()111 unmodified lines760 return slice(const(self.start), const(self.stop), const(self.step))761 762 763 class Concat(Expr):791- """Concatenates the list of expressions provided after converting them to792- unicode.764+ """Concatenates the list of expressions provided after converting765+ them to strings.766 """767 768 fields = ("nodes",)769 770 def as_const(self, eval_ctx=None):771 eval_ctx = get_eval_context(self, eval_ctx)799- return "".join(text_type(x.as_const(eval_ctx)) for x in self.nodes)772+ return "".join(str(x.as_const(eval_ctx)) for x in self.nodes)773 774 775 class Compare(Expr):776 """Compares an expression with some other expressions. `ops` must be a26 unmodified lines803 804 fields = ("op", "expr")805 806 834-if __debug__:835- Operand.__doc__ += "\nThe following operators are available: " + ", ".join(836- sorted(837- "``%s``" % x838- for x in set(_binop_to_func) | set(_uaop_to_func) | set(_cmpop_to_func)839- )840- )841-842-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+16 added-21 removed
1-# -*- coding: utf-8 -*-1 """Parse tokens from the lexer into nodes for the compiler."""2 from . import nodes4-from ._compat import imap3 from .exceptions import TemplateAssertionError4 from .exceptions import TemplateSyntaxError5 from .lexer import describe_token6 from .lexer import describe_token_expr25 unmodified lines32 "mod": nodes.Mod,33 }34 35 38-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 22 unmodified lines63 64 def _fail_ut_eof(self, name, end_token_stack, lineno):65 expected = []66 for exprs in end_token_stack:69- expected.extend(imap(describe_token_expr, exprs))67+ expected.extend(map(describe_token_expr, exprs))68 if end_token_stack:69 currently_looking = " or ".join(72- "'%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:80- 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(85- "You probably made a nesting mistake. Jinja "86- "is expecting this tag, but currently looking "87- "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(91- "Jinja was looking for the following tags: "92- "%s." % currently_looking88+ f"Jinja was looking for the following tags: {currently_looking}."89 )90 91 if self._tag_stack:92 message.append(97- "The innermost block that needs to be "98- "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)129- 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(268- "Block names in Jinja have to be valid Python "269- "identifiers and may not contain hyphens, use an "270- "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(438- "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:599- 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(661- "Expected an expression, got '%s'"662- % 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+88 added-183 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 chain5 from types import MethodType6 7 from markupsafe import escape # noqa: F4018 from markupsafe import Markup9-from markupsafe import soft_unicode9+from markupsafe import soft_str10 11-from ._compat import abc12-from ._compat import imap13-from ._compat import implements_iterator14-from ._compat import implements_to_string15-from ._compat import iteritems16-from ._compat import PY217-from ._compat import string_types18-from ._compat import text_type19-from ._compat import with_metaclass11 from .exceptions import TemplateNotFound # noqa: F40112 from .exceptions import TemplateRuntimeError # noqa: F40113 from .exceptions import UndefinedError14 from .nodes import EvalContext14 unmodified lines29 "missing",30 "concat",31 "escape",32 "markup_join",42- "unicode_join",43- "to_string",33+ "str_join",34 "identity",35 "TemplateNotFound",36 "Namespace",37 "Undefined",38 ]39 50-#: the name of the function that is used to convert something into51-#: a string. We can just use the text type here.52-to_string = text_type40 54-41 def identity(x):42 """Returns its argument. Useful for certain things in the43 environment.44 """45 return x46 47 48 def markup_join(seq):63- """Concatenation that escapes if necessary and converts to unicode."""49+ """Concatenation that escapes if necessary and converts to string."""50 buf = []65- iterator = imap(soft_unicode, seq)51+ iterator = map(soft_str, seq)52 for arg in iterator:53 buf.append(arg)54 if hasattr(arg, "__html__"):69- 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):60+ """Simple args to string conversion and concatenation."""61+ return concat(map(str, seq))62+63+64 def unicode_join(seq):74- """Simple args to unicode conversion and concatenation."""75- return concat(imap(text_type, seq))65+ import warnings66 67+ warnings.warn(68+ "This template must be recompiled with at least Jinja 3.0, or"69+ " it will fail in 3.1.",70+ DeprecationWarning,71+ stacklevel=2,72+ )73+ return str_join(seq)74 75+76 def new_context(77 environment,78 template_name,79 blocks,13 unmodified lines93 # if the parent is shared a copy should be created because94 # we don't want to modify the dict passed95 if shared:96 parent = dict(parent)99- for key, value in iteritems(locals):97+ for key, value in locals.items():98 if value is not missing:99 parent[key] = value100 return environment.context_class(environment, parent, template_name, blocks)101 102 105-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):116- 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)33 unmodified lines152 return context.parent[key]153 return missing154 155 158-class Context(with_metaclass(ContextMeta)):156+@abc.Mapping.register157+class Context(metaclass=ContextMeta):158 """The template context holds the variables of a template. It stores the159 values passed to the template and also the names the template exports.160 Creating instances is neither supported nor useful as it's created161 automatically at various stages of the template evaluation and should not27 unmodified lines189 190 # create the initial mapping of blocks. Whenever template inheritance191 # takes place the runtime will update this mapping with the new blocks192 # from the template.194- self.blocks = dict((k, [v]) for k, v in iteritems(blocks))193+ self.blocks = {k: [v] for k, v in blocks.items()}194 195 # In case we detect the fast resolve mode we can set up an alias196 # here that bypasses the legacy code logic.197 if self._fast_resolve_mode:6 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 is3 unmodified lines301 context = new_context(302 self.environment, self.name, {}, self.get_all(), True, None, locals303 )304 context.eval_ctx = self.eval_ctx307- context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))305+ context.blocks.update((k, list(v)) for k, v in self.blocks.items())306 return context307 308 def _all(meth): # noqa: B902309 def proxy(self):5 unmodified lines315 316 keys = _all("keys")317 values = _all("values")318 items = _all("items")321-322- # not available on python 3323- if PY2:324- iterkeys = _all("iterkeys")325- itervalues = _all("itervalues")326- iteritems = _all("iteritems")319 del _all320 321 def __contains__(self, name):322 return name in self.vars or name in self.parent7 unmodified lines330 raise KeyError(key)331 return item332 333 def __repr__(self):342- return "<%s %s of %r>" % (343- self.__class__.__name__,344- repr(self.get_all()),345- self.name,346- )334+ return f"<{self.__class__.__name__} {self.get_all()!r} of {self.name!r}>"335 336 349-abc.Mapping.register(Context)350-351-352-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(366- "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 @internalcode3 unmodified lines359 rv = Markup(rv)360 return rv361 362 378-@implements_iterator363 class LoopContext:364 """A wrapper iterable for dynamic ``for`` loops, with information365 about the loop and iteration.366 """180 unmodified lines547 548 return self._recurse(iterable, self._recurse, depth=self.depth)549 550 def __repr__(self):567- return "<%s %d/%d>" % (self.__class__.__name__, self.index, self.length)551+ return f"<{self.__class__.__name__} {self.index}/{self.length}>"552 553 570-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(659- "macro %r was invoked with two values for "660- "the special caller argument. This is "661- "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(664- "macro %r takes no keyword argument %r"665- % (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(671- "macro %r takes not more than %d argument(s)"672- % (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):685- return "<%s %s>" % (686- self.__class__.__name__,687- self.name is None and "anonymous" or repr(self.name),688- )667+ name = "anonymous" if self.name is None else repr(self.name)668+ return f"<{self.__class__.__name__} {name}>"669 670 691-@implements_to_string692-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:729- return "%r is undefined" % self._undefined_name708+ return f"{self._undefined_name!r} is undefined"709 731- if not isinstance(self._undefined_name, string_types):732- return "%s has no element %r" % (733- object_type_repr(self._undefined_obj),734- self._undefined_name,710+ if not isinstance(self._undefined_name, str):711+ return (712+ f"{object_type_repr(self._undefined_obj)} has no"713+ f" element {self._undefined_name!r}"714 )715 737- return "%r has no attribute %r" % (738- object_type_repr(self._undefined_obj),739- 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):7 unmodified lines730 if name[:2] == "__":731 raise AttributeError(name)732 return self._fail_with_undefined_error()733 755- __add__ = (756- __radd__757- ) = (758- __mul__759- ) = (760- __rmul__761- ) = (762- __div__763- ) = (764- __rdiv__765- ) = (766- __truediv__767- ) = (768- __rtruediv__769- ) = (770- __floordiv__771- ) = (772- __rfloordiv__773- ) = (774- __mod__775- ) = (776- __rmod__777- ) = (778- __pos__779- ) = (780- __neg__781- ) = (782- __call__783- ) = (784- __getitem__785- ) = (786- __lt__787- ) = (788- __le__789- ) = (790- __gt__791- ) = (792- __ge__793- ) = (794- __int__795- ) = (796- __float__797- ) = (798- __complex__799- ) = __pow__ = __rpow__ = __sub__ = __rsub__ = _fail_with_undefined_error734+ __add__ = __radd__ = __sub__ = __rsub__ = _fail_with_undefined_error735+ __mul__ = __rmul__ = __div__ = __rdiv__ = _fail_with_undefined_error736+ __truediv__ = __rtruediv__ = _fail_with_undefined_error737+ __floordiv__ = __rfloordiv__ = _fail_with_undefined_error738+ __mod__ = __rmod__ = _fail_with_undefined_error739+ __pos__ = __neg__ = _fail_with_undefined_error740+ __call__ = __getitem__ = _fail_with_undefined_error741+ __lt__ = __le__ = __gt__ = __ge__ = _fail_with_undefined_error742+ __int__ = __float__ = __complex__ = _fail_with_undefined_error743+ __pow__ = __rpow__ = _fail_with_undefined_error744 745 def __eq__(self, other):746 return type(self) is type(other)747 3 unmodified lines751 def __hash__(self):752 return id(type(self))753 754 def __str__(self):811- return u""755+ return ""756 757 def __len__(self):758 return 0759 760 def __iter__(self):761 if 0:762 yield None763 820- def __nonzero__(self):764+ def __bool__(self):765 return False766 823- __bool__ = __nonzero__824-767 def __repr__(self):768 return "Undefined"769 770 25 unmodified lines796 if base is None:797 base = Undefined798 799 def _log_message(undef):858- if undef._undefined_hint is None:859- if undef._undefined_obj is missing:860- hint = "%s is undefined" % undef._undefined_name861- elif not isinstance(undef._undefined_name, string_types):862- hint = "%s has no element %s" % (863- object_type_repr(undef._undefined_obj),864- undef._undefined_name,865- )866- else:867- hint = "%s has no attribute %s" % (868- object_type_repr(undef._undefined_obj),869- undef._undefined_name,870- )871- else:872- hint = undef._undefined_hint873- 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:878- 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:880- logger.error("Template variable error: %s", str(e))807+ logger.error(f"Template variable error: %s", e)808 raise e809 810 def __str__(self):884- rv = base.__str__(self)811 _log_message(self)886- return rv812+ return super().__str__()813 814 def __iter__(self):889- rv = base.__iter__(self)815 _log_message(self)891- return rv816+ return super().__iter__()817 893- if PY2:818+ def __bool__(self):819+ _log_message(self)820+ return super().__bool__()821 895- def __nonzero__(self):896- rv = base.__nonzero__(self)897- _log_message(self)898- return rv899-900- def __unicode__(self):901- rv = base.__unicode__(self)902- _log_message(self)903- return rv904-905- else:906-907- def __bool__(self):908- rv = base.__bool__(self)909- _log_message(self)910- return rv911-822 return LoggingUndefined823 824 915-# No @implements_to_string decorator here because __str__916-# is not overwritten from Undefined in this class.917-# This would cause a recursion error in Python 2.825 class ChainableUndefined(Undefined):826 """An undefined that is chainable, where both ``__getattr__`` and827 ``__getitem__`` return itself rather than raising an828 :exc:`UndefinedError`.19 unmodified lines848 849 __getitem__ = __getattr__850 851 945-@implements_to_string852 class DebugUndefined(Undefined):853 """An undefined that returns the debug info when printed.854 855 >>> foo = DebugUndefined(name='foo')9 unmodified lines865 866 __slots__ = ()867 868 def __str__(self):963- if self._undefined_hint is None:964- if self._undefined_obj is missing:965- return u"{{ %s }}" % self._undefined_name966- return "{{ no such element: %s[%r] }}" % (967- object_type_repr(self._undefined_obj),968- 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 )970- return u"{{ undefined value printed: %s }}" % self._undefined_hint880 881+ return f"{{{{ {message} }}}}"882 973-@implements_to_string883+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.13 unmodified lines901 jinja2.exceptions.UndefinedError: 'foo' is undefined902 """903 904 __slots__ = ()995- __iter__ = (996- __str__997- ) = (998- __len__999- ) = (1000- __nonzero__1001- ) = __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error905+ __iter__ = __str__ = __len__ = Undefined._fail_with_undefined_error906+ __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error907 908 1004-# remove remaining slots attributes, after the metaclass did the magic they1005-# are unneeded and irritating as they contain wrong data for the subclasses.909+# Remove slots attributes, after the metaclass is applied they are910+# unneeded and contain wrong data for subclasses.911 del (912 Undefined.__slots__,913 ChainableUndefined.__slots__,914 DebugUndefined.__slots__,2 unmodified linesmodified:src/jinja2/sandbox.py+23 added-82 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 operator5 import types7-import warnings6+from _string import formatter_field_name_split7+from collections import abc8 from collections import deque9 from string import Formatter10 11 from markupsafe import EscapeFormatter12 from markupsafe import Markup13 14-from ._compat import abc15-from ._compat import PY216-from ._compat import range_type17-from ._compat import string_types14 from .environment import Environment15 from .exceptions import SecurityError16 17 #: maximum number of items a range may produce18 MAX_RANGE = 10000019 24-#: attributes of function objects that are considered unsafe.25-if PY2:26- UNSAFE_FUNCTION_ATTRIBUTES = {27- "func_closure",28- "func_code",29- "func_dict",30- "func_defaults",31- "func_globals",32- }33-else:34- # On versions > python 2 the special attributes on functions are gone,35- # but they remain on methods and generators for whatever reason.36- UNSAFE_FUNCTION_ATTRIBUTES = set()20+#: Unsafe function attributes.21+UNSAFE_FUNCTION_ATTRIBUTES = set()22 38-#: unsafe method attributes. function attributes are unsafe for methods too39-UNSAFE_METHOD_ATTRIBUTES = {"im_class", "im_func", "im_self"}23+#: Unsafe method attributes. Function attributes are unsafe for methods too.24+UNSAFE_METHOD_ATTRIBUTES = set()25 26 #: unsafe generator attributes.27 UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}28 2 unmodified lines31 32 #: unsafe attributes on async generators33 UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}34 50-# make sure we don't warn in python 2.6 about stuff we don't care about51-warnings.filterwarnings(52- "ignore", "the sets module", DeprecationWarning, module=__name__53-)54-55-_mutable_set_types = (set,)56-_mutable_mapping_types = (dict,)57-_mutable_sequence_types = (list,)58-59-# on python 2.x we can register the user collection types60-try:61- from UserDict import UserDict, DictMixin62- from UserList import UserList63-64- _mutable_mapping_types += (UserDict, DictMixin)65- _mutable_set_types += (UserList,)66-except ImportError:67- pass68-69-# if sets is still available, register the mutable set from there as well70-try:71- from sets import Set72-73- _mutable_set_types += (Set,)74-except ImportError:75- pass76-77-#: register Python 2.6 abstract base classes78-_mutable_set_types += (abc.MutableSet,)79-_mutable_mapping_types += (abc.MutableMapping,)80-_mutable_sequence_types += (abc.MutableSequence,)81-35 _mutable_spec = (36 (84- _mutable_set_types,37+ abc.MutableSet,38 frozenset(39 [40 "add",41 "clear",6 unmodified lines48 ]49 ),50 ),51 (99- _mutable_mapping_types,52+ abc.MutableMapping,53 frozenset(["clear", "pop", "popitem", "setdefault", "update"]),54 ),55 (103- _mutable_sequence_types,56+ abc.MutableSequence,57 frozenset(["append", "reverse", "insert", "sort", "extend", "remove"]),58 ),59 (60 deque,50 unmodified lines111 callable, (types.MethodType, types.BuiltinMethodType)112 ) or callable.__name__ not in ("format", "format_map"):113 return None114 obj = callable.__self__162- if isinstance(obj, string_types):115+ if isinstance(obj, str):116 return obj117 118 119 def safe_range(*args):120 """A range that can't generate ranges with a length of more than121 MAX_RANGE items.122 """170- rng = range_type(*args)123+ rng = range(*args)124 125 if len(rng) > MAX_RANGE:126 raise OverflowError(127 "Range too big. The sandbox blocks ranges larger than"175- " 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 184- ::137+ .. code-block: python138 139 @unsafe140 def delete(self):141 pass40 unmodified lines182 183 184 def modifies_known_mutable(obj, attr):185 """This function checks if an attribute on a builtin mutable object233- (list, dict, set or deque) would modify it if called. It also supports234- the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and235- with Python 2.6 onwards the abstract base classes `MutableSet`,236- `MutableMapping`, and `MutableSequence`.186+ (list, dict, set or deque) or the corresponding ABCs would modify it187+ if called.188 189 >>> modifies_known_mutable({}, "clear")190 True191 >>> modifies_known_mutable({}, "keys")2 unmodified lines194 True195 >>> modifies_known_mutable([], "index")196 False197 247- If called with an unsupported object (such as unicode) `False` is248- returned.198+ If called with an unsupported object, ``False`` is returned.199 200 >>> modifies_known_mutable("foo", "upper")201 False202 """129 unmodified lines332 """Subscribe an object from sandboxed code."""333 try:334 return obj[argument]335 except (TypeError, LookupError):386- if isinstance(argument, string_types):336+ if isinstance(argument, str):337 try:338 attr = str(argument)339 except Exception:340 pass27 unmodified lines368 369 def unsafe_undefined(self, obj, attribute):370 """Return an undefined object for unsafe attributes."""371 return self.undefined(422- "access to attribute %r of %r "423- "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(441- "format_map() takes exactly one argument %d given"442- % (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):461- 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 477-# This really is not a public API apparently.478-try:479- from _string import formatter_field_name_split480-except ImportError:481-482- def formatter_field_name_split(field_name):483- return field_name._formatter_field_name_split()484-485-486-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+7 added-11 removed
1-# -*- coding: utf-8 -*-1 """Built-in template tests used with the ``is`` operator."""3-import decimal2 import operator3 import re4+from collections import abc5+from numbers import Number6 7-from ._compat import abc8-from ._compat import integer_types9-from ._compat import string_types10-from ._compat import text_type7 from .runtime import Undefined8 9 number_re = re.compile(r"^-?\d+(\.\d+)?$")10 regex_type = type(number_re)71 unmodified lines82 """Return true if the object is an integer.83 84 .. versionadded:: 2.1185 """90- return isinstance(value, integer_types) and value is not True and value is not False86+ return isinstance(value, int) and value is not True and value is not False87 88 89 # NOTE: The existing 'number' test matches booleans and integers90 def test_float(value):5 unmodified lines96 97 98 def test_lower(value):99 """Return true if the variable is lowercased."""104- return text_type(value).islower()100+ return str(value).islower()101 102 103 def test_upper(value):104 """Return true if the variable is uppercased."""109- return text_type(value).isupper()105+ return str(value).isupper()106 107 108 def test_string(value):109 """Return true if the object is a string."""114- return isinstance(value, string_types)110+ return isinstance(value, str)111 112 113 def test_mapping(value):114 """Return true if the object is a mapping (dict etc.).4 unmodified lines119 120 121 def test_number(value):122 """Return true if the variable is a number."""127- return isinstance(value, integer_types + (float, complex, decimal.Decimal))123+ return isinstance(value, Number)124 125 126 def test_sequence(value):127 """Return true if the variable is a sequence. Sequences are variables84 unmodified linesmodified:src/jinja2/utils.py+64 added-127 removed
1-# -*- coding: utf-8 -*-1 import json2 import os3 import re5-import warnings4+from collections import abc5 from collections import deque6 from random import choice7 from random import randrange8 from threading import Lock9+from urllib.parse import quote_from_bytes10 11 from markupsafe import escape12 from markupsafe import Markup13 14-from ._compat import abc15-from ._compat import string_types16-from ._compat import text_type17-from ._compat import url_quote18-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(21- "^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$"22- % (23- "|".join(map(re.escape, ("(", "<", "<"))),24- "|".join(map(re.escape, (".", ",", ")", ">", "\n", ">"))),25- )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 39-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:172- name = obj.__class__.__module__ + "." + obj.__class__.__name__173- return "%s object" % name165+ name = f"{obj.__class__.__module__}.{obj.__class__.__name__}"166+ return f"{name} object"167 168 176-def pformat(obj, verbose=False):177- """Prettyprint an object. Either use the `pretty` library or the178- builtin `pprint`.169+def pformat(obj):170+ """Format an object using :func:`pprint.pformat`.171 """180- try:181- from pretty import pretty172+ from pprint import pformat173 183- return pretty(obj, verbose=verbose)184- except ImportError:185- from pprint import pformat174+ return pformat(obj)175 187- return pformat(obj)176 189-177 def urlize(text, trim_url_limit=None, rel=None, target=None):178 """Converts any URLs in text into clickable links. Works on http://,179 https:// and www. links. Links can have trailing punctuation (periods,180 commas, close-parens) and leading punctuation (opening parens) and6 unmodified lines187 attribute.188 189 If target is not None, a target attribute will be added to the link.190 """204- trim_url = (205- lambda x, limit=trim_url_limit: limit is not None206- and (x[:limit] + (len(x) >= limit and "..." or ""))207- or x208- )209- words = _word_split_re.split(text_type(escape(text)))210- rel_attr = rel and ' rel="%s"' % text_type(escape(rel)) or ""211- target_attr = target and ' target="%s"' % escape(target) or ""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)))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:205 lead, middle, trail = match.groups()8 unmodified lines214 or middle.endswith(".net")215 or middle.endswith(".com")216 )217 ):229- middle = '<a href="http://%s"%s%s>%s</a>' % (230- middle,231- rel_attr,232- target_attr,233- 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://"):236- middle = '<a href="%s"%s%s>%s</a>' % (237- middle,238- rel_attr,239- target_attr,240- 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 ):248- 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 + trail251- 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.291- 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:299- return u"\n\n".join(result)300- 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 303-def unicode_urlencode(obj, charset="utf-8", for_qs=False):287+def url_quote(obj, charset="utf-8", for_qs=False):288 """Quote a string for use in a URL using the given charset.289 290 This function is misnamed, it is a wrapper around291 :func:`urllib.parse.quote`.2 unmodified lines294 string then encoded to bytes using the given charset.295 :param charset: Encode text to bytes using this charset.296 :param for_qs: Quote "/" and use "+" for spaces.297 """314- if not isinstance(obj, string_types):315- obj = text_type(obj)298+ if not isinstance(obj, bytes):299+ if not isinstance(obj, str):300+ obj = str(obj)301 317- if isinstance(obj, text_type):302 obj = obj.encode(charset)303 304 safe = b"" if for_qs else b"/"321- rv = url_quote(obj, safe)305+ rv = quote_from_bytes(obj, safe)306 323- if not isinstance(rv, text_type):324- rv = rv.decode("utf-8")325-307 if for_qs:308 rv = rv.replace("%20", "+")309 310 return rv311 312 313+def unicode_urlencode(obj, charset="utf-8", for_qs=False):314+ import warnings315+316+ warnings.warn(317+ "'unicode_urlencode' has been renamed to 'url_quote'. The old"318+ " name will be removed in version 3.1.",319+ DeprecationWarning,320+ stacklevel=2,321+ )322+ 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.50 unmodified lines458 result = [(key, self._mapping[key]) for key in list(self._queue)]459 result.reverse()460 return result461 468- def iteritems(self):469- """Iterate over all items."""470- warnings.warn(471- "'iteritems()' will be removed in version 3.0. Use"472- " 'iter(cache.items())' instead.",473- DeprecationWarning,474- stacklevel=2,475- )476- return iter(self.items())477-462 def values(self):463 """Return a list of all values."""464 return [x[1] for x in self.items()]465 482- def itervalue(self):483- """Iterate over all values."""484- warnings.warn(485- "'itervalue()' will be removed in version 3.0. Use"486- " 'iter(cache.values())' instead.",487- DeprecationWarning,488- stacklevel=2,489- )490- return iter(self.values())491-492- def itervalues(self):493- """Iterate over all values."""494- warnings.warn(495- "'itervalues()' will be removed in version 3.0. Use"496- " 'iter(cache.values())' instead.",497- DeprecationWarning,498- stacklevel=2,499- )500- return iter(self.values())501-466 def keys(self):467 """Return a list of all keys ordered by most recent usage."""468 return list(self)469 506- def iterkeys(self):507- """Iterate over all keys in the cache dict, ordered by508- the most recent usage.509- """510- warnings.warn(511- "'iterkeys()' will be removed in version 3.0. Use"512- " 'iter(cache.keys())' instead.",513- DeprecationWarning,514- stacklevel=2,515- )516- return iter(self)517-470 def __iter__(self):471 return reversed(tuple(self._queue))472 473 def __reversed__(self):4 unmodified lines478 479 __copy__ = copy480 481 530-abc.MutableMapping.register(LRUCache)531-532-482 def select_autoescape(483 enabled_extensions=("html", "htm", "xml"),484 disabled_extensions=(),485 default_for_string=True,32 unmodified lines518 For security reasons this function operates case insensitive.519 520 .. versionadded:: 2.9521 """573- enabled_patterns = tuple("." + x.lstrip(".").lower() for x in enabled_extensions)574- 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)611- .replace(u"<", u"\\u003c")612- .replace(u">", u"\\u003e")613- .replace(u"&", u"\\u0026")614- .replace(u"'", u"\\u0027")560+ .replace("<", "\\u003c")561+ .replace(">", "\\u003e")562+ .replace("&", "\\u0026")563+ .replace("'", "\\u0027")564 )565 return Markup(rv)566 567 619-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 673-class Joiner(object):622+class Joiner:623 """A joining helper for templates."""624 676- 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 = True683- return u""632+ return ""633 return self.sep634 635 687-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):707- 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:661 exec("async def _():\n async for _ in ():\n yield _")662 have_async_gen = True663 except SyntaxError:664 have_async_gen = False716-717-718-def soft_unicode(s):719- from markupsafe import soft_unicode720-721- warnings.warn(722- "'jinja2.utils.soft_unicode' will be removed in version 3.0."723- " Use 'markupsafe.soft_unicode' instead.",724- DeprecationWarning,725- stacklevel=2,726- )727- return soft_unicode(s)modified: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-30 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():35- # the |list is necessary for python334 tmpl = env.from_string("{{ foo.items()|list }}")35 assert tmpl.render(foo={"items": 42}) == "[('items', 42)]"36 tmpl = env.from_string('{{ foo|attr("items")()|list }}')37 assert tmpl.render(foo={"items": 42}) == "[('items', 42)]"124 unmodified lines162 163 164 @pytest.mark.api165 @pytest.mark.meta168-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)172- 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)181- 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)185- 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.streaming223-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)240- assert next(stream) == u"<ul><li>1"241- 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:255- 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.undefined266-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 283- 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)292- 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 == [299- "W:Template variable warning: missing is undefined",297+ "W:Template variable warning: 'missing' is undefined",298 "E:Template variable error: 'missing' is undefined",301- "W:Template variable warning: missing is undefined",302- "W:Template variable warning: int object has no attribute missing",303- "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)308- 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_undefined326- 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 expected336- 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 (338- env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() == u"foo"339- )340- assert (337 env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(foo=42)342- == u"bar"338+ == "bar"339 )340 assert (341 env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(342 foo={"bar": 42}343 )348- == 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)359- == 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))365- == 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.lowlevel405-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:413- 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+70 added-85 removed
1-# -*- coding: utf-8 -*-1 import re2+from io import BytesIO3 4 import pytest5 6 from jinja2 import contextfunction7 from jinja2 import DictLoader8 from jinja2 import Environment9 from jinja2 import nodes10-from jinja2._compat import BytesIO11-from jinja2._compat import itervalues12-from jinja2._compat import text_type10 from jinja2.exceptions import TemplateAssertionError11 from jinja2.ext import Extension12 from jinja2.lexer import count_newlines13 from jinja2.lexer import Token36 unmodified lines50 51 52 languages = {53 "de": {57- "missing": u"fehlend",58- "watch out": u"pass auf",59- "One user online": u"Ein Benutzer online",60- "%(user_count)s users online": u"%(user_count)s Benutzer online",61- "User: %(num)s": u"Benutzer: %(num)s",62- "User: %(count)s": u"Benutzer: %(count)s",63- "%(num)s apple": u"%(num)s Apfel",64- "%(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):100- 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):120- return "%s|%s|%s|%s|%s" % (121- sandboxed,122- ext_attr,123- imported_object,124- context.blocks,125- 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":142- for t in self.interpolate(token):143- 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.ext171-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 %}')54 unmodified lines223 def test_rebinding(self):224 original = Environment(extensions=[ExampleExtension])225 overlay = original.overlay()226 for env in original, overlay:234- for ext in itervalues(env.extensions):227+ for ext in env.extensions.values():228 assert ext.environment is env229 230 def test_preprocessor_extension(self):231 env = Environment(extensions=[PreprocessorExtension])24 unmodified lines256 t = env.from_string("Hello\n{% debug %}\nGoodbye")257 out = t.render()258 259 for value in ("context", "cycler", "filters", "abs", "tests", "!="):267- assert "'{}'".format(value) in out260+ assert f"'{value}'" in out261 262 263 @pytest.mark.ext271-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 65 unmodified lines334 def test_extract(self):335 from jinja2.ext import babel_extract336 337 source = BytesIO(338+ b"""339+ {{ gettext('Hello World') }}340+ {% trans %}Hello World{% endtrans %}341+ {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}342 """346- {{ gettext('Hello World') }}347- {% trans %}Hello World{% endtrans %}348- {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}349- """.encode(350- "ascii"351- )343+ )352- ) # make python 3 happy344 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], {})) == [354- (2, "gettext", u"Hello World", []),355- (3, "gettext", u"Hello World", []),356- (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_extract352 353 source = BytesIO(354+ b"""355+ {{ gettext(' Hello \n World') }}356+ {% trans trimmed %} Hello \n World{% endtrans %}357+ {% trans trimmed %}{{ users }} \n user358+ {%- pluralize %}{{ users }} \n users{% endtrans %}359 """364- {{ gettext(' Hello \n World') }}365- {% trans trimmed %} Hello \n World{% endtrans %}366- {% trans trimmed %}{{ users }} \n user367- {%- pluralize %}{{ users }} \n users{% endtrans %}368- """.encode(369- "ascii"370- )360+ )371- ) # make python 3 happy361 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], {})) == [373- (2, "gettext", u" Hello \n World", []),374- (4, "gettext", u"Hello World", []),375- (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_extract369 370 source = BytesIO(371+ b"""372+ {{ gettext(' Hello \n World') }}373+ {% trans %} Hello \n World{% endtrans %}374+ {% trans %}{{ users }} \n user375+ {%- pluralize %}{{ users }} \n users{% endtrans %}376 """383- {{ gettext(' Hello \n World') }}384- {% trans %} Hello \n World{% endtrans %}385- {% trans %}{{ users }} \n user386- {%- pluralize %}{{ users }} \n users{% endtrans %}387- """.encode(388- "ascii"389- )377+ )390- ) # make python 3 happy378 opts = {"trimmed": "true"}379 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], opts)) == [393- (2, "gettext", u" Hello \n World", []),394- (4, "gettext", u"Hello World", []),395- (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_extract387 388 source = BytesIO(389+ b"""390+ {# trans first #}391+ {{ gettext('Hello World') }}392+ {% trans %}Hello World{% endtrans %}{# trans second #}393+ {#: third #}394+ {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}395 """403- {# trans first #}404- {{ gettext('Hello World') }}405- {% trans %}Hello World{% endtrans %}{# trans second #}406- {#: third #}407- {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}408- """.encode(409- "utf-8"410- )396+ )411- ) # make python 3 happy397 assert list(398 babel_extract(source, ("gettext", "ngettext", "_"), ["trans", ":"], {})399 ) == [415- (3, "gettext", u"Hello World", ["first"]),416- (4, "gettext", u"Hello World", ["second"]),417- (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.ext422-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):426- 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.ext456-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"485- 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(490- 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")511- 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 (526- 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.ext548-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() == [561- u"<HelloWorld>",562- u"<HelloWorld>",563- 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() == [577- u"<HelloWorld>",578- u"<HelloWorld>",579- u"<HelloWorld>",562+ "<HelloWorld>",563+ "<HelloWorld>",564+ "<HelloWorld>",565 ]566 567 def test_nonvolatile(self):568 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)34 unmodified lines603 {{ '<testing>' }}604 """605 tmpl = env.from_string(tmplsource)606 assert tmpl.render(val=True).split()[0] == "Markup"622- assert tmpl.render(val=False).split()[0] == text_type.__name__607+ assert tmpl.render(val=False).split()[0] == "str"608 609 # looking at the source we should see <testing> there in raw610 # (and then escaped as well)611 env = Environment(extensions=["jinja2.ext.autoescape"])5 unmodified lines617 assert "<testing>\\n" in pysource618 619 def test_overlay_scopes(self):620 class MagicScopeExtension(Extension):636- 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-30 removed
1-import sys2-1 import pytest2 5-from jinja2 import contextfilter6-from jinja2 import Environment3 from jinja2 import Template8-from jinja2._compat import text_type4 5 11-@pytest.mark.skipif(sys.version_info < (3, 5), reason="Requires 3.5 or later")6+# Python < 3.77 def test_generator_stop():13- class X(object):8+ class X:9 def __getattr__(self, name):10 raise StopIteration()11 12 t = Template("a{{ bad.bar() }}b")13 with pytest.raises(RuntimeError):14 t.render(bad=X())20-21-22-@pytest.mark.skipif(sys.version_info[0] > 2, reason="Feature only supported on 2.x")23-def test_ascii_str():24- @contextfilter25- def assert_func(context, value):26- assert type(value) is context["expected_type"]27-28- env = Environment()29- env.filters["assert"] = assert_func30-31- env.policies["compiler.ascii_str"] = False32- t = env.from_string('{{ "foo"|assert }}')33- t.render(expected_type=text_type)34-35- env.policies["compiler.ascii_str"] = True36- t = env.from_string('{{ "foo"|assert }}')37- t.render(expected_type=str)38-39- for val in True, False:40- env.policies["compiler.ascii_str"] = val41- t = env.from_string(u'{{ "\N{SNOWMAN}"|assert }}')42- t.render(expected_type=text_type)modified:tests/test_filters.py+22 added-28 removed
1-# -*- coding: utf-8 -*-1 import random2 from collections import namedtuple3 4 import pytest5 6 from jinja2 import Environment7 from jinja2 import Markup9-from jinja2._compat import implements_to_string10-from jinja2._compat import text_type8 9 13-@implements_to_string14-class Magic(object):10+class Magic:11 def __init__(self, value):12 self.value = value13 14 def __str__(self):19- return text_type(self.value)15+ return str(self.value)16 17 22-@implements_to_string23-class Magic2(object):18+class Magic2:19 def __init__(self, value1, value2):20 self.value1 = value121 self.value2 = value222 23 def __str__(self):29- return u"(%s,%s)" % (text_type(self.value1), text_type(self.value2))24+ return f"({self.value1},{self.value2})"25 26 27 @pytest.mark.filter33-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):63- 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(146- ("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):149- t = env.from_string("{{ '%s'|float }}" % value)150- 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):157- 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):200- t = env.from_string("{{ '%s'|int }}" % value)201- 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):208- t = env.from_string("{{ '%s'|int(base=%d) }}" % (value, base))209- 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):216- class IntIsh(object):211+ class IntIsh:212 def __int__(self):213 return 42214 215 t = env.from_string("{{ value|int }}")59 unmodified lines275 276 def test_string(self, env):277 x = [1, 2, 3, 4, 5]278 tmpl = env.from_string("""{{ obj|string }}""")284- assert tmpl.render(obj=x) == text_type(x)279+ assert tmpl.render(obj=x) == str(x)280 281 def test_title(self, env):282 tmpl = env.from_string("""{{ "foo bar"|title }}""")283 assert tmpl.render() == "Foo Bar"32 unmodified lines316 '{{ data|truncate(15, false, ">>>") }}|'317 "{{ smalldata|truncate(15) }}"318 )319 out = tmpl.render(data="foobar baz bar" * 1000, smalldata="foobar baz bar")325- msg = "Current output: %s" % out326- 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()333- 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()338- 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 }}")587- 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"),600- (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"),603- ({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+49 added-74 removed
1-# -*- coding: utf-8 -*-1 import pytest2 3 from jinja2 import Environment4 from jinja2 import nodes5 from jinja2 import Template6 from jinja2 import TemplateSyntaxError7 from jinja2 import UndefinedError9-from jinja2._compat import iteritems10-from jinja2._compat import PY211-from jinja2._compat import text_type8 from jinja2.lexer import Token9 from jinja2.lexer import TOKEN_BLOCK_BEGIN10 from jinja2.lexer import TOKEN_BLOCK_END11 from jinja2.lexer import TOKEN_EOF12 from jinja2.lexer import TokenStream13 14 19-# how does a string look like in jinja syntax?20-if PY2:21-22- def jinja_string_repr(string):23- return repr(string)[1:]24-25-26-else:27- jinja_string_repr = repr28-29-15 @pytest.mark.lexnparse16 @pytest.mark.tokenstream32-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.lexer62-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):113- for char in u"\0", u"\u2668", u"\xe4", u"\t", u"\r", u"\n":114- tmpl = env.from_string("{{ %s }}" % jinja_string_repr(char))98+ for char in "\0", "\u2668", "\xe4", "\t", "\r", "\n":99+ tmpl = env.from_string(f"{{{{ {char!r} }}}}")100 assert tmpl.render() == char116- 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 121- tmpl = env.from_string(u"""{{ 'foo'|pprint }}|{{ 'bär'|pprint }}""")122- 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 127- for test, expect in iteritems(operators):112+ for test, expect in operators.items():113 if test in "([{}])":114 continue130- 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):17 unmodified lines137 result = tmpl.render()138 assert result == expect, (keep, template, result, expect)139 140 @pytest.mark.parametrize(156- "name,valid2,valid3",157- (158- (u"foo", True, True),159- (u"föö", False, True),160- (u"き", False, True),161- (u"_", True, True),162- (u"1a", False, False), # invalid ascii start163- (u"a-", False, False), # invalid ascii continue164- (u"🐍", False, False), # invalid unicode start165- (u"a🐍", False, False), # invalid unicode continue141+ ("name", "valid"),142+ [143+ ("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 \w167- (u"\u1885", False, True),168- (u"\u1886", False, True),169- (u"\u2118", False, True),170- (u"\u212e", False, True),152+ ("\u1885", True),153+ ("\u1886", True),154+ ("\u2118", True),155+ ("\u212e", True),156 # continue character not matched by \w172- (u"\xb7", False, False),173- (u"a\xb7", False, True),174- ),157+ ("\xb7", False),158+ ("a\xb7", True),159+ ],160 )176- def test_name(self, env, name, valid2, valid3):177- t = u"{{ " + name + u" }}"161+ def test_name(self, env, name, valid):162+ t = "{{ " + name + " }}"163 179- if (valid2 and PY2) or (valid3 and not PY2):164+ if valid:165 # valid for version being tested, shouldn't raise166 env.from_string(t)167 else:168 pytest.raises(TemplateSyntaxError, env.from_string, t)169 170 171 @pytest.mark.lexnparse172 @pytest.mark.parser188-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.syntax323-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):374- 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):402- 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):423- 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:477- pytest.raises(478- TemplateSyntaxError, env.from_string, "{{ foo(%s) }}" % sig479- )462+ with pytest.raises(TemplateSyntaxError):463+ env.from_string(f"{{{{ foo({sig}) }}}}")464 else:481- 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(509- "{{ %s }}|{{ %s }}|{{ %s }}"510- % (str(const), str(const).lower(), str(const).upper())494+ f"{{{{ {const} }}}}|{{{{ {const.lower()} }}}}|{{{{ {const.upper()} }}}}"495 )512- 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 }}"10 unmodified lines511 assert tmpl.render(bar=bar) == "False"512 513 def test_operator_precedence(self, env):514 tmpl = env.from_string("""{{ 2 * 3 + 4 % 2 + 1 - 2 }}""")531- assert tmpl.render() == text_type(2 * 3 + 4 % 2 + 1 - 2)515+ assert tmpl.render() == "5"516 517 def test_implicit_subscribed_tuple(self, env):534- class Foo(object):518+ class Foo:519 def __getitem__(self, x):520 return x521 522 t = env.from_string("{{ foo[1, 2] }}")539- 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.lstripblocks580-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 )700- 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 )722- 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 )748- assert tmpl.render(seq=range(5)) == "".join(749- " %s\n" % x for x in range(5)750- )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 )763- assert tmpl.render(seq=range(5)) == "".join(764- " %s\n" % x for x in range(5)765- )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 )771- # env.from_string('')772- # for n,r in env.lexer.rules.iteritems():773- # print n774- # print env.lexer.rules['root'][0][0].pattern775- # 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 )784- 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+11 added-34 removed
1-# -*- coding: utf-8 -*-1 import os2+import platform3 import shutil4 import sys5 import tempfile6 import time3 unmodified lines10 11 from jinja2 import Environment12 from jinja2 import loaders13 from jinja2 import PackageLoader14-from jinja2._compat import PY215-from jinja2._compat import PYPY14 from jinja2.exceptions import TemplateNotFound15 from jinja2.loaders import split_template_path16 17 18 @pytest.mark.loaders21-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):71- 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.filesystemloader122-class TestFileSystemLoader(object):120+class TestFileSystemLoader:121 searchpath = os.path.join(122 os.path.dirname(os.path.abspath(__file__)), "res", "templates"123 )124 10 unmodified lines135 136 env = Environment(loader=filesystem_loader)137 self._test_common(env)138 141- @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")139 def test_searchpath_as_pathlib(self):140 import pathlib141 142 searchpath = pathlib.Path(self.searchpath)146-143 filesystem_loader = loaders.FileSystemLoader(searchpath)148-144 env = Environment(loader=filesystem_loader)145 self._test_common(env)146 152- @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")147 def test_searchpath_as_list_including_pathlib(self):148 import pathlib149 150 searchpath = pathlib.Path(self.searchpath)157-151 filesystem_loader = loaders.FileSystemLoader(["/tmp/templates", searchpath])159-152 env = Environment(loader=filesystem_loader)153 self._test_common(env)154 155 def test_caches_template_based_on_mtime(self):10 unmodified lines166 167 @pytest.mark.parametrize(168 ("encoding", "expect"),169 [178- ("utf-8", u"文字化け"),179- ("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.moduleloader191-class TestModuleLoader(object):183+class TestModuleLoader:184 archive = None185 194- def compile_down(self, prefix_loader, zip="deflated", py_compile=False):186+ def compile_down(self, prefix_loader, zip="deflated"):187 log = []188 self.reg_env = Environment(loader=prefix_loader)189 if zip is not None:190 fd, self.archive = tempfile.mkstemp(suffix=".zip")191 os.close(fd)192 else:193 self.archive = tempfile.mkdtemp()202- self.reg_env.compile_templates(203- self.archive, zip=zip, log_function=log.append, py_compile=py_compile204- )194+ self.reg_env.compile_templates(self.archive, zip=zip, log_function=log.append)195 self.mod_env = Environment(loader=loaders.ModuleLoader(self.archive))196 return "".join(log)197 198 def teardown(self):57 unmodified lines256 pass257 258 assert name not in sys.modules259 270- # This test only makes sense on non-pypy python 2271- @pytest.mark.skipif(272- not (PY2 and not PYPY), reason="This test only makes sense on non-pypy python 2"273- )274- def test_byte_compilation(self, prefix_loader):275- log = self.compile_down(prefix_loader, py_compile=True)276- assert 'Byte-compiled "a/test.html"' in log277- self.mod_env.get_template("a/test.html")278- mod = self.mod_env.loader.module.tmpl_3c4ddf650c1a73df961a6d3d2ce2752f1b8fd490279- assert mod.__file__.endswith(".pyc")280-260 def test_choice_loader(self, prefix_loader):261 self.compile_down(prefix_loader)262 self.mod_env.loader = loaders.ChoiceLoader(263 [self.mod_env.loader, loaders.DictLoader({"DICT_SOURCE": "DICT_TEMPLATE"})]15 unmodified lines279 assert tmpl1.render() == "BAR"280 tmpl2 = self.mod_env.get_template("DICT/test.html")281 assert tmpl2.render() == "DICT_TEMPLATE"282 304- @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")283 def test_path_as_pathlib(self, prefix_loader):284 self.compile_down(prefix_loader)285 286 mod_path = self.mod_env.loader.module.__path__[0]4 unmodified lines291 self.mod_env = Environment(loader=mod_loader)292 293 self._test_common()294 317- @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")295 def test_supports_pathlib_in_list_of_paths(self, prefix_loader):296 self.compile_down(prefix_loader)297 298 mod_path = self.mod_env.loader.module.__path__[0]46 unmodified lines345 assert up_to_date is None346 347 348 @pytest.mark.xfail(372- PYPY,373- reason="PyPy's zipimporter doesn't have a _files attribute.",349+ platform.python_implementation() == "PyPy",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_nativetypes.py+2 added-3 removed
1 import pytest2 3-from jinja2._compat import text_type3 from jinja2.exceptions import UndefinedError4 from jinja2.nativetypes import NativeEnvironment5 from jinja2.nativetypes import NativeTemplate6 from jinja2.runtime import Undefined44 unmodified lines51 52 def test_loops(env):53 t = env.from_string("{% for x in value %}{{ x }}{% endfor %}")54 result = t.render(value=["a", "b", "c", "d"])56- assert isinstance(result, text_type)55+ assert isinstance(result, str)56 assert result == "abcd"57 58 59 def test_loops_with_ints(env):49 unmodified lines109 110 def test_string_literal_var(env):111 t = env.from_string("[{{ 'all' }}]")112 result = t.render()114- assert isinstance(result, text_type)113+ assert isinstance(result, str)114 assert result == "[all]"115 116 117 def test_string_top_level(env):21 unmodified linesmodified:tests/test_regression.py+13 added-24 removed
1-# -*- coding: utf-8 -*-2-import sys3-1 import pytest2 3 from jinja2 import DictLoader4 from jinja2 import Environment1 unmodified line6 from jinja2 import Template7 from jinja2 import TemplateAssertionError8 from jinja2 import TemplateNotFound9 from jinja2 import TemplateSyntaxError13-from jinja2._compat import text_type10 11 12 @pytest.mark.regression17-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.regression89-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 (39 unmodified lines129 130 """131 )132 137- assert tmpl.render().split() == [text_type(x) for x in range(1, 11)] * 5133+ assert tmpl.render().split() == [str(x) for x in range(1, 11)] * 5134 135 def test_weird_inline_comment(self, env):136 env = Environment(line_statement_prefix="%")137 pytest.raises(52 unmodified lines190 {{ x }}191 """192 )193 rv = t.render(foo=[1]).strip()198- 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 ] == [232- u"<ul><li><p>apo</p><dl>",233- u"<dl>Realname</dl>",234- u"<dd>something else</dd>",235- u"<dl>Description</dl>",236- u"<dd>test</dd>",237- u"</dl>",238- 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 300- class CallableClass(object):296+ class CallableClass:297 @contextfunction298 def __call__(self, ctx):299 return ctx.resolve("hello")300 2 unmodified lines303 expected = "TEST"304 305 assert output == expected306 311- @pytest.mark.skipif(sys.version_info[0] > 2, reason="This only works on 2.x")312- def test_old_style_attribute(self, env):313- class Foo:314- x = 42315-316- assert env.getitem(Foo(), "x") == 42317-307 def test_block_set_with_extends(self):308 env = Environment(309 loader=DictLoader({"main": "{% block body %}[{{ x }}]{% endblock %}"})310 )282 unmodified lines593 class MyContext(Context):594 def resolve(self, name):595 if name == "foo":596 return 42608- 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+10 added-54 removed
1-# -*- coding: utf-8 -*-1 import pytest2 3 from jinja2 import Environment4 from jinja2 import escape6-from jinja2 import Markup7-from jinja2._compat import text_type5 from jinja2.exceptions import SecurityError6 from jinja2.exceptions import TemplateRuntimeError7 from jinja2.exceptions import TemplateSyntaxError8 from jinja2.nodes import EvalContext1 unmodified line10 from jinja2.sandbox import SandboxedEnvironment11 from jinja2.sandbox import unsafe12 13 17-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 29-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.sandbox41-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()30 unmodified lines73 env.from_string,74 "{% for foo, bar.baz in seq %}...{% endfor %}",75 )76 80- def test_markup_operations(self, env):81- # adding two strings should escape the unsafe one82- unsafe = '<script type="application/x-some-script">alert("foo");</script>'83- safe = Markup("<em>username</em>")84- assert unsafe + safe == text_type(escape(unsafe)) + text_type(safe)85-86- # string interpolations are safe to use too87- assert Markup("<em>%s</em>") % "<bad user>" == "<em><bad user></em>"88- assert (89- Markup("<em>%(username)s</em>") % {"username": "<bad user>"}90- == "<em><bad user></em>"91- )92-93- # an escaped object is markup too94- assert type(Markup("foo") + "bar") is Markup95-96- # and it implements __html__ by returning itself97- x = Markup("foo")98- assert x.__html__() is x99-100- # it also knows how to treat __html__ objects101- class Foo(object):102- def __html__(self):103- return "<em>awesome</em>"104-105- def __unicode__(self):106- return "awesome"107-108- assert Markup(Foo()) == "<em>awesome</em>"109- assert (110- Markup("<strong>%s</strong>") % Foo() == "<strong><em>awesome</em></strong>"111- )112-113- # escaping and unescaping114- assert escape("\"<>&'") == ""<>&'"115- assert Markup("<em>Foo & Bar</em>").striptags() == "Foo & Bar"116- assert Markup("<test>").unescape() == "<test>"117-77 def test_template_data(self, env):78 env = Environment(autoescape=True)79 t = env.from_string(80 "{% macro say_hello(name) %}"1 unmodified line82 '{{ say_hello("<blink>foo</blink>") }}'83 )84 escaped_out = "<p>Hello <blink>foo</blink>!</p>"85 assert t.render() == escaped_out127- assert text_type(t.module) == escaped_out86+ assert str(t.module) == escaped_out87 assert escape(t.module) == escaped_out88 assert t.module.say_hello("<blink>foo</blink>") == escaped_out89 assert (90 escape(t.module.say_hello(EvalContext(env), "<blink>foo</blink>"))12 unmodified lines103 104 for expr, ctx, rv in ("1 + 2", {}, "3"), ("a + 2", {"a": 2}, "4"):105 env = SandboxedEnvironment()106 env.binop_table["+"] = disable_op148- t = env.from_string("{{ %s }}" % expr)107+ t = env.from_string(f"{{{{ {expr} }}}}")108 assert t.render(ctx) == rv109 env.intercepted_binops = frozenset(["+"])151- 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_op162- t = env.from_string("{{ %s }}" % expr)121+ t = env.from_string(f"{{{{ {expr} }}}}")122 assert t.render(ctx) == rv123 env.intercepted_unops = frozenset(["-"])165- 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.sandbox171-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.sandbox194-@pytest.mark.skipif(195- not hasattr(str, "format_map"), reason="requires str.format_map method"196-)197-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+14 added-24 removed
1-# -*- coding: utf-8 -*-1 import pickle2 import random3 from collections import deque4 from copy import copy as shallow_copy5 6 import pytest7 from markupsafe import Markup8 10-from jinja2._compat import range_type11-from jinja2._compat import string_types9 from jinja2.utils import consume10 from jinja2.utils import generate_lorem_ipsum11 from jinja2.utils import LRUCache12 from jinja2.utils import missing3 unmodified lines16 17 18 @pytest.mark.utils19 @pytest.mark.lrucache23-class TestLRUCache(object):20+class TestLRUCache:21 def test_simple(self):22 d = LRUCache(3)23 d["a"] = 124 d["b"] = 22 unmodified lines27 d["d"] = 428 assert len(d) == 329 assert "a" in d and "c" in d and "d" in d and "b" not in d30 34- def test_itervalue_deprecated(self):35- cache = LRUCache(3)36- cache["a"] = 137- cache["b"] = 238- with pytest.deprecated_call():39- cache.itervalue()40-31 def test_itervalues(self):32 cache = LRUCache(3)33 cache["b"] = 134 cache["a"] = 243 unmodified lines78 d["a"] = 179 d["b"] = 280 d["c"] = 381 # Sort the strings - mapping is unordered92- 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.helpers125-class TestHelpers(object):115+class TestHelpers:116 def test_object_type_repr(self):127- 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.escapeUrlizeTarget155-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.loremIpsum168-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 163 def test_lorem_ipsum_html(self):164 """Test that output of lorem_ipsum is a string_type when not html."""175- assert isinstance(generate_lorem_ipsum(html=False), string_types)165+ 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."""179- assert generate_lorem_ipsum(n=0, html=False) == u""180- for n in range_type(1, 50):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):174 """Test that at least min words are in the output of each line"""185- for _ in range_type(5):175+ for _ in range(5):176 m = random.randrange(20, 99)187- for _ in range_type(10):177+ for _ in range(10):178 assert generate_lorem_ipsum(n=1, min=m, html=False).count(" ") >= m - 1179 180 def test_lorem_ipsum_max(self):181 """Test that at least max words are in the output of each line"""192- for _ in range_type(5):182+ for _ in range(5):183 m = random.randrange(21, 100)194- for _ in range_type(10):184+ for _ in range(10):185 assert generate_lorem_ipsum(n=1, max=m, html=False).count(" ") < m - 1186 187 188 def test_missing():189 """Test the repr of missing."""200- 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 linesmodified:.pre-commit-config.yaml+5 added
1 repos:2+ - repo: https://github.com/asottile/pyupgrade3+ rev: v1.26.24+ hooks:5+ - id: pyupgrade6+ args: ["--py36-plus"]7 - repo: https://github.com/asottile/reorder_python_imports8 rev: v1.9.09 hooks:10 - id: reorder-python-imports16 unmodified linesmodified:CHANGES.rst+2 added
6 unmodified lines7 8 - Drop support for Python 2.7 and 3.5.9 - Bump MarkupSafe dependency to >=1.1.10 - Bump Babel optional dependency to >=2.1.11+- Remove code that was marked deprecated.12+-13 14 15 2.11.216 ------748 unmodified linesmodified:setup.cfg+1 added-4 removed
1 [metadata]2 license_file = LICENSE.rst3+long_description = file:README.rst4 long_description_content_type = text/x-rst5 5-[bdist_wheel]6-universal = true7-6 [tool:pytest]7 testpaths = tests8 filterwarnings =9 error12- ignore:the sets module:DeprecationWarning:jinja2.sandbox10 11 [coverage:run]12 branch = True13 source =29 unmodified linesmodified:setup.py+1 added-6 removed
1-import io1 import re2 3 from setuptools import find_packages4 from setuptools import setup5 7-with io.open("README.rst", "rt", encoding="utf8") as f:8- readme = f.read()9-10-with io.open("src/jinja2/__init__.py", "rt", encoding="utf8") as f:6+with open("src/jinja2/__init__.py", "rt", encoding="utf8") as f:7 version = re.search(r'__version__ = "(.*?)"', f.read(), re.M).group(1)8 9 setup(10 name="Jinja2",7 unmodified lines18 license="BSD-3-Clause",19 maintainer="Pallets",20 maintainer_email="contact@palletsprojects.com",21 description="A very fast and expressive template engine.",26- long_description=readme,22 classifiers=[23 "Development Status :: 5 - Production/Stable",24 "Environment :: Web Environment",25 "Intended Audience :: Developers",15 unmodified linesmodified:tox.ini+1 added-1 removed
1 [tox]2 envlist =3- py{38,37,36,35,27,py3,py}3+ py{38,37,36,py3}4 style5 docs6 skip_missing_interpreters = true7 13 unmodified lines