utils.py 24 KB

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