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 fileTake 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 back1import enumupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 2–4why, one step back2import json3import os4import reMerge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c
line 5why, one step back5import typing as tupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 6–10why, one step back6from collections import abc7from collections import deque8from random import choice9from random import randrange10from threading import LockMerge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c
line 11why, one step back11from types import CodeTypeupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 12–13why, one step back12from urllib.parse import quote_from_bytes13Merge pull request #1391 from pallets/markupsafe-importsDavid Lordbefore adoptiona9b06f4
line 14why, one step back14import markupsafeupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 15why, one step back15Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0
lines 16–18why, one step back16if t.TYPE_CHECKING:17 import typing_extensions as te18Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 19why, one step back19F = t.TypeVar("F", bound=t.Callable[..., t.Any])Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 20why, one step back20update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 21why, one step back21Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 22–32why, one step back22class _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."""32Merge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c
line 33why, one step back33internal_code: t.MutableSet[CodeType] = set()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 34–37why, one step back3435concat = "".join3637Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 38why, one step back38def pass_context(f: F) -> F:Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 39–40why, one step back39 """Pass the :class:`~jinja2.runtime.Context` as the first argument40 to the decorated function when called while rendering a template.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 41why, one step back41Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 42–49why, one step back42 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 back50 """Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 51why, one step back51 f.jinja_pass_arg = _PassArg.context # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 52–54why, one step back52 return f5354Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 55why, one step back55def pass_eval_context(f: F) -> F:Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 56–71why, one step back56 """Pass the :class:`~jinja2.nodes.EvalContext` as the first argument57 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 f7071Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 72why, one step back72def pass_environment(f: F) -> F:Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 73–90why, one step back73 """Pass the :class:`~jinja2.Environment` as the first argument to74 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 @classmethodMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 91why, one step back91 def from_obj(cls, obj: F) -> t.Optional["_PassArg"]:Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 92why, one step back92 if hasattr(obj, "jinja_pass_arg"):Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 93why, one step back93 return obj.jinja_pass_arg # type: ignoreMerge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 94why, one step back94Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 95why, one step back95 return NoneMerge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 96why, one step back96Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 97–98why, one step back9798def internalcode(f: F) -> F:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 99–103why, one step back99 """Marks the function as internally used"""100 internal_code.add(f.__code__)101 return f102103Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 104why, one step back104def is_undefined(obj: t.Any) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 105–120why, one step back105 """Check if the object passed is undefined. This does nothing more than106 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)119120Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 121why, one step back121def consume(iterable: t.Iterable[t.Any]) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 122–126why, one step back122 """Consumes an iterable without doing anything with it."""123 for _ in iterable:124 pass125126Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 127why, one step back127def clear_caches() -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 128–132why, one step back128 """Jinja keeps internal caches for environments and lexers. These are129 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 back133 from .environment import get_spontaneous_environmentupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 134–135why, one step back134 from .lexer import _lexer_cache135Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 136why, one step back136 get_spontaneous_environment.cache_clear()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 137–139why, one step back137 _lexer_cache.clear()138139Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 140why, one step back140def 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 back141 """Imports an object based on a string. This is useful if you want to142 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 raise162163drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 164why, one step back164def 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 back165 """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)172173Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 174why, one step back174def object_type_repr(obj: t.Any) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 175–191why, one step back175 """Returns the name of the object's type. For some recognized176 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"190191Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 192why, one step back192def pformat(obj: t.Any) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 193why, one step back193 """Format an object using :func:`pprint.pformat`."""Merge branch '3.1.x'David Lordbefore adoption81a2384
line 194why, one step back194 from pprint import pformatupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 195–229why, one step back195196 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+$")228229Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 230–231why, one step back230def urlize(231 text: str,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 232–235why, one step back232 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 back236) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 237–269why, one step back237 """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:269Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 270why, one step back270 def trim_url(x: str) -> str:Merge branch '3.1.x'David Lordbefore adoptionc0e4f69
line 271why, one step back271 if len(x) > trim_url_limit:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 272–277why, one step back272 return f"{x[:trim_url_limit]}..."273274 return x275276 else:277Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 278why, one step back278 def trim_url(x: str) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 279–280why, one step back279 return x280Merge pull request #1391 from pallets/markupsafe-importsDavid Lordbefore adoptiona9b06f4
lines 281–283why, one step back281 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 back284285 for i, word in enumerate(words):286 head, middle, tail = "", word, ""287 match = re.match(r"^([(<]|<)+", 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", ">")):297 match = re.search(r"([)>.,\n]|>)+$", 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 ("(", ")"), ("<", ">"), ("<", ">"):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 back336 # 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 back338 and ":" not in middle339 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)351352Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 353–355why, one step back353def 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 back356 """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 back392 p_str = " ".join(p)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 393why, one step back393Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 394–400why, one step back394 if p_str.endswith(","):395 p_str = p_str[:-1] + "."396 elif not p_str.endswith("."):397 p_str += "."398399 result.append(p_str)400update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 401–402why, one step back401 if not html:402 return "\n\n".join(result)Merge pull request #1391 from pallets/markupsafe-importsDavid Lordbefore adoptiona9b06f4
lines 403–405why, one step back403 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 back406407Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 408why, one step back408def 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 back409 """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.438Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 439why, one step back439 def __init__(self, capacity: int) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 440why, one step back440 self.capacity = capacityUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 441–442why, one step back441 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 back443 self._postinit()444Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 445why, one step back445 def _postinit(self) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 446–452why, one step back446 # alias all queue methods for faster lookup447 self._popleft = self._queue.popleft448 self._pop = self._queue.pop449 self._remove = self._queue.remove450 self._wlock = Lock()451 self._append = self._queue.append452Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 453why, one step back453 def __getstate__(self) -> t.Mapping[str, t.Any]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 454–459why, one step back454 return {455 "capacity": self.capacity,456 "_mapping": self._mapping,457 "_queue": self._queue,458 }459Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 460why, one step back460 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 back461 self.__dict__.update(d)462 self._postinit()463Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 464why, one step back464 def __getnewargs__(self) -> tuple[t.Any, ...]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 465–466why, one step back465 return (self.capacity,)466Merge branch 'stable'David Lordbefore adoption6aeab5d
line 467why, one step back467 def copy(self) -> "te.Self":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 468–473why, one step back468 """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 rv473Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 474why, one step back474 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 back475 """Return an item from the cache dict or `default`"""476 try:477 return self[key]478 except KeyError:479 return default480Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 481why, one step back481 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 back482 """Set `default` if the key is not in the cache otherwise483 leave unchanged. Return the value of this key.484 """485 try:486 return self[key]487 except KeyError:488 self[key] = default489 return default490Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 491why, one step back491 def clear(self) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 492why, one step back492 """Clear the cache."""Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 493why, one step back493 with self._wlock:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 494–496why, one step back494 self._mapping.clear()495 self._queue.clear()496Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 497why, one step back497 def __contains__(self, key: t.Any) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 498–500why, one step back498 """Check if a key exists in this cache."""499 return key in self._mapping500Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 501why, one step back501 def __len__(self) -> int:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 502–504why, one step back502 """Return the current size of the cache."""503 return len(self._mapping)504Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 505–506why, one step back505 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 back507Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 508why, one step back508 def __getitem__(self, key: t.Any) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 509–513why, one step back509 """Get an item from the cache. Moves the item up so that it has the510 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 back514 with self._wlock:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 515why, one step back515 rv = self._mapping[key]Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 516why, one step back516update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 517–524why, one step back517 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 passMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 525why, one step back525update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 526why, one step back526 self._append(key)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 527why, one step back527update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 528–529why, one step back528 return rv529Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 530why, one step back530 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 back531 """Sets the value for an item. Moves the item up so that it532 has the highest priority then.533 """Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 534why, one step back534 with self._wlock:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 535–538why, one step back535 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 back539update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 540–542why, one step back540 self._append(key)541 self._mapping[key] = value542Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 543why, one step back543 def __delitem__(self, key: t.Any) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 544–546why, one step back544 """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 back547 with self._wlock:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 548why, one step back548 del self._mapping[key]Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 549why, one step back549update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 550–554why, one step back550 try:551 self._remove(key)552 except ValueError:553 pass554Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 555why, one step back555 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 back556 """Return a list of items."""557 result = [(key, self._mapping[key]) for key in list(self._queue)]558 result.reverse()559 return result560Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 561why, one step back561 def values(self) -> t.Iterable[t.Any]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 562–564why, one step back562 """Return a list of all values."""563 return [x[1] for x in self.items()]564Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 565why, one step back565 def keys(self) -> t.Iterable[t.Any]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 566–568why, one step back566 """Return a list of all keys ordered by most recent usage."""567 return list(self)568Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 569why, one step back569 def __iter__(self) -> t.Iterator[t.Any]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 570–571why, one step back570 return reversed(tuple(self._queue))571Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 572why, one step back572 def __reversed__(self) -> t.Iterator[t.Any]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 573–581why, one step back573 """Iterate over the keys in the cache dict, oldest items574 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 back582 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 back586) -> t.Callable[[str | None], bool]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 587–623why, one step back587 """Intelligently sets the initial value of autoescaping based on the588 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)623drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 624why, one step back624 def autoescape(template_name: str | None) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 625–636why, one step back625 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 autoescape635636Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 637why, one step back637def htmlsafe_json_dumps(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 638why, one step back638 obj: t.Any, dumps: t.Callable[..., str] | None = None, **kwargs: t.AnyMerge pull request #1391 from pallets/markupsafe-importsDavid Lordbefore adoptiona9b06f4
line 639why, one step back639) -> markupsafe.Markup:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 640–667why, one step back640 """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.dumps667Merge pull request #1391 from pallets/markupsafe-importsDavid Lordbefore adoptiona9b06f4
line 668why, one step back668 return markupsafe.Markup(update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 669–702why, one step back669 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 """702Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 703why, one step back703 def __init__(self, *items: t.Any) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 704–708why, one step back704 if not items:705 raise RuntimeError("at least one item has to be provided")706 self.items = items707 self.pos = 0708Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 709why, one step back709 def reset(self) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 710–713why, one step back710 """Resets the current item to the first item."""711 self.pos = 0712713 @propertyMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 714why, one step back714 def current(self) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 715–719why, one step back715 """Return the current item. Equivalent to the item that will be716 returned next time :meth:`next` is called.717 """718 return self.items[self.pos]719Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 720why, one step back720 def next(self) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 721–733why, one step back721 """Return the current item, then advance :attr:`current` to the722 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."""733Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 734why, one step back734 def __init__(self, sep: str = ", ") -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 735–737why, one step back735 self.sep = sep736 self.used = False737Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 738why, one step back738 def __call__(self) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 739–748why, one step back739 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."""748Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 749why, one step back749 def __init__(*args: t.Any, **kwargs: t.Any) -> None: # noqa: B902update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 750–752why, one step back750 self, args = args[0], args[1:]751 self.__attrs = dict(*args, **kwargs)752Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 753why, one step back753 def __getattribute__(self, name: str) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 754–759why, one step back754 # __class__ is needed for the awaitable check in async mode755 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 back760 raise AttributeError(name) from Noneupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 761why, one step back761Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 762why, one step back762 def __setitem__(self, name: str, value: t.Any) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 763–764why, one step back763 self.__attrs[name] = value764Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 765why, one step back765 def __repr__(self) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 766why, one step back766 return f"<Namespace {self.__attrs!r}>"