Skip to content
Myr

utils.py

This file

Path

src/jinja2/utils.py

755 lines · 23.4 KiB · Python

Last changed by

Merge pull request #1544 from pallets/remove-deprecated-codeDavid Lordbefore adoptionb285d0c

History of this file

Take it

The walk stopped after 200 commits: lines older than d312609 point at it.

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 1why, one step back
1import enum

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 2–4why, one step back
2import json
3import os4import re

Merge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c

line 5why, one step back
5import typing as t

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 6why, one step back
6from collections import abc

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 7–10why, one step back
7from collections import deque
8from random import choice9from random import randrange10from threading import Lock

Merge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c

line 11why, one step back
11from types import CodeType

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 12why, one step back
12from urllib.parse import quote_from_bytes

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 13why, one step back
13

Merge pull request #1391 from pallets/markupsafe-importsDavid Lordbefore adoptiona9b06f4

line 14why, one step back
14import markupsafe

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 15why, one step back
15

Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0

lines 16–18why, one step back
16if t.TYPE_CHECKING:
17 import typing_extensions as te18

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 19why, one step back
19F = t.TypeVar("F", bound=t.Callable[..., t.Any])

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 20why, one step back
20

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 21why, one step back
21# special singleton representing missing values for the runtime

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 22why, one step back
22missing: t.Any = type("MissingType", (), {"__repr__": lambda x: "missing"})()

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 23why, one step back
23

Merge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c

line 24why, one step back
24internal_code: t.MutableSet[CodeType] = set()

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 25why, one step back
25

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 26why, one step back
26concat = "".join

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 27–28why, one step back
27
28

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 29why, one step back
29def pass_context(f: F) -> F:

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

lines 30–31why, one step back
30 """Pass the :class:`~jinja2.runtime.Context` as the first argument
31 to the decorated function when called while rendering a template.

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 32why, one step back
32

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

lines 33–40why, one step back
33 Can be used on functions, filters, and tests.
3435 If only ``Context.eval_context`` is needed, use36 :func:`pass_eval_context`. If only ``Context.environment`` is37 needed, use :func:`pass_environment`.3839 .. versionadded:: 3.0.040 Replaces ``contextfunction`` and ``contextfilter``.

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 41why, one step back
41 """

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 42why, one step back
42 f.jinja_pass_arg = _PassArg.context # type: ignore

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 43–45why, one step back
43 return f
4445

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 46why, one step back
46def pass_eval_context(f: F) -> F:

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

lines 47–62why, one step back
47 """Pass the :class:`~jinja2.nodes.EvalContext` as the first argument
48 to the decorated function when called while rendering a template.49 See :ref:`eval-context`.5051 Can be used on functions, filters, and tests.5253 If only ``EvalContext.environment`` is needed, use54 :func:`pass_environment`.5556 .. versionadded:: 3.0.057 Replaces ``evalcontextfunction`` and ``evalcontextfilter``.58 """59 f.jinja_pass_arg = _PassArg.eval_context # type: ignore60 return f6162

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 63why, one step back
63def pass_environment(f: F) -> F:

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

lines 64–81why, one step back
64 """Pass the :class:`~jinja2.Environment` as the first argument to
65 the decorated function when called while rendering a template.6667 Can be used on functions, filters, and tests.6869 .. versionadded:: 3.0.070 Replaces ``environmentfunction`` and ``environmentfilter``.71 """72 f.jinja_pass_arg = _PassArg.environment # type: ignore73 return f747576class _PassArg(enum.Enum):77 context = enum.auto()78 eval_context = enum.auto()79 environment = enum.auto()8081 @classmethod

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 82why, one step back
82 def from_obj(cls, obj: F) -> t.Optional["_PassArg"]:

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 83why, one step back
83 if hasattr(obj, "jinja_pass_arg"):

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 84why, one step back
84 return obj.jinja_pass_arg # type: ignore

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 85why, one step back
85

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 86why, one step back
86 return None

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 87why, one step back
87

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 88–89why, one step back
88
89def internalcode(f: F) -> F:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 90–94why, one step back
90 """Marks the function as internally used"""
91 internal_code.add(f.__code__)92 return f9394

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 95why, one step back
95def is_undefined(obj: t.Any) -> bool:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 96–111why, one step back
96 """Check if the object passed is undefined. This does nothing more than
97 performing an instance check against :class:`Undefined` but looks nicer.98 This can be used for custom filters or tests that want to react to99 undefined variables. For example a custom default filter can look like100 this::101102 def default(var, default=''):103 if is_undefined(var):104 return default105 return var106 """107 from .runtime import Undefined108109 return isinstance(obj, Undefined)110111

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 112why, one step back
112def consume(iterable: t.Iterable[t.Any]) -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 113–117why, one step back
113 """Consumes an iterable without doing anything with it."""
114 for _ in iterable:115 pass116117

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 118why, one step back
118def clear_caches() -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 119–123why, one step back
119 """Jinja keeps internal caches for environments and lexers. These are
120 used so that Jinja doesn't have to recreate environments and lexers all121 the time. Normally you don't have to care about that but if you are122 measuring memory consumption you may want to clean the caches.123 """

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 124why, one step back
124 from .environment import get_spontaneous_environment

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 125–126why, one step back
125 from .lexer import _lexer_cache
126

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 127why, one step back
127 get_spontaneous_environment.cache_clear()

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 128–130why, one step back
128 _lexer_cache.clear()
129130

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 131why, one step back
131def import_string(import_name: str, silent: bool = False) -> t.Any:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 132–154why, one step back
132 """Imports an object based on a string. This is useful if you want to
133 use import paths as endpoints or something similar. An import path can134 be specified either in dotted notation (``xml.sax.saxutils.escape``)135 or with a colon as object delimiter (``xml.sax.saxutils:escape``).136137 If the `silent` is True the return value will be `None` if the import138 fails.139140 :return: imported object141 """142 try:143 if ":" in import_name:144 module, obj = import_name.split(":", 1)145 elif "." in import_name:146 module, _, obj = import_name.rpartition(".")147 else:148 return __import__(import_name)149 return getattr(__import__(module, None, None, [obj]), obj)150 except (ImportError, AttributeError):151 if not silent:152 raise153154

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 155why, one step back
155def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO]:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 156–164why, one step back
156 """Returns a file descriptor for the filename if that file exists,
157 otherwise ``None``.158 """159 if not os.path.isfile(filename):160 return None161162 return open(filename, mode)163164

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 165why, one step back
165def object_type_repr(obj: t.Any) -> str:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 166–173why, one step back
166 """Returns the name of the object's type. For some recognized
167 singletons the name of the object is returned instead. (For168 example for `None` and `Ellipsis`).169 """170 if obj is None:171 return "None"172 elif obj is Ellipsis:173 return "Ellipsis"

Merge branch '2.11.x'David Lordbefore adoptionc074fd5

lines 174–180why, one step back
174
175 cls = type(obj)176177 if cls.__module__ == "builtins":178 return f"{cls.__name__} object"179180 return f"{cls.__module__}.{cls.__name__} object"

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 181–182why, one step back
181
182

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 183why, one step back
183def pformat(obj: t.Any) -> str:

Merge pull request #1310 from pallets/pre-commit-ci-update-configDavid Lordbefore adoption1cad38c

line 184why, one step back
184 """Format an object using :func:`pprint.pformat`."""

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 185why, one step back
185 from pprint import pformat # type: ignore

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 186why, one step back
186

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 187why, one step back
187 return pformat(obj)

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 188–189why, one step back
188
189

Merge pull request #1195 from bebleo/add_mailto_link_supportDavid Lordbefore adoptionf1b1caf

lines 190–218why, one step back
190_http_re = re.compile(
191 r"""192 ^193 (194 (https?://|www\.) # scheme or www195 (([\w%-]+\.)+)? # subdomain196 (197 [a-z]{2,63} # basic tld198 |199 xn--[\w%]{2,59} # idna tld200 )201 |202 ([\w%-]{2,63}\.)+ # basic domain203 (com|net|int|edu|gov|org|info|mil) # basic tld204 |205 (https?://) # scheme206 (207 (([\d]{1,3})(\.[\d]{1,3}){3}) # IPv4208 |209 (\[([\da-f]{0,4}:){2}([\da-f]{0,4}:?){1,6}]) # IPv6210 )211 )212 (?::[\d]{1,5})? # port213 (?:[/?#]\S*)? # path, query, and fragment214 $215 """,216 re.IGNORECASE | re.VERBOSE,217)218_email_re = re.compile(r"^\S+@\w[\w.-]*\.\w+$")

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 219–220why, one step back
219
220

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 221–227why, one step back
221def urlize(
222 text: str,223 trim_url_limit: t.Optional[int] = None,224 rel: t.Optional[str] = None,225 target: t.Optional[str] = None,226 extra_schemes: t.Optional[t.Iterable[str]] = None,227) -> str:

Merge pull request #1195 from bebleo/add_mailto_link_supportDavid Lordbefore adoptionf1b1caf

line 228why, one step back
228 """Convert URLs in text into clickable links.

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 229why, one step back
229

Merge pull request #1195 from bebleo/add_mailto_link_supportDavid Lordbefore adoptionf1b1caf

lines 230–257why, one step back
230 This may not recognize links in some situations. Usually, a more
231 comprehensive formatter, such as a Markdown library, is a better232 choice.233234 Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email235 addresses. Links with trailing punctuation (periods, commas, closing236 parentheses) and leading punctuation (opening parentheses) are237 recognized excluding the punctuation. Email addresses that include238 header fields are not recognized (for example,239 ``mailto:address@example.com?cc=copy@example.com``).240241 :param text: Original text containing URLs to link.242 :param trim_url_limit: Shorten displayed URL values to this length.243 :param target: Add the ``target`` attribute to links.244 :param rel: Add the ``rel`` attribute to links.245 :param extra_schemes: Recognize URLs that start with these schemes246 in addition to the default behavior.247248 .. versionchanged:: 3.0249 The ``extra_schemes`` parameter was added.250251 .. versionchanged:: 3.0252 Generate ``https://`` links for URLs without a scheme.253254 .. versionchanged:: 3.0255 The parsing rules were updated. Recognize email addresses with256 or without the ``mailto:`` scheme. Validate IP addresses. Ignore257 parentheses and brackets in more cases.

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 258why, one step back
258 """

Merge pull request #1195 from bebleo/add_mailto_link_supportDavid Lordbefore adoptionf1b1caf

line 259why, one step back
259 if trim_url_limit is not None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 260why, one step back
260

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 261–262why, one step back
261 def trim_url(x: str) -> str:
262 if len(x) > trim_url_limit: # type: ignore

Merge pull request #1195 from bebleo/add_mailto_link_supportDavid Lordbefore adoptionf1b1caf

line 263why, one step back
263 return f"{x[:trim_url_limit]}..."

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 264why, one step back
264

Merge pull request #1195 from bebleo/add_mailto_link_supportDavid Lordbefore adoptionf1b1caf

line 265why, one step back
265 return x

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 266why, one step back
266

Merge pull request #1195 from bebleo/add_mailto_link_supportDavid Lordbefore adoptionf1b1caf

lines 267–268why, one step back
267 else:
268

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 269why, one step back
269 def trim_url(x: str) -> str:

Merge pull request #1195 from bebleo/add_mailto_link_supportDavid Lordbefore adoptionf1b1caf

lines 270–271why, one step back
270 return x
271

Merge pull request #1391 from pallets/markupsafe-importsDavid Lordbefore adoptiona9b06f4

lines 272–274why, one step back
272 words = re.split(r"(\s+)", str(markupsafe.escape(text)))
273 rel_attr = f' rel="{markupsafe.escape(rel)}"' if rel else ""274 target_attr = f' target="{markupsafe.escape(target)}"' if target else ""

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 275why, one step back
275

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 276why, one step back
276 for i, word in enumerate(words):

Merge pull request #1195 from bebleo/add_mailto_link_supportDavid Lordbefore adoptionf1b1caf

lines 277–279why, one step back
277 head, middle, tail = "", word, ""
278 match = re.match(r"^([(<]|&lt;)+", middle)279

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 280why, one step back
280 if match:

Merge pull request #1195 from bebleo/add_mailto_link_supportDavid Lordbefore adoptionf1b1caf

lines 281–313why, one step back
281 head = match.group()
282 middle = middle[match.end() :]283284 # Unlike lead, which is anchored to the start of the string,285 # need to check that the string ends with any of the characters286 # before trying to match all of them, to avoid backtracking.287 if middle.endswith((")", ">", ".", ",", "\n", "&gt;")):288 match = re.search(r"([)>.,\n]|&gt;)+$", middle)289290 if match:291 tail = match.group()292 middle = middle[: match.start()]293294 # Prefer balancing parentheses in URLs instead of ignoring a295 # trailing character.296 for start_char, end_char in ("(", ")"), ("<", ">"), ("&lt;", "&gt;"):297 start_count = middle.count(start_char)298299 if start_count <= middle.count(end_char):300 # Balanced, or lighter on the left301 continue302303 # Move as many as possible from the tail to balance304 for _ in range(min(start_count, tail.count(end_char))):305 end_index = tail.index(end_char) + len(end_char)306 # Move anything in the tail before the end char too307 middle += tail[:end_index]308 tail = tail[end_index:]309310 if _http_re.match(middle):311 if middle.startswith("https://") or middle.startswith("http://"):312 middle = (313 f'<a href="{middle}"{rel_attr}{target_attr}>{trim_url(middle)}</a>'

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 314why, one step back
314 )

Merge pull request #1195 from bebleo/add_mailto_link_supportDavid Lordbefore adoptionf1b1caf

line 315why, one step back
315 else:

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 316why, one step back
316 middle = (

Merge pull request #1195 from bebleo/add_mailto_link_supportDavid Lordbefore adoptionf1b1caf

line 317why, one step back
317 f'<a href="https://{middle}"{rel_attr}{target_attr}>'

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 318why, one step back
318 f"{trim_url(middle)}</a>"

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 319why, one step back
319 )

Merge pull request #1195 from bebleo/add_mailto_link_supportDavid Lordbefore adoptionf1b1caf

lines 320–338why, one step back
320
321 elif middle.startswith("mailto:") and _email_re.match(middle[7:]):322 middle = f'<a href="{middle}">{middle[7:]}</a>'323324 elif (325 "@" in middle326 and not middle.startswith("www.")327 and ":" not in middle328 and _email_re.match(middle)329 ):330 middle = f'<a href="mailto:{middle}">{middle}</a>'331332 elif extra_schemes is not None:333 for scheme in extra_schemes:334 if middle != scheme and middle.startswith(scheme):335 middle = f'<a href="{middle}"{rel_attr}{target_attr}>{middle}</a>'336337 words[i] = f"{head}{middle}{tail}"338

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 339why, one step back
339 return "".join(words)

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 340–341why, one step back
340
341

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 342–344why, one step back
342def generate_lorem_ipsum(
343 n: int = 5, html: bool = True, min: int = 20, max: int = 100344) -> str:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 345–380why, one step back
345 """Generate some lorem ipsum for the template."""
346 from .constants import LOREM_IPSUM_WORDS347348 words = LOREM_IPSUM_WORDS.split()349 result = []350351 for _ in range(n):352 next_capitalized = True353 last_comma = last_fullstop = 0354 word = None355 last = None356 p = []357358 # each paragraph contains out of 20 to 100 words.359 for idx, _ in enumerate(range(randrange(min, max))):360 while True:361 word = choice(words)362 if word != last:363 last = word364 break365 if next_capitalized:366 word = word.capitalize()367 next_capitalized = False368 # add commas369 if idx - randrange(3, 8) > last_comma:370 last_comma = idx371 last_fullstop += 2372 word += ","373 # add end of sentences374 if idx - randrange(10, 20) > last_fullstop:375 last_comma = last_fullstop = idx376 word += "."377 next_capitalized = True378 p.append(word)379380 # ensure that the paragraph ends with a dot.

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 381why, one step back
381 p_str = " ".join(p)

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 382why, one step back
382

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 383–389why, one step back
383 if p_str.endswith(","):
384 p_str = p_str[:-1] + "."385 elif not p_str.endswith("."):386 p_str += "."387388 result.append(p_str)389

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 390why, one step back
390 if not html:

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 391why, one step back
391 return "\n\n".join(result)

Merge pull request #1391 from pallets/markupsafe-importsDavid Lordbefore adoptiona9b06f4

lines 392–394why, one step back
392 return markupsafe.Markup(
393 "\n".join(f"<p>{markupsafe.escape(x)}</p>" for x in result)394 )

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 395–396why, one step back
395
396

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 397why, one step back
397def url_quote(obj: t.Any, charset: str = "utf-8", for_qs: bool = False) -> str:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 398–404why, one step back
398 """Quote a string for use in a URL using the given charset.
399400 :param obj: String or bytes to quote. Other types are converted to401 string then encoded to bytes using the given charset.402 :param charset: Encode text to bytes using this charset.403 :param for_qs: Quote "/" and use "+" for spaces.404 """

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 405–407why, one step back
405 if not isinstance(obj, bytes):
406 if not isinstance(obj, str):407 obj = str(obj)

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 408–411why, one step back
408
409 obj = obj.encode(charset)410411 safe = b"" if for_qs else b"/"

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 412why, one step back
412 rv = quote_from_bytes(obj, safe)

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 413–419why, one step back
413
414 if for_qs:415 rv = rv.replace("%20", "+")416417 return rv418419

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 420–421why, one step back
420@abc.MutableMapping.register
421class LRUCache:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 422–427why, one step back
422 """A simple LRU Cache implementation."""
423424 # this is fast for small capacities (something below 1000) but doesn't425 # scale. But as long as it's only used as storage for templates this426 # won't do any harm.427

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 428why, one step back
428 def __init__(self, capacity: int) -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 429why, one step back
429 self.capacity = capacity

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 430why, one step back
430 self._mapping: t.Dict[t.Any, t.Any] = {}

Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0

line 431why, one step back
431 self._queue: "te.Deque[t.Any]" = deque()

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 432–433why, one step back
432 self._postinit()
433

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 434why, one step back
434 def _postinit(self) -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 435–441why, one step back
435 # alias all queue methods for faster lookup
436 self._popleft = self._queue.popleft437 self._pop = self._queue.pop438 self._remove = self._queue.remove439 self._wlock = Lock()440 self._append = self._queue.append441

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 442why, one step back
442 def __getstate__(self) -> t.Mapping[str, t.Any]:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 443–448why, one step back
443 return {
444 "capacity": self.capacity,445 "_mapping": self._mapping,446 "_queue": self._queue,447 }448

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 449why, one step back
449 def __setstate__(self, d: t.Mapping[str, t.Any]) -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 450–452why, one step back
450 self.__dict__.update(d)
451 self._postinit()452

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 453why, one step back
453 def __getnewargs__(self) -> t.Tuple:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 454–455why, one step back
454 return (self.capacity,)
455

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 456why, one step back
456 def copy(self) -> "LRUCache":

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 457–462why, one step back
457 """Return a shallow copy of the instance."""
458 rv = self.__class__(self.capacity)459 rv._mapping.update(self._mapping)460 rv._queue.extend(self._queue)461 return rv462

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 463why, one step back
463 def get(self, key: t.Any, default: t.Any = None) -> t.Any:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 464–469why, one step back
464 """Return an item from the cache dict or `default`"""
465 try:466 return self[key]467 except KeyError:468 return default469

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 470why, one step back
470 def setdefault(self, key: t.Any, default: t.Any = None) -> t.Any:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 471–479why, one step back
471 """Set `default` if the key is not in the cache otherwise
472 leave unchanged. Return the value of this key.473 """474 try:475 return self[key]476 except KeyError:477 self[key] = default478 return default479

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 480why, one step back
480 def clear(self) -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 481why, one step back
481 """Clear the cache."""

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 482why, one step back
482 with self._wlock:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 483–485why, one step back
483 self._mapping.clear()
484 self._queue.clear()485

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 486why, one step back
486 def __contains__(self, key: t.Any) -> bool:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 487–489why, one step back
487 """Check if a key exists in this cache."""
488 return key in self._mapping489

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 490why, one step back
490 def __len__(self) -> int:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 491–493why, one step back
491 """Return the current size of the cache."""
492 return len(self._mapping)493

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 494–495why, one step back
494 def __repr__(self) -> str:
495 return f"<{type(self).__name__} {self._mapping!r}>"

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 496why, one step back
496

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 497why, one step back
497 def __getitem__(self, key: t.Any) -> t.Any:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 498–502why, one step back
498 """Get an item from the cache. Moves the item up so that it has the
499 highest priority then.500501 Raise a `KeyError` if it does not exist.502 """

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 503why, one step back
503 with self._wlock:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 504why, one step back
504 rv = self._mapping[key]

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 505why, one step back
505

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 506–513why, one step back
506 if self._queue[-1] != key:
507 try:508 self._remove(key)509 except ValueError:510 # if something removed the key from the container511 # when we read, ignore the ValueError that we would512 # get otherwise.513 pass

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 514why, one step back
514

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 515why, one step back
515 self._append(key)

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 516why, one step back
516

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 517–518why, one step back
517 return rv
518

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 519why, one step back
519 def __setitem__(self, key: t.Any, value: t.Any) -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 520–522why, one step back
520 """Sets the value for an item. Moves the item up so that it
521 has the highest priority then.522 """

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 523why, one step back
523 with self._wlock:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 524–527why, one step back
524 if key in self._mapping:
525 self._remove(key)526 elif len(self._mapping) == self.capacity:527 del self._mapping[self._popleft()]

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 528why, one step back
528

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 529–531why, one step back
529 self._append(key)
530 self._mapping[key] = value531

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 532why, one step back
532 def __delitem__(self, key: t.Any) -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 533–535why, one step back
533 """Remove an item from the cache dict.
534 Raise a `KeyError` if it does not exist.535 """

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 536why, one step back
536 with self._wlock:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 537why, one step back
537 del self._mapping[key]

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 538why, one step back
538

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 539–543why, one step back
539 try:
540 self._remove(key)541 except ValueError:542 pass543

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 544why, one step back
544 def items(self) -> t.Iterable[t.Tuple[t.Any, t.Any]]:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 545–549why, one step back
545 """Return a list of items."""
546 result = [(key, self._mapping[key]) for key in list(self._queue)]547 result.reverse()548 return result549

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 550why, one step back
550 def values(self) -> t.Iterable[t.Any]:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 551–553why, one step back
551 """Return a list of all values."""
552 return [x[1] for x in self.items()]553

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 554why, one step back
554 def keys(self) -> t.Iterable[t.Any]:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 555–557why, one step back
555 """Return a list of all keys ordered by most recent usage."""
556 return list(self)557

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 558why, one step back
558 def __iter__(self) -> t.Iterator[t.Any]:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 559–560why, one step back
559 return reversed(tuple(self._queue))
560

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 561why, one step back
561 def __reversed__(self) -> t.Iterator[t.Any]:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 562–570why, one step back
562 """Iterate over the keys in the cache dict, oldest items
563 coming first.564 """565 return iter(tuple(self._queue))566567 __copy__ = copy568569570def select_autoescape(

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 571–575why, one step back
571 enabled_extensions: t.Collection[str] = ("html", "htm", "xml"),
572 disabled_extensions: t.Collection[str] = (),573 default_for_string: bool = True,574 default: bool = False,575) -> t.Callable[[t.Optional[str]], bool]:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 576–609why, one step back
576 """Intelligently sets the initial value of autoescaping based on the
577 filename of the template. This is the recommended way to configure578 autoescaping if you do not want to write a custom function yourself.579580 If you want to enable it for all templates created from strings or581 for all templates with `.html` and `.xml` extensions::582583 from jinja2 import Environment, select_autoescape584 env = Environment(autoescape=select_autoescape(585 enabled_extensions=('html', 'xml'),586 default_for_string=True,587 ))588589 Example configuration to turn it on at all times except if the template590 ends with `.txt`::591592 from jinja2 import Environment, select_autoescape593 env = Environment(autoescape=select_autoescape(594 disabled_extensions=('txt',),595 default_for_string=True,596 default=True,597 ))598599 The `enabled_extensions` is an iterable of all the extensions that600 autoescaping should be enabled for. Likewise `disabled_extensions` is601 a list of all templates it should be disabled for. If a template is602 loaded from a string then the default from `default_for_string` is used.603 If nothing matches then the initial value of autoescaping is set to the604 value of `default`.605606 For security reasons this function operates case insensitive.607608 .. versionadded:: 2.9609 """

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 610–611why, one step back
610 enabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in enabled_extensions)
611 disabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in disabled_extensions)

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 612why, one step back
612

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 613why, one step back
613 def autoescape(template_name: t.Optional[str]) -> bool:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 614–625why, one step back
614 if template_name is None:
615 return default_for_string616 template_name = template_name.lower()617 if template_name.endswith(enabled_patterns):618 return True619 if template_name.endswith(disabled_patterns):620 return False621 return default622623 return autoescape624625

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 626–627why, one step back
626def htmlsafe_json_dumps(
627 obj: t.Any, dumps: t.Optional[t.Callable[..., str]] = None, **kwargs: t.Any

Merge pull request #1391 from pallets/markupsafe-importsDavid Lordbefore adoptiona9b06f4

line 628why, one step back
628) -> markupsafe.Markup:

Merge pull request #1348 from pallets/json-docsDavid Lordbefore adoptionf009a00

lines 629–631why, one step back
629 """Serialize an object to a string of JSON with :func:`json.dumps`,
630 then replace HTML-unsafe characters with Unicode escapes and mark631 the result safe with :class:`~markupsafe.Markup`.

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 632why, one step back
632

Merge pull request #1348 from pallets/json-docsDavid Lordbefore adoptionf009a00

line 633why, one step back
633 This is available in templates as the ``|tojson`` filter.

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 634why, one step back
634

Merge pull request #1348 from pallets/json-docsDavid Lordbefore adoptionf009a00

line 635why, one step back
635 The following characters are escaped: ``<``, ``>``, ``&``, ``'``.

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 636why, one step back
636

Merge pull request #1348 from pallets/json-docsDavid Lordbefore adoptionf009a00

lines 637–652why, one step back
637 The returned string is safe to render in HTML documents and
638 ``<script>`` tags. The exception is in HTML attributes that are639 double quoted; either use single quotes or the ``|forceescape``640 filter.641642 :param obj: The object to serialize to JSON.643 :param dumps: The ``dumps`` function to use. Defaults to644 ``env.policies["json.dumps_function"]``, which defaults to645 :func:`json.dumps`.646 :param kwargs: Extra arguments to pass to ``dumps``. Merged onto647 ``env.policies["json.dumps_kwargs"]``.648649 .. versionchanged:: 3.0650 The ``dumper`` parameter is renamed to ``dumps``.651652 .. versionadded:: 2.9

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 653why, one step back
653 """

Merge pull request #1348 from pallets/json-docsDavid Lordbefore adoptionf009a00

lines 654–656why, one step back
654 if dumps is None:
655 dumps = json.dumps656

Merge pull request #1391 from pallets/markupsafe-importsDavid Lordbefore adoptiona9b06f4

line 657why, one step back
657 return markupsafe.Markup(

Merge pull request #1348 from pallets/json-docsDavid Lordbefore adoptionf009a00

line 658why, one step back
658 dumps(obj, **kwargs)

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 659–662why, one step back
659 .replace("<", "\\u003c")
660 .replace(">", "\\u003e")661 .replace("&", "\\u0026")662 .replace("'", "\\u0027")

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 663–665why, one step back
663 )
664665

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 666why, one step back
666class Cycler:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 667–691why, one step back
667 """Cycle through values by yield them one at a time, then restarting
668 once the end is reached. Available as ``cycler`` in templates.669670 Similar to ``loop.cycle``, but can be used outside loops or across671 multiple loops. For example, render a list of folders and files in a672 list, alternating giving them "odd" and "even" classes.673674 .. code-block:: html+jinja675676 {% set row_class = cycler("odd", "even") %}677 <ul class="browser">678 {% for folder in folders %}679 <li class="folder {{ row_class.next() }}">{{ folder }}680 {% endfor %}681 {% for file in files %}682 <li class="file {{ row_class.next() }}">{{ file }}683 {% endfor %}684 </ul>685686 :param items: Each positional argument will be yielded in the order687 given for each cycle.688689 .. versionadded:: 2.1690 """691

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 692why, one step back
692 def __init__(self, *items: t.Any) -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 693–697why, one step back
693 if not items:
694 raise RuntimeError("at least one item has to be provided")695 self.items = items696 self.pos = 0697

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 698why, one step back
698 def reset(self) -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 699–702why, one step back
699 """Resets the current item to the first item."""
700 self.pos = 0701702 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 703why, one step back
703 def current(self) -> t.Any:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 704–708why, one step back
704 """Return the current item. Equivalent to the item that will be
705 returned next time :meth:`next` is called.706 """707 return self.items[self.pos]708

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 709why, one step back
709 def next(self) -> t.Any:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 710–719why, one step back
710 """Return the current item, then advance :attr:`current` to the
711 next item.712 """713 rv = self.current714 self.pos = (self.pos + 1) % len(self.items)715 return rv716717 __next__ = next718719

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 720why, one step back
720class Joiner:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 721–722why, one step back
721 """A joining helper for templates."""
722

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 723why, one step back
723 def __init__(self, sep: str = ", ") -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 724–726why, one step back
724 self.sep = sep
725 self.used = False726

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 727why, one step back
727 def __call__(self) -> str:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 728–729why, one step back
728 if not self.used:
729 self.used = True

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 730why, one step back
730 return ""

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 731–733why, one step back
731 return self.sep
732733

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 734why, one step back
734class Namespace:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 735–737why, one step back
735 """A namespace object that can hold arbitrary attributes. It may be
736 initialized from a dictionary or with keyword arguments."""737

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 738why, one step back
738 def __init__(*args: t.Any, **kwargs: t.Any) -> None: # noqa: B902

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 739–741why, one step back
739 self, args = args[0], args[1:]
740 self.__attrs = dict(*args, **kwargs)741

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 742why, one step back
742 def __getattribute__(self, name: str) -> t.Any:

Merge branch '2.11.x'David Lordbefore adoption0a37031

lines 743–744why, one step back
743 # __class__ is needed for the awaitable check in async mode
744 if name in {"_Namespace__attrs", "__class__"}:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 745–748why, one step back
745 return object.__getattribute__(self, name)
746 try:747 return self.__attrs[name]748 except KeyError:

Merge branch '3.0.x'David Lordbefore adoptione20a52e

line 749why, one step back
749 raise AttributeError(name) from None

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 750why, one step back
750

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 751why, one step back
751 def __setitem__(self, name: str, value: t.Any) -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 752–753why, one step back
752 self.__attrs[name] = value
753

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 754why, one step back
754 def __repr__(self) -> str:

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 755why, one step back
755 return f"<Namespace {self.__attrs!r}>"