Skip to content
Myr

utils.py

This file

Path

src/jinja2/utils.py

766 lines · 23.5 KiB · Python

Last changed by

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

History of this file

Take it

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

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

line 1why, one step back
1import enum

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 6–10why, one step back
6from collections import abc
7from collections import deque8from 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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 12–13why, one step back
12from urllib.parse import quote_from_bytes
13

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

line 14why, one step back
14import markupsafe

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 21why, one step back
21

Merge branch 'stable'David Lordbefore adoption6aeab5d

lines 22–32why, one step back
22class _MissingType:
23 def __repr__(self) -> str:24 return "missing"2526 def __reduce__(self) -> str:27 return "missing"282930missing: t.Any = _MissingType()31"""Special singleton representing missing values for the runtime."""32

Merge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 34–37why, one step back
34
35concat = "".join3637

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 41why, one step back
41

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

lines 42–49why, one step back
42 Can be used on functions, filters, and tests.
4344 If only ``Context.eval_context`` is needed, use45 :func:`pass_eval_context`. If only ``Context.environment`` is46 needed, use :func:`pass_environment`.4748 .. versionadded:: 3.0.049 Replaces ``contextfunction`` and ``contextfilter``.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 50why, one step back
50 """

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

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 52–54why, one step back
52 return f
5354

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 56–71why, one step back
56 """Pass the :class:`~jinja2.nodes.EvalContext` as the first argument
57 to the decorated function when called while rendering a template.58 See :ref:`eval-context`.5960 Can be used on functions, filters, and tests.6162 If only ``EvalContext.environment`` is needed, use63 :func:`pass_environment`.6465 .. versionadded:: 3.0.066 Replaces ``evalcontextfunction`` and ``evalcontextfilter``.67 """68 f.jinja_pass_arg = _PassArg.eval_context # type: ignore69 return f7071

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 73–90why, one step back
73 """Pass the :class:`~jinja2.Environment` as the first argument to
74 the decorated function when called while rendering a template.7576 Can be used on functions, filters, and tests.7778 .. versionadded:: 3.0.079 Replaces ``environmentfunction`` and ``environmentfilter``.80 """81 f.jinja_pass_arg = _PassArg.environment # type: ignore82 return f838485class _PassArg(enum.Enum):86 context = enum.auto()87 eval_context = enum.auto()88 environment = enum.auto()8990 @classmethod

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

line 94why, one step back
94

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 95why, one step back
95 return None

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

line 96why, one step back
96

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 99–103why, one step back
99 """Marks the function as internally used"""
100 internal_code.add(f.__code__)101 return f102103

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 105–120why, one step back
105 """Check if the object passed is undefined. This does nothing more than
106 performing an instance check against :class:`Undefined` but looks nicer.107 This can be used for custom filters or tests that want to react to108 undefined variables. For example a custom default filter can look like109 this::110111 def default(var, default=''):112 if is_undefined(var):113 return default114 return var115 """116 from .runtime import Undefined117118 return isinstance(obj, Undefined)119120

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 122–126why, one step back
122 """Consumes an iterable without doing anything with it."""
123 for _ in iterable:124 pass125126

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 134–135why, one step back
134 from .lexer import _lexer_cache
135

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 137–139why, one step back
137 _lexer_cache.clear()
138139

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 141–163why, one step back
141 """Imports an object based on a string. This is useful if you want to
142 use import paths as endpoints or something similar. An import path can143 be specified either in dotted notation (``xml.sax.saxutils.escape``)144 or with a colon as object delimiter (``xml.sax.saxutils:escape``).145146 If the `silent` is True the return value will be `None` if the import147 fails.148149 :return: imported object150 """151 try:152 if ":" in import_name:153 module, obj = import_name.split(":", 1)154 elif "." in import_name:155 module, _, obj = import_name.rpartition(".")156 else:157 return __import__(import_name)158 return getattr(__import__(module, None, None, [obj]), obj)159 except (ImportError, AttributeError):160 if not silent:161 raise162163

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 165–173why, one step back
165 """Returns a file descriptor for the filename if that file exists,
166 otherwise ``None``.167 """168 if not os.path.isfile(filename):169 return None170171 return open(filename, mode)172173

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 175–191why, one step back
175 """Returns the name of the object's type. For some recognized
176 singletons the name of the object is returned instead. (For177 example for `None` and `Ellipsis`).178 """179 if obj is None:180 return "None"181 elif obj is Ellipsis:182 return "Ellipsis"183184 cls = type(obj)185186 if cls.__module__ == "builtins":187 return f"{cls.__name__} object"188189 return f"{cls.__module__}.{cls.__name__} object"190191

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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

Merge branch '3.1.x'David Lordbefore adoption81a2384

line 194why, one step back
194 from pprint import pformat

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 195–229why, one step back
195
196 return pformat(obj)197198199_http_re = re.compile(200 r"""201 ^202 (203 (https?://|www\.) # scheme or www204 (([\w%-]+\.)+)? # subdomain205 (206 [a-z]{2,63} # basic tld207 |208 xn--[\w%]{2,59} # idna tld209 )210 |211 ([\w%-]{2,63}\.)+ # basic domain212 (com|net|int|edu|gov|org|info|mil) # basic tld213 |214 (https?://) # scheme215 (216 (([\d]{1,3})(\.[\d]{1,3}){3}) # IPv4217 |218 (\[([\da-f]{0,4}:){2}([\da-f]{0,4}:?){1,6}]) # IPv6219 )220 )221 (?::[\d]{1,5})? # port222 (?:[/?#]\S*)? # path, query, and fragment223 $224 """,225 re.IGNORECASE | re.VERBOSE,226)227_email_re = re.compile(r"^\S+@\w[\w.-]*\.\w+$")228229

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

lines 230–231why, one step back
230def urlize(
231 text: str,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 232–235why, one step back
232 trim_url_limit: int | None = None,
233 rel: str | None = None,234 target: str | None = None,235 extra_schemes: t.Iterable[str] | None = None,

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

line 236why, one step back
236) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 237–269why, one step back
237 """Convert URLs in text into clickable links.
238239 This may not recognize links in some situations. Usually, a more240 comprehensive formatter, such as a Markdown library, is a better241 choice.242243 Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email244 addresses. Links with trailing punctuation (periods, commas, closing245 parentheses) and leading punctuation (opening parentheses) are246 recognized excluding the punctuation. Email addresses that include247 header fields are not recognized (for example,248 ``mailto:address@example.com?cc=copy@example.com``).249250 :param text: Original text containing URLs to link.251 :param trim_url_limit: Shorten displayed URL values to this length.252 :param target: Add the ``target`` attribute to links.253 :param rel: Add the ``rel`` attribute to links.254 :param extra_schemes: Recognize URLs that start with these schemes255 in addition to the default behavior.256257 .. versionchanged:: 3.0258 The ``extra_schemes`` parameter was added.259260 .. versionchanged:: 3.0261 Generate ``https://`` links for URLs without a scheme.262263 .. versionchanged:: 3.0264 The parsing rules were updated. Recognize email addresses with265 or without the ``mailto:`` scheme. Validate IP addresses. Ignore266 parentheses and brackets in more cases.267 """268 if trim_url_limit is not None:269

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

Merge branch '3.1.x'David Lordbefore adoptionc0e4f69

line 271why, one step back
271 if len(x) > trim_url_limit:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 272–277why, one step back
272 return f"{x[:trim_url_limit]}..."
273274 return x275276 else:277

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 279–280why, one step back
279 return x
280

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

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 284–335why, one step back
284
285 for i, word in enumerate(words):286 head, middle, tail = "", word, ""287 match = re.match(r"^([(<]|&lt;)+", middle)288289 if match:290 head = match.group()291 middle = middle[match.end() :]292293 # Unlike lead, which is anchored to the start of the string,294 # need to check that the string ends with any of the characters295 # before trying to match all of them, to avoid backtracking.296 if middle.endswith((")", ">", ".", ",", "\n", "&gt;")):297 match = re.search(r"([)>.,\n]|&gt;)+$", middle)298299 if match:300 tail = match.group()301 middle = middle[: match.start()]302303 # Prefer balancing parentheses in URLs instead of ignoring a304 # trailing character.305 for start_char, end_char in ("(", ")"), ("<", ">"), ("&lt;", "&gt;"):306 start_count = middle.count(start_char)307308 if start_count <= middle.count(end_char):309 # Balanced, or lighter on the left310 continue311312 # Move as many as possible from the tail to balance313 for _ in range(min(start_count, tail.count(end_char))):314 end_index = tail.index(end_char) + len(end_char)315 # Move anything in the tail before the end char too316 middle += tail[:end_index]317 tail = tail[end_index:]318319 if _http_re.match(middle):320 if middle.startswith("https://") or middle.startswith("http://"):321 middle = (322 f'<a href="{middle}"{rel_attr}{target_attr}>{trim_url(middle)}</a>'323 )324 else:325 middle = (326 f'<a href="https://{middle}"{rel_attr}{target_attr}>'327 f"{trim_url(middle)}</a>"328 )329330 elif middle.startswith("mailto:") and _email_re.match(middle[7:]):331 middle = f'<a href="{middle}">{middle[7:]}</a>'332333 elif (334 "@" in middle335 and not middle.startswith("www.")

Merge branch 'stable'David Lordbefore adoption6aeab5d

lines 336–337why, one step back
336 # ignore values like `@a@b`
337 and not middle.startswith("@")

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 338–352why, one step back
338 and ":" not in middle
339 and _email_re.match(middle)340 ):341 middle = f'<a href="mailto:{middle}">{middle}</a>'342343 elif extra_schemes is not None:344 for scheme in extra_schemes:345 if middle != scheme and middle.startswith(scheme):346 middle = f'<a href="{middle}"{rel_attr}{target_attr}>{middle}</a>'347348 words[i] = f"{head}{middle}{tail}"349350 return "".join(words)351352

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 353–355why, one step back
353def generate_lorem_ipsum(
354 n: int = 5, html: bool = True, min: int = 20, max: int = 100355) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 356–391why, one step back
356 """Generate some lorem ipsum for the template."""
357 from .constants import LOREM_IPSUM_WORDS358359 words = LOREM_IPSUM_WORDS.split()360 result = []361362 for _ in range(n):363 next_capitalized = True364 last_comma = last_fullstop = 0365 word = None366 last = None367 p = []368369 # each paragraph contains out of 20 to 100 words.370 for idx, _ in enumerate(range(randrange(min, max))):371 while True:372 word = choice(words)373 if word != last:374 last = word375 break376 if next_capitalized:377 word = word.capitalize()378 next_capitalized = False379 # add commas380 if idx - randrange(3, 8) > last_comma:381 last_comma = idx382 last_fullstop += 2383 word += ","384 # add end of sentences385 if idx - randrange(10, 20) > last_fullstop:386 last_comma = last_fullstop = idx387 word += "."388 next_capitalized = True389 p.append(word)390391 # ensure that the paragraph ends with a dot.

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 393why, one step back
393

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 394–400why, one step back
394 if p_str.endswith(","):
395 p_str = p_str[:-1] + "."396 elif not p_str.endswith("."):397 p_str += "."398399 result.append(p_str)400

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 401–402why, one step back
401 if not html:
402 return "\n\n".join(result)

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

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 406–407why, one step back
406
407

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

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 409–438why, one step back
409 """Quote a string for use in a URL using the given charset.
410411 :param obj: String or bytes to quote. Other types are converted to412 string then encoded to bytes using the given charset.413 :param charset: Encode text to bytes using this charset.414 :param for_qs: Quote "/" and use "+" for spaces.415 """416 if not isinstance(obj, bytes):417 if not isinstance(obj, str):418 obj = str(obj)419420 obj = obj.encode(charset)421422 safe = b"" if for_qs else b"/"423 rv = quote_from_bytes(obj, safe)424425 if for_qs:426 rv = rv.replace("%20", "+")427428 return rv429430431@abc.MutableMapping.register432class LRUCache:433 """A simple LRU Cache implementation."""434435 # this is fast for small capacities (something below 1000) but doesn't436 # scale. But as long as it's only used as storage for templates this437 # won't do any harm.438

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

lines 441–442why, one step back
441 self._mapping: dict[t.Any, t.Any] = {}
442 self._queue: deque[t.Any] = deque()

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 443–444why, one step back
443 self._postinit()
444

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 446–452why, one step back
446 # alias all queue methods for faster lookup
447 self._popleft = self._queue.popleft448 self._pop = self._queue.pop449 self._remove = self._queue.remove450 self._wlock = Lock()451 self._append = self._queue.append452

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 454–459why, one step back
454 return {
455 "capacity": self.capacity,456 "_mapping": self._mapping,457 "_queue": self._queue,458 }459

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 461–463why, one step back
461 self.__dict__.update(d)
462 self._postinit()463

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 464why, one step back
464 def __getnewargs__(self) -> tuple[t.Any, ...]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 465–466why, one step back
465 return (self.capacity,)
466

Merge branch 'stable'David Lordbefore adoption6aeab5d

line 467why, one step back
467 def copy(self) -> "te.Self":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 468–473why, one step back
468 """Return a shallow copy of the instance."""
469 rv = self.__class__(self.capacity)470 rv._mapping.update(self._mapping)471 rv._queue.extend(self._queue)472 return rv473

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 475–480why, one step back
475 """Return an item from the cache dict or `default`"""
476 try:477 return self[key]478 except KeyError:479 return default480

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 482–490why, one step back
482 """Set `default` if the key is not in the cache otherwise
483 leave unchanged. Return the value of this key.484 """485 try:486 return self[key]487 except KeyError:488 self[key] = default489 return default490

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 494–496why, one step back
494 self._mapping.clear()
495 self._queue.clear()496

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 498–500why, one step back
498 """Check if a key exists in this cache."""
499 return key in self._mapping500

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 502–504why, one step back
502 """Return the current size of the cache."""
503 return len(self._mapping)504

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 507why, one step back
507

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 516why, one step back
516

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 517–524why, one step back
517 if self._queue[-1] != key:
518 try:519 self._remove(key)520 except ValueError:521 # if something removed the key from the container522 # when we read, ignore the ValueError that we would523 # get otherwise.524 pass

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 525why, one step back
525

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 527why, one step back
527

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 528–529why, one step back
528 return rv
529

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 535–538why, one step back
535 if key in self._mapping:
536 self._remove(key)537 elif len(self._mapping) == self.capacity:538 del self._mapping[self._popleft()]

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 539why, one step back
539

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 540–542why, one step back
540 self._append(key)
541 self._mapping[key] = value542

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 549why, one step back
549

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 550–554why, one step back
550 try:
551 self._remove(key)552 except ValueError:553 pass554

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 556–560why, one step back
556 """Return a list of items."""
557 result = [(key, self._mapping[key]) for key in list(self._queue)]558 result.reverse()559 return result560

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 570–571why, one step back
570 return reversed(tuple(self._queue))
571

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 573–581why, one step back
573 """Iterate over the keys in the cache dict, oldest items
574 coming first.575 """576 return iter(tuple(self._queue))577578 __copy__ = copy579580581def select_autoescape(

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 582–585why, one step back
582 enabled_extensions: t.Collection[str] = ("html", "htm", "xml"),
583 disabled_extensions: t.Collection[str] = (),584 default_for_string: bool = True,585 default: bool = False,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 586why, one step back
586) -> t.Callable[[str | None], bool]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 587–623why, one step back
587 """Intelligently sets the initial value of autoescaping based on the
588 filename of the template. This is the recommended way to configure589 autoescaping if you do not want to write a custom function yourself.590591 If you want to enable it for all templates created from strings or592 for all templates with `.html` and `.xml` extensions::593594 from jinja2 import Environment, select_autoescape595 env = Environment(autoescape=select_autoescape(596 enabled_extensions=('html', 'xml'),597 default_for_string=True,598 ))599600 Example configuration to turn it on at all times except if the template601 ends with `.txt`::602603 from jinja2 import Environment, select_autoescape604 env = Environment(autoescape=select_autoescape(605 disabled_extensions=('txt',),606 default_for_string=True,607 default=True,608 ))609610 The `enabled_extensions` is an iterable of all the extensions that611 autoescaping should be enabled for. Likewise `disabled_extensions` is612 a list of all templates it should be disabled for. If a template is613 loaded from a string then the default from `default_for_string` is used.614 If nothing matches then the initial value of autoescaping is set to the615 value of `default`.616617 For security reasons this function operates case insensitive.618619 .. versionadded:: 2.9620 """621 enabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in enabled_extensions)622 disabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in disabled_extensions)623

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 624why, one step back
624 def autoescape(template_name: str | None) -> bool:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 625–636why, one step back
625 if template_name is None:
626 return default_for_string627 template_name = template_name.lower()628 if template_name.endswith(enabled_patterns):629 return True630 if template_name.endswith(disabled_patterns):631 return False632 return default633634 return autoescape635636

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

line 637why, one step back
637def htmlsafe_json_dumps(

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 638why, one step back
638 obj: t.Any, dumps: t.Callable[..., str] | None = None, **kwargs: t.Any

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

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 640–667why, one step back
640 """Serialize an object to a string of JSON with :func:`json.dumps`,
641 then replace HTML-unsafe characters with Unicode escapes and mark642 the result safe with :class:`~markupsafe.Markup`.643644 This is available in templates as the ``|tojson`` filter.645646 The following characters are escaped: ``<``, ``>``, ``&``, ``'``.647648 The returned string is safe to render in HTML documents and649 ``<script>`` tags. The exception is in HTML attributes that are650 double quoted; either use single quotes or the ``|forceescape``651 filter.652653 :param obj: The object to serialize to JSON.654 :param dumps: The ``dumps`` function to use. Defaults to655 ``env.policies["json.dumps_function"]``, which defaults to656 :func:`json.dumps`.657 :param kwargs: Extra arguments to pass to ``dumps``. Merged onto658 ``env.policies["json.dumps_kwargs"]``.659660 .. versionchanged:: 3.0661 The ``dumper`` parameter is renamed to ``dumps``.662663 .. versionadded:: 2.9664 """665 if dumps is None:666 dumps = json.dumps667

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

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 669–702why, one step back
669 dumps(obj, **kwargs)
670 .replace("<", "\\u003c")671 .replace(">", "\\u003e")672 .replace("&", "\\u0026")673 .replace("'", "\\u0027")674 )675676677class Cycler:678 """Cycle through values by yield them one at a time, then restarting679 once the end is reached. Available as ``cycler`` in templates.680681 Similar to ``loop.cycle``, but can be used outside loops or across682 multiple loops. For example, render a list of folders and files in a683 list, alternating giving them "odd" and "even" classes.684685 .. code-block:: html+jinja686687 {% set row_class = cycler("odd", "even") %}688 <ul class="browser">689 {% for folder in folders %}690 <li class="folder {{ row_class.next() }}">{{ folder }}691 {% endfor %}692 {% for file in files %}693 <li class="file {{ row_class.next() }}">{{ file }}694 {% endfor %}695 </ul>696697 :param items: Each positional argument will be yielded in the order698 given for each cycle.699700 .. versionadded:: 2.1701 """702

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 704–708why, one step back
704 if not items:
705 raise RuntimeError("at least one item has to be provided")706 self.items = items707 self.pos = 0708

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 710–713why, one step back
710 """Resets the current item to the first item."""
711 self.pos = 0712713 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 715–719why, one step back
715 """Return the current item. Equivalent to the item that will be
716 returned next time :meth:`next` is called.717 """718 return self.items[self.pos]719

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 721–733why, one step back
721 """Return the current item, then advance :attr:`current` to the
722 next item.723 """724 rv = self.current725 self.pos = (self.pos + 1) % len(self.items)726 return rv727728 __next__ = next729730731class Joiner:732 """A joining helper for templates."""733

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 735–737why, one step back
735 self.sep = sep
736 self.used = False737

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 739–748why, one step back
739 if not self.used:
740 self.used = True741 return ""742 return self.sep743744745class Namespace:746 """A namespace object that can hold arbitrary attributes. It may be747 initialized from a dictionary or with keyword arguments."""748

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 750–752why, one step back
750 self, args = args[0], args[1:]
751 self.__attrs = dict(*args, **kwargs)752

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 754–759why, one step back
754 # __class__ is needed for the awaitable check in async mode
755 if name in {"_Namespace__attrs", "__class__"}:756 return object.__getattribute__(self, name)757 try:758 return self.__attrs[name]759 except KeyError:

Merge branch '3.0.x'David Lordbefore adoptione20a52e

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 761why, one step back
761

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 763–764why, one step back
763 self.__attrs[name] = value
764

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

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