utils.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. import enum
  2. import json
  3. import os
  4. import re
  5. import typing as t
  6. from collections import abc
  7. from collections import deque
  8. from random import choice
  9. from random import randrange
  10. from threading import Lock
  11. from types import CodeType
  12. from urllib.parse import quote_from_bytes
  13. import markupsafe
  14. if t.TYPE_CHECKING:
  15. import typing_extensions as te
  16. F = t.TypeVar("F", bound=t.Callable[..., t.Any])
  17. # special singleton representing missing values for the runtime
  18. missing: t.Any = type("MissingType", (), {"__repr__": lambda x: "missing"})()
  19. internal_code: t.MutableSet[CodeType] = set()
  20. concat = "".join
  21. def pass_context(f: F) -> F:
  22. """Pass the :class:`~jinja2.runtime.Context` as the first argument
  23. to the decorated function when called while rendering a template.
  24. Can be used on functions, filters, and tests.
  25. If only ``Context.eval_context`` is needed, use
  26. :func:`pass_eval_context`. If only ``Context.environment`` is
  27. needed, use :func:`pass_environment`.
  28. .. versionadded:: 3.0.0
  29. Replaces ``contextfunction`` and ``contextfilter``.
  30. """
  31. f.jinja_pass_arg = _PassArg.context # type: ignore
  32. return f
  33. def pass_eval_context(f: F) -> F:
  34. """Pass the :class:`~jinja2.nodes.EvalContext` as the first argument
  35. to the decorated function when called while rendering a template.
  36. See :ref:`eval-context`.
  37. Can be used on functions, filters, and tests.
  38. If only ``EvalContext.environment`` is needed, use
  39. :func:`pass_environment`.
  40. .. versionadded:: 3.0.0
  41. Replaces ``evalcontextfunction`` and ``evalcontextfilter``.
  42. """
  43. f.jinja_pass_arg = _PassArg.eval_context # type: ignore
  44. return f
  45. def pass_environment(f: F) -> F:
  46. """Pass the :class:`~jinja2.Environment` as the first argument to
  47. the decorated function when called while rendering a template.
  48. Can be used on functions, filters, and tests.
  49. .. versionadded:: 3.0.0
  50. Replaces ``environmentfunction`` and ``environmentfilter``.
  51. """
  52. f.jinja_pass_arg = _PassArg.environment # type: ignore
  53. return f
  54. class _PassArg(enum.Enum):
  55. context = enum.auto()
  56. eval_context = enum.auto()
  57. environment = enum.auto()
  58. @classmethod
  59. def from_obj(cls, obj: F) -> t.Optional["_PassArg"]:
  60. if hasattr(obj, "jinja_pass_arg"):
  61. return obj.jinja_pass_arg # type: ignore
  62. return None
  63. def internalcode(f: F) -> F:
  64. """Marks the function as internally used"""
  65. internal_code.add(f.__code__)
  66. return f
  67. def is_undefined(obj: t.Any) -> bool:
  68. """Check if the object passed is undefined. This does nothing more than
  69. performing an instance check against :class:`Undefined` but looks nicer.
  70. This can be used for custom filters or tests that want to react to
  71. undefined variables. For example a custom default filter can look like
  72. this::
  73. def default(var, default=''):
  74. if is_undefined(var):
  75. return default
  76. return var
  77. """
  78. from .runtime import Undefined
  79. return isinstance(obj, Undefined)
  80. def consume(iterable: t.Iterable[t.Any]) -> None:
  81. """Consumes an iterable without doing anything with it."""
  82. for _ in iterable:
  83. pass
  84. def clear_caches() -> None:
  85. """Jinja keeps internal caches for environments and lexers. These are
  86. used so that Jinja doesn't have to recreate environments and lexers all
  87. the time. Normally you don't have to care about that but if you are
  88. measuring memory consumption you may want to clean the caches.
  89. """
  90. from .environment import get_spontaneous_environment
  91. from .lexer import _lexer_cache
  92. get_spontaneous_environment.cache_clear()
  93. _lexer_cache.clear()
  94. def import_string(import_name: str, silent: bool = False) -> t.Any:
  95. """Imports an object based on a string. This is useful if you want to
  96. use import paths as endpoints or something similar. An import path can
  97. be specified either in dotted notation (``xml.sax.saxutils.escape``)
  98. or with a colon as object delimiter (``xml.sax.saxutils:escape``).
  99. If the `silent` is True the return value will be `None` if the import
  100. fails.
  101. :return: imported object
  102. """
  103. try:
  104. if ":" in import_name:
  105. module, obj = import_name.split(":", 1)
  106. elif "." in import_name:
  107. module, _, obj = import_name.rpartition(".")
  108. else:
  109. return __import__(import_name)
  110. return getattr(__import__(module, None, None, [obj]), obj)
  111. except (ImportError, AttributeError):
  112. if not silent:
  113. raise
  114. def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO[t.Any]]:
  115. """Returns a file descriptor for the filename if that file exists,
  116. otherwise ``None``.
  117. """
  118. if not os.path.isfile(filename):
  119. return None
  120. return open(filename, mode)
  121. def object_type_repr(obj: t.Any) -> str:
  122. """Returns the name of the object's type. For some recognized
  123. singletons the name of the object is returned instead. (For
  124. example for `None` and `Ellipsis`).
  125. """
  126. if obj is None:
  127. return "None"
  128. elif obj is Ellipsis:
  129. return "Ellipsis"
  130. cls = type(obj)
  131. if cls.__module__ == "builtins":
  132. return f"{cls.__name__} object"
  133. return f"{cls.__module__}.{cls.__name__} object"
  134. def pformat(obj: t.Any) -> str:
  135. """Format an object using :func:`pprint.pformat`."""
  136. from pprint import pformat
  137. return pformat(obj)
  138. _http_re = re.compile(
  139. r"""
  140. ^
  141. (
  142. (https?://|www\.) # scheme or www
  143. (([\w%-]+\.)+)? # subdomain
  144. (
  145. [a-z]{2,63} # basic tld
  146. |
  147. xn--[\w%]{2,59} # idna tld
  148. )
  149. |
  150. ([\w%-]{2,63}\.)+ # basic domain
  151. (com|net|int|edu|gov|org|info|mil) # basic tld
  152. |
  153. (https?://) # scheme
  154. (
  155. (([\d]{1,3})(\.[\d]{1,3}){3}) # IPv4
  156. |
  157. (\[([\da-f]{0,4}:){2}([\da-f]{0,4}:?){1,6}]) # IPv6
  158. )
  159. )
  160. (?::[\d]{1,5})? # port
  161. (?:[/?#]\S*)? # path, query, and fragment
  162. $
  163. """,
  164. re.IGNORECASE | re.VERBOSE,
  165. )
  166. _email_re = re.compile(r"^\S+@\w[\w.-]*\.\w+$")
  167. def urlize(
  168. text: str,
  169. trim_url_limit: t.Optional[int] = None,
  170. rel: t.Optional[str] = None,
  171. target: t.Optional[str] = None,
  172. extra_schemes: t.Optional[t.Iterable[str]] = None,
  173. ) -> str:
  174. """Convert URLs in text into clickable links.
  175. This may not recognize links in some situations. Usually, a more
  176. comprehensive formatter, such as a Markdown library, is a better
  177. choice.
  178. Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email
  179. addresses. Links with trailing punctuation (periods, commas, closing
  180. parentheses) and leading punctuation (opening parentheses) are
  181. recognized excluding the punctuation. Email addresses that include
  182. header fields are not recognized (for example,
  183. ``mailto:address@example.com?cc=copy@example.com``).
  184. :param text: Original text containing URLs to link.
  185. :param trim_url_limit: Shorten displayed URL values to this length.
  186. :param target: Add the ``target`` attribute to links.
  187. :param rel: Add the ``rel`` attribute to links.
  188. :param extra_schemes: Recognize URLs that start with these schemes
  189. in addition to the default behavior.
  190. .. versionchanged:: 3.0
  191. The ``extra_schemes`` parameter was added.
  192. .. versionchanged:: 3.0
  193. Generate ``https://`` links for URLs without a scheme.
  194. .. versionchanged:: 3.0
  195. The parsing rules were updated. Recognize email addresses with
  196. or without the ``mailto:`` scheme. Validate IP addresses. Ignore
  197. parentheses and brackets in more cases.
  198. """
  199. if trim_url_limit is not None:
  200. def trim_url(x: str) -> str:
  201. if len(x) > trim_url_limit:
  202. return f"{x[:trim_url_limit]}..."
  203. return x
  204. else:
  205. def trim_url(x: str) -> str:
  206. return x
  207. words = re.split(r"(\s+)", str(markupsafe.escape(text)))
  208. rel_attr = f' rel="{markupsafe.escape(rel)}"' if rel else ""
  209. target_attr = f' target="{markupsafe.escape(target)}"' if target else ""
  210. for i, word in enumerate(words):
  211. head, middle, tail = "", word, ""
  212. match = re.match(r"^([(<]|&lt;)+", middle)
  213. if match:
  214. head = match.group()
  215. middle = middle[match.end() :]
  216. # Unlike lead, which is anchored to the start of the string,
  217. # need to check that the string ends with any of the characters
  218. # before trying to match all of them, to avoid backtracking.
  219. if middle.endswith((")", ">", ".", ",", "\n", "&gt;")):
  220. match = re.search(r"([)>.,\n]|&gt;)+$", middle)
  221. if match:
  222. tail = match.group()
  223. middle = middle[: match.start()]
  224. # Prefer balancing parentheses in URLs instead of ignoring a
  225. # trailing character.
  226. for start_char, end_char in ("(", ")"), ("<", ">"), ("&lt;", "&gt;"):
  227. start_count = middle.count(start_char)
  228. if start_count <= middle.count(end_char):
  229. # Balanced, or lighter on the left
  230. continue
  231. # Move as many as possible from the tail to balance
  232. for _ in range(min(start_count, tail.count(end_char))):
  233. end_index = tail.index(end_char) + len(end_char)
  234. # Move anything in the tail before the end char too
  235. middle += tail[:end_index]
  236. tail = tail[end_index:]
  237. if _http_re.match(middle):
  238. if middle.startswith("https://") or middle.startswith("http://"):
  239. middle = (
  240. f'<a href="{middle}"{rel_attr}{target_attr}>{trim_url(middle)}</a>'
  241. )
  242. else:
  243. middle = (
  244. f'<a href="https://{middle}"{rel_attr}{target_attr}>'
  245. f"{trim_url(middle)}</a>"
  246. )
  247. elif middle.startswith("mailto:") and _email_re.match(middle[7:]):
  248. middle = f'<a href="{middle}">{middle[7:]}</a>'
  249. elif (
  250. "@" in middle
  251. and not middle.startswith("www.")
  252. and ":" not in middle
  253. and _email_re.match(middle)
  254. ):
  255. middle = f'<a href="mailto:{middle}">{middle}</a>'
  256. elif extra_schemes is not None:
  257. for scheme in extra_schemes:
  258. if middle != scheme and middle.startswith(scheme):
  259. middle = f'<a href="{middle}"{rel_attr}{target_attr}>{middle}</a>'
  260. words[i] = f"{head}{middle}{tail}"
  261. return "".join(words)
  262. def generate_lorem_ipsum(
  263. n: int = 5, html: bool = True, min: int = 20, max: int = 100
  264. ) -> str:
  265. """Generate some lorem ipsum for the template."""
  266. from .constants import LOREM_IPSUM_WORDS
  267. words = LOREM_IPSUM_WORDS.split()
  268. result = []
  269. for _ in range(n):
  270. next_capitalized = True
  271. last_comma = last_fullstop = 0
  272. word = None
  273. last = None
  274. p = []
  275. # each paragraph contains out of 20 to 100 words.
  276. for idx, _ in enumerate(range(randrange(min, max))):
  277. while True:
  278. word = choice(words)
  279. if word != last:
  280. last = word
  281. break
  282. if next_capitalized:
  283. word = word.capitalize()
  284. next_capitalized = False
  285. # add commas
  286. if idx - randrange(3, 8) > last_comma:
  287. last_comma = idx
  288. last_fullstop += 2
  289. word += ","
  290. # add end of sentences
  291. if idx - randrange(10, 20) > last_fullstop:
  292. last_comma = last_fullstop = idx
  293. word += "."
  294. next_capitalized = True
  295. p.append(word)
  296. # ensure that the paragraph ends with a dot.
  297. p_str = " ".join(p)
  298. if p_str.endswith(","):
  299. p_str = p_str[:-1] + "."
  300. elif not p_str.endswith("."):
  301. p_str += "."
  302. result.append(p_str)
  303. if not html:
  304. return "\n\n".join(result)
  305. return markupsafe.Markup(
  306. "\n".join(f"<p>{markupsafe.escape(x)}</p>" for x in result)
  307. )
  308. def url_quote(obj: t.Any, charset: str = "utf-8", for_qs: bool = False) -> str:
  309. """Quote a string for use in a URL using the given charset.
  310. :param obj: String or bytes to quote. Other types are converted to
  311. string then encoded to bytes using the given charset.
  312. :param charset: Encode text to bytes using this charset.
  313. :param for_qs: Quote "/" and use "+" for spaces.
  314. """
  315. if not isinstance(obj, bytes):
  316. if not isinstance(obj, str):
  317. obj = str(obj)
  318. obj = obj.encode(charset)
  319. safe = b"" if for_qs else b"/"
  320. rv = quote_from_bytes(obj, safe)
  321. if for_qs:
  322. rv = rv.replace("%20", "+")
  323. return rv
  324. @abc.MutableMapping.register
  325. class LRUCache:
  326. """A simple LRU Cache implementation."""
  327. # this is fast for small capacities (something below 1000) but doesn't
  328. # scale. But as long as it's only used as storage for templates this
  329. # won't do any harm.
  330. def __init__(self, capacity: int) -> None:
  331. self.capacity = capacity
  332. self._mapping: t.Dict[t.Any, t.Any] = {}
  333. self._queue: "te.Deque[t.Any]" = deque()
  334. self._postinit()
  335. def _postinit(self) -> None:
  336. # alias all queue methods for faster lookup
  337. self._popleft = self._queue.popleft
  338. self._pop = self._queue.pop
  339. self._remove = self._queue.remove
  340. self._wlock = Lock()
  341. self._append = self._queue.append
  342. def __getstate__(self) -> t.Mapping[str, t.Any]:
  343. return {
  344. "capacity": self.capacity,
  345. "_mapping": self._mapping,
  346. "_queue": self._queue,
  347. }
  348. def __setstate__(self, d: t.Mapping[str, t.Any]) -> None:
  349. self.__dict__.update(d)
  350. self._postinit()
  351. def __getnewargs__(self) -> t.Tuple[t.Any, ...]:
  352. return (self.capacity,)
  353. def copy(self) -> "LRUCache":
  354. """Return a shallow copy of the instance."""
  355. rv = self.__class__(self.capacity)
  356. rv._mapping.update(self._mapping)
  357. rv._queue.extend(self._queue)
  358. return rv
  359. def get(self, key: t.Any, default: t.Any = None) -> t.Any:
  360. """Return an item from the cache dict or `default`"""
  361. try:
  362. return self[key]
  363. except KeyError:
  364. return default
  365. def setdefault(self, key: t.Any, default: t.Any = None) -> t.Any:
  366. """Set `default` if the key is not in the cache otherwise
  367. leave unchanged. Return the value of this key.
  368. """
  369. try:
  370. return self[key]
  371. except KeyError:
  372. self[key] = default
  373. return default
  374. def clear(self) -> None:
  375. """Clear the cache."""
  376. with self._wlock:
  377. self._mapping.clear()
  378. self._queue.clear()
  379. def __contains__(self, key: t.Any) -> bool:
  380. """Check if a key exists in this cache."""
  381. return key in self._mapping
  382. def __len__(self) -> int:
  383. """Return the current size of the cache."""
  384. return len(self._mapping)
  385. def __repr__(self) -> str:
  386. return f"<{type(self).__name__} {self._mapping!r}>"
  387. def __getitem__(self, key: t.Any) -> t.Any:
  388. """Get an item from the cache. Moves the item up so that it has the
  389. highest priority then.
  390. Raise a `KeyError` if it does not exist.
  391. """
  392. with self._wlock:
  393. rv = self._mapping[key]
  394. if self._queue[-1] != key:
  395. try:
  396. self._remove(key)
  397. except ValueError:
  398. # if something removed the key from the container
  399. # when we read, ignore the ValueError that we would
  400. # get otherwise.
  401. pass
  402. self._append(key)
  403. return rv
  404. def __setitem__(self, key: t.Any, value: t.Any) -> None:
  405. """Sets the value for an item. Moves the item up so that it
  406. has the highest priority then.
  407. """
  408. with self._wlock:
  409. if key in self._mapping:
  410. self._remove(key)
  411. elif len(self._mapping) == self.capacity:
  412. del self._mapping[self._popleft()]
  413. self._append(key)
  414. self._mapping[key] = value
  415. def __delitem__(self, key: t.Any) -> None:
  416. """Remove an item from the cache dict.
  417. Raise a `KeyError` if it does not exist.
  418. """
  419. with self._wlock:
  420. del self._mapping[key]
  421. try:
  422. self._remove(key)
  423. except ValueError:
  424. pass
  425. def items(self) -> t.Iterable[t.Tuple[t.Any, t.Any]]:
  426. """Return a list of items."""
  427. result = [(key, self._mapping[key]) for key in list(self._queue)]
  428. result.reverse()
  429. return result
  430. def values(self) -> t.Iterable[t.Any]:
  431. """Return a list of all values."""
  432. return [x[1] for x in self.items()]
  433. def keys(self) -> t.Iterable[t.Any]:
  434. """Return a list of all keys ordered by most recent usage."""
  435. return list(self)
  436. def __iter__(self) -> t.Iterator[t.Any]:
  437. return reversed(tuple(self._queue))
  438. def __reversed__(self) -> t.Iterator[t.Any]:
  439. """Iterate over the keys in the cache dict, oldest items
  440. coming first.
  441. """
  442. return iter(tuple(self._queue))
  443. __copy__ = copy
  444. def select_autoescape(
  445. enabled_extensions: t.Collection[str] = ("html", "htm", "xml"),
  446. disabled_extensions: t.Collection[str] = (),
  447. default_for_string: bool = True,
  448. default: bool = False,
  449. ) -> t.Callable[[t.Optional[str]], bool]:
  450. """Intelligently sets the initial value of autoescaping based on the
  451. filename of the template. This is the recommended way to configure
  452. autoescaping if you do not want to write a custom function yourself.
  453. If you want to enable it for all templates created from strings or
  454. for all templates with `.html` and `.xml` extensions::
  455. from jinja2 import Environment, select_autoescape
  456. env = Environment(autoescape=select_autoescape(
  457. enabled_extensions=('html', 'xml'),
  458. default_for_string=True,
  459. ))
  460. Example configuration to turn it on at all times except if the template
  461. ends with `.txt`::
  462. from jinja2 import Environment, select_autoescape
  463. env = Environment(autoescape=select_autoescape(
  464. disabled_extensions=('txt',),
  465. default_for_string=True,
  466. default=True,
  467. ))
  468. The `enabled_extensions` is an iterable of all the extensions that
  469. autoescaping should be enabled for. Likewise `disabled_extensions` is
  470. a list of all templates it should be disabled for. If a template is
  471. loaded from a string then the default from `default_for_string` is used.
  472. If nothing matches then the initial value of autoescaping is set to the
  473. value of `default`.
  474. For security reasons this function operates case insensitive.
  475. .. versionadded:: 2.9
  476. """
  477. enabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in enabled_extensions)
  478. disabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in disabled_extensions)
  479. def autoescape(template_name: t.Optional[str]) -> bool:
  480. if template_name is None:
  481. return default_for_string
  482. template_name = template_name.lower()
  483. if template_name.endswith(enabled_patterns):
  484. return True
  485. if template_name.endswith(disabled_patterns):
  486. return False
  487. return default
  488. return autoescape
  489. def htmlsafe_json_dumps(
  490. obj: t.Any, dumps: t.Optional[t.Callable[..., str]] = None, **kwargs: t.Any
  491. ) -> markupsafe.Markup:
  492. """Serialize an object to a string of JSON with :func:`json.dumps`,
  493. then replace HTML-unsafe characters with Unicode escapes and mark
  494. the result safe with :class:`~markupsafe.Markup`.
  495. This is available in templates as the ``|tojson`` filter.
  496. The following characters are escaped: ``<``, ``>``, ``&``, ``'``.
  497. The returned string is safe to render in HTML documents and
  498. ``<script>`` tags. The exception is in HTML attributes that are
  499. double quoted; either use single quotes or the ``|forceescape``
  500. filter.
  501. :param obj: The object to serialize to JSON.
  502. :param dumps: The ``dumps`` function to use. Defaults to
  503. ``env.policies["json.dumps_function"]``, which defaults to
  504. :func:`json.dumps`.
  505. :param kwargs: Extra arguments to pass to ``dumps``. Merged onto
  506. ``env.policies["json.dumps_kwargs"]``.
  507. .. versionchanged:: 3.0
  508. The ``dumper`` parameter is renamed to ``dumps``.
  509. .. versionadded:: 2.9
  510. """
  511. if dumps is None:
  512. dumps = json.dumps
  513. return markupsafe.Markup(
  514. dumps(obj, **kwargs)
  515. .replace("<", "\\u003c")
  516. .replace(">", "\\u003e")
  517. .replace("&", "\\u0026")
  518. .replace("'", "\\u0027")
  519. )
  520. class Cycler:
  521. """Cycle through values by yield them one at a time, then restarting
  522. once the end is reached. Available as ``cycler`` in templates.
  523. Similar to ``loop.cycle``, but can be used outside loops or across
  524. multiple loops. For example, render a list of folders and files in a
  525. list, alternating giving them "odd" and "even" classes.
  526. .. code-block:: html+jinja
  527. {% set row_class = cycler("odd", "even") %}
  528. <ul class="browser">
  529. {% for folder in folders %}
  530. <li class="folder {{ row_class.next() }}">{{ folder }}
  531. {% endfor %}
  532. {% for file in files %}
  533. <li class="file {{ row_class.next() }}">{{ file }}
  534. {% endfor %}
  535. </ul>
  536. :param items: Each positional argument will be yielded in the order
  537. given for each cycle.
  538. .. versionadded:: 2.1
  539. """
  540. def __init__(self, *items: t.Any) -> None:
  541. if not items:
  542. raise RuntimeError("at least one item has to be provided")
  543. self.items = items
  544. self.pos = 0
  545. def reset(self) -> None:
  546. """Resets the current item to the first item."""
  547. self.pos = 0
  548. @property
  549. def current(self) -> t.Any:
  550. """Return the current item. Equivalent to the item that will be
  551. returned next time :meth:`next` is called.
  552. """
  553. return self.items[self.pos]
  554. def next(self) -> t.Any:
  555. """Return the current item, then advance :attr:`current` to the
  556. next item.
  557. """
  558. rv = self.current
  559. self.pos = (self.pos + 1) % len(self.items)
  560. return rv
  561. __next__ = next
  562. class Joiner:
  563. """A joining helper for templates."""
  564. def __init__(self, sep: str = ", ") -> None:
  565. self.sep = sep
  566. self.used = False
  567. def __call__(self) -> str:
  568. if not self.used:
  569. self.used = True
  570. return ""
  571. return self.sep
  572. class Namespace:
  573. """A namespace object that can hold arbitrary attributes. It may be
  574. initialized from a dictionary or with keyword arguments."""
  575. def __init__(*args: t.Any, **kwargs: t.Any) -> None: # noqa: B902
  576. self, args = args[0], args[1:]
  577. self.__attrs = dict(*args, **kwargs)
  578. def __getattribute__(self, name: str) -> t.Any:
  579. # __class__ is needed for the awaitable check in async mode
  580. if name in {"_Namespace__attrs", "__class__"}:
  581. return object.__getattribute__(self, name)
  582. try:
  583. return self.__attrs[name]
  584. except KeyError:
  585. raise AttributeError(name) from None
  586. def __setitem__(self, name: str, value: t.Any) -> None:
  587. self.__attrs[name] = value
  588. def __repr__(self) -> str:
  589. return f"<Namespace {self.__attrs!r}>"