add type annotations to filters and tests
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 43d4228 · Browse files · 6 files·+509 added−206 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+509 added−206 removed
- other:+509 added−206 removed
Provenance
- Commit
f0a9f31- Tree
8f8bfc7- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
43d4228
6 files changed+509 added−206 removed
modified:src/jinja2/asyncfilters.py+121 added-30 removed
1+import typing2+import typing as t3 from functools import wraps4+from itertools import groupby5 6 from . import filters7 from .asyncsupport import auto_aiter8 from .asyncsupport import auto_await9 10+if t.TYPE_CHECKING:11+ from .environment import Environment12+ from .nodes import EvalContext13+ from .runtime import Context14+ from .runtime import Undefined15 16+ V = t.TypeVar("V")17+18+8-async def auto_to_seq(value):19+async def auto_to_seq(20+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",21+) -> "t.List[V]":22 seq = []23+24 if hasattr(value, "__aiter__"):11- async for item in value:25+ async for item in t.cast(t.AsyncIterable, value):26 seq.append(item)27 else:14- for item in value:28+ for item in t.cast(t.Iterable, value):29 seq.append(item)30+31 return seq32 33 19-async def async_select_or_reject(args, kwargs, modfunc, lookup_attr):20- seq, func = filters.prepare_select_or_reject(args, kwargs, modfunc, lookup_attr)21- if seq:22- async for item in auto_aiter(seq):34+async def async_select_or_reject(35+ context: "Context",36+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",37+ args: t.Tuple,38+ kwargs: t.Dict[str, t.Any],39+ modfunc: t.Callable[[t.Any], t.Any],40+ lookup_attr: bool,41+) -> "t.AsyncIterator[V]":42+ if value:43+ func = filters.prepare_select_or_reject(44+ context, args, kwargs, modfunc, lookup_attr45+ )46+47+ async for item in auto_aiter(value):48 if func(item):49 yield item50 51 52 def dualfilter(normal_filter, async_filter):53 wrap_evalctx = False54+55 if getattr(normal_filter, "environmentfilter", False) is True:56 57 def is_async(args):58 return args[0].is_async9 unmodified lines68 69 @wraps(normal_filter)70 def wrapper(*args, **kwargs):71 b = is_async(args)72+73 if wrap_evalctx:74 args = args[1:]75+76 if b:77 return async_filter(*args, **kwargs)78+79 return normal_filter(*args, **kwargs)80 81 if wrap_evalctx:82 wrapper.evalcontextfilter = True83 84 wrapper.asyncfiltervariant = True56-85 return wrapper86 87 88 def asyncfiltervariant(original):3 unmodified lines92 return decorator93 94 95 @asyncfiltervariant(filters.do_first)68-async def do_first(environment, seq):96+async def do_first(97+ environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]"98+) -> "t.Union[V, Undefined]":99 try:70- return await auto_aiter(seq).__anext__()100+ return t.cast("V", await auto_aiter(seq).__anext__())101 except StopAsyncIteration:102 return environment.undefined("No first item, sequence was empty.")103 104 105 @asyncfiltervariant(filters.do_groupby)76-async def do_groupby(environment, value, attribute):106+async def do_groupby(107+ environment: "Environment",108+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",109+ attribute: t.Union[str, int],110+) -> "t.List[t.Tuple[t.Any, t.List[V]]]":111 expr = filters.make_attrgetter(environment, attribute)112 return [113 filters._GroupTuple(key, await auto_to_seq(values))80- for key, values in filters.groupby(81- sorted(await auto_to_seq(value), key=expr), expr82- )114+ for key, values in groupby(sorted(await auto_to_seq(value), key=expr), expr)115 ]116 117 118 @asyncfiltervariant(filters.do_join)87-async def do_join(eval_ctx, value, d="", attribute=None):119+async def do_join(120+ eval_ctx: "EvalContext",121+ value: t.Union[t.AsyncIterable, t.Iterable],122+ d: str = "",123+ attribute: t.Optional[t.Union[str, int]] = None,124+) -> str:125 return filters.do_join(eval_ctx, await auto_to_seq(value), d, attribute)126 127 128 @asyncfiltervariant(filters.do_list)92-async def do_list(value):129+async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":130 return await auto_to_seq(value)131 132 133 @asyncfiltervariant(filters.do_reject)97-async def do_reject(*args, **kwargs):98- return async_select_or_reject(args, kwargs, lambda x: not x, False)134+async def do_reject(135+ context: "Context",136+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",137+ *args: t.Any,138+ **kwargs: t.Any,139+) -> "t.AsyncIterator[V]":140+ return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)141 142 143 @asyncfiltervariant(filters.do_rejectattr)102-async def do_rejectattr(*args, **kwargs):103- return async_select_or_reject(args, kwargs, lambda x: not x, True)144+async def do_rejectattr(145+ context: "Context",146+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",147+ *args: t.Any,148+ **kwargs: t.Any,149+) -> "t.AsyncIterator[V]":150+ return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)151 152 153 @asyncfiltervariant(filters.do_select)107-async def do_select(*args, **kwargs):108- return async_select_or_reject(args, kwargs, lambda x: x, False)154+async def do_select(155+ context: "Context",156+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",157+ *args: t.Any,158+ **kwargs: t.Any,159+) -> "t.AsyncIterator[V]":160+ return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)161 162 163 @asyncfiltervariant(filters.do_selectattr)112-async def do_selectattr(*args, **kwargs):113- return async_select_or_reject(args, kwargs, lambda x: x, True)164+async def do_selectattr(165+ context: "Context",166+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",167+ *args: t.Any,168+ **kwargs: t.Any,169+) -> "t.AsyncIterator[V]":170+ return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)171 172 173+@typing.overload174+def do_map(175+ context: "Context",176+ value: t.Union[t.AsyncIterable, t.Iterable],177+ name: str,178+ *args: t.Any,179+ **kwargs: t.Any,180+) -> t.Iterable:181+ ...182+183+184+@typing.overload185+def do_map(186+ context: "Context",187+ value: t.Union[t.AsyncIterable, t.Iterable],188+ *,189+ attribute: str = ...,190+ default: t.Optional[t.Any] = None,191+) -> t.Iterable:192+ ...193+194+195 @asyncfiltervariant(filters.do_map)117-async def do_map(*args, **kwargs):118- seq, func = filters.prepare_map(args, kwargs)119- if seq:120- async for item in auto_aiter(seq):196+async def do_map(context, value, *args, **kwargs):197+ if value:198+ func = filters.prepare_map(context, args, kwargs)199+200+ async for item in auto_aiter(value):201 yield await auto_await(func(item))202 203 204 @asyncfiltervariant(filters.do_sum)125-async def do_sum(environment, iterable, attribute=None, start=0):205+async def do_sum(206+ environment: "Environment",207+ iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",208+ attribute: t.Optional[t.Union[str, int]] = None,209+ start: "V" = 0, # type: ignore210+) -> "V":211 rv = start212+213 if attribute is not None:214 func = filters.make_attrgetter(environment, attribute)215 else:216 1 unmodified line218 return x219 220 async for item in auto_aiter(iterable):221 rv += func(item)222+223 return rv224 225 226 @asyncfiltervariant(filters.do_slice)140-async def do_slice(value, slices, fill_with=None):227+async def do_slice(228+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",229+ slices: int,230+ fill_with: t.Optional[t.Any] = None,231+) -> "t.Iterator[t.List[V]]":232 return filters.do_slice(await auto_to_seq(value), slices, fill_with)233 234 235 ASYNC_FILTERS = {13 unmodified linesmodified:src/jinja2/environment.py+1 added-1 removed
317 unmodified lines318 self.newline_sequence = newline_sequence319 self.keep_trailing_newline = keep_trailing_newline320 321 # runtime information322- self.undefined = undefined322+ self.undefined: t.Type[Undefined] = undefined323 self.optimized = optimized324 self.finalize = finalize325 self.autoescape = autoescape326 1086 unmodified linesmodified:src/jinja2/filters.py+343 added-140 removed
1 """Built-in template filters used with the ``|`` operator."""2 import math3 import random4 import re5+import typing6+import typing as t7 from collections import abc6-from collections import namedtuple8 from itertools import chain9 from itertools import groupby10 11 from markupsafe import escape6 unmodified lines18 from .utils import pformat19 from .utils import url_quote20 from .utils import urlize21 21-_word_re = re.compile(r"\w+")22-_word_beginning_split_re = re.compile(r"([-\s({\[<]+)")22+if t.TYPE_CHECKING:23+ import typing_extensions as te24+ from .environment import Environment25+ from .nodes import EvalContext26+ from .runtime import Context27+ from .sandbox import SandboxedEnvironment # noqa: F40128 29+ K = t.TypeVar("K")30+ V = t.TypeVar("V")31+ F = t.TypeVar("F", bound=t.Callable[..., t.Any])32 33+ class HasHTML(te.Protocol):34+ def __html__(self) -> str:35+ pass36+37+25-def contextfilter(f):38+def contextfilter(f: "F") -> "F":39 """Decorator for marking context dependent filters. The current40 :class:`Context` will be passed as first argument.41 """29- f.contextfilter = True42+ f.contextfilter = True # type: ignore43 return f44 45 33-def evalcontextfilter(f):46+def evalcontextfilter(f: "F") -> "F":47 """Decorator for marking eval-context dependent filters. An eval48 context object is passed as first argument. For more information49 about the eval context, see :ref:`eval-context`.50 51 .. versionadded:: 2.452 """40- f.evalcontextfilter = True53+ f.evalcontextfilter = True # type: ignore54 return f55 56 44-def environmentfilter(f):57+def environmentfilter(f: "F") -> "F":58 """Decorator for marking environment dependent filters. The current59 :class:`Environment` is passed to the filter as first argument.60 """48- f.environmentfilter = True61+ f.environmentfilter = True # type: ignore62 return f63 64 52-def ignore_case(value):65+def ignore_case(value: "V") -> "V":66 """For use as a postprocessor for :func:`make_attrgetter`. Converts strings67 to lowercase and returns other types as-is."""55- return value.lower() if isinstance(value, str) else value68+ if isinstance(value, str):69+ return t.cast("V", value.lower())70 71+ return value72 58-def make_attrgetter(environment, attribute, postprocess=None, default=None):73+74+def make_attrgetter(75+ environment: "Environment",76+ attribute: t.Optional[t.Union[str, int]],77+ postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,78+ default: t.Optional[t.Any] = None,79+) -> t.Callable[[t.Any], t.Any]:80 """Returns a callable that looks up the given attribute from a81 passed object with the rules of the environment. Dots are allowed82 to access attributes of attributes. Integer parts in paths are83 looked up as integers.84 """64- attribute = _prepare_attribute_parts(attribute)85+ parts = _prepare_attribute_parts(attribute)86 66- def attrgetter(item):67- for part in attribute:87+ def attrgetter(item: t.Any) -> t.Any:88+ for part in parts:89 item = environment.getitem(item, part)90 91 if default is not None and isinstance(item, Undefined):92 item = default5 unmodified lines98 99 return attrgetter100 101 81-def make_multi_attrgetter(environment, attribute, postprocess=None):102+def make_multi_attrgetter(103+ environment: "Environment",104+ attribute: t.Optional[t.Union[str, int]],105+ postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,106+) -> t.Callable[[t.Any], t.List[t.Any]]:107 """Returns a callable that looks up the given comma separated108 attributes from a passed object with the rules of the environment.109 Dots are allowed to access attributes of each attribute. Integer110 parts in paths are looked up as integers.2 unmodified lines113 attribute values.114 115 Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.116 """92- attribute_parts = (93- attribute.split(",") if isinstance(attribute, str) else [attribute]94- )95- attribute = [96- _prepare_attribute_parts(attribute_part) for attribute_part in attribute_parts97- ]117+ if isinstance(attribute, str):118+ split: t.Sequence[t.Union[str, int, None]] = attribute.split(",")119+ else:120+ split = [attribute]121 99- def attrgetter(item):100- items = [None] * len(attribute)101- for i, attribute_part in enumerate(attribute):122+ parts = [_prepare_attribute_parts(item) for item in split]123+124+ def attrgetter(item: t.Any) -> t.List[t.Any]:125+ items = [None] * len(parts)126+127+ for i, attribute_part in enumerate(parts):128 item_i = item129+130 for part in attribute_part:131 item_i = environment.getitem(item_i, part)132 133 if postprocess is not None:134 item_i = postprocess(item_i)135 136 items[i] = item_i137+138 return items139 140 return attrgetter141 142 115-def _prepare_attribute_parts(attr):143+def _prepare_attribute_parts(144+ attr: t.Optional[t.Union[str, int]]145+) -> t.List[t.Union[str, int]]:146 if attr is None:147 return []148+118- elif isinstance(attr, str):149+ if isinstance(attr, str):150 return [int(x) if x.isdigit() else x for x in attr.split(".")]120- else:121- return [attr]151 152+ return [attr]153 124-def do_forceescape(value):154+155+def do_forceescape(value: "t.Union[str, HasHTML]") -> Markup:156 """Enforce HTML escaping. This will probably double escape variables."""157 if hasattr(value, "__html__"):127- value = value.__html__()158+ value = t.cast("HasHTML", value).__html__()159+160 return escape(str(value))161 162 131-def do_urlencode(value):163+def do_urlencode(164+ value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]]165+) -> str:166 """Quote data for use in a URL path or query using UTF-8.167 168 Basic wrapper around :func:`urllib.parse.quote` when given a169 string, or :func:`urllib.parse.urlencode` for a dict or iterable.11 unmodified lines181 if isinstance(value, str) or not isinstance(value, abc.Iterable):182 return url_quote(value)183 184 if isinstance(value, dict):151- items = value.items()185+ items: t.Iterable[t.Tuple[str, t.Any]] = value.items()186 else:153- items = iter(value)187+ items = value # type: ignore188 189 return "&".join(190 f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items191 )192 193 194 @evalcontextfilter161-def do_replace(eval_ctx, s, old, new, count=None):195+def do_replace(196+ eval_ctx: "EvalContext", s: str, old: str, new: str, count: t.Optional[int] = None197+) -> str:198 """Return a copy of the value with all occurrences of a substring199 replaced with a new one. The first argument is the substring200 that should be replaced, the second is the replacement string.201 If the optional third argument ``count`` is given, only the first8 unmodified lines210 -> d'oh, d'oh, aaargh211 """212 if count is None:213 count = -1214+215 if not eval_ctx.autoescape:216 return str(s).replace(str(old), str(new), count)217+218 if (219 hasattr(old, "__html__")220 or hasattr(new, "__html__")221 and not hasattr(s, "__html__")222 ):223 s = escape(s)224 else:225 s = soft_str(s)226+227 return s.replace(soft_str(old), soft_str(new), count)228 229 191-def do_upper(s):230+def do_upper(s: str) -> str:231 """Convert a value to uppercase."""232 return soft_str(s).upper()233 234 196-def do_lower(s):235+def do_lower(s: str) -> str:236 """Convert a value to lowercase."""237 return soft_str(s).lower()238 239 240 @evalcontextfilter202-def do_xmlattr(_eval_ctx, d, autospace=True):241+def do_xmlattr(242+ eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True243+) -> str:244 """Create an SGML/XML attribute string based on the items in a dict.245 All values that are neither `none` nor `undefined` are automatically246 escaped:247 19 unmodified lines267 f'{escape(key)}="{escape(value)}"'268 for key, value in d.items()269 if value is not None and not isinstance(value, Undefined)270 )271+272 if autospace and rv:273 rv = " " + rv274+232- if _eval_ctx.autoescape:275+ if eval_ctx.autoescape:276 rv = Markup(rv)277+278 return rv279 280 237-def do_capitalize(s):281+def do_capitalize(s: str) -> str:282 """Capitalize a value. The first character will be uppercase, all others283 lowercase.284 """285 return soft_str(s).capitalize()286 287 288+_word_beginning_split_re = re.compile(r"([-\s({\[<]+)")289+290+244-def do_title(s):291+def do_title(s: str) -> str:292 """Return a titlecased version of the value. I.e. words will start with293 uppercase letters, all remaining characters are lowercase.294 """295 return "".join(4 unmodified lines300 ]301 )302 303 257-def do_dictsort(value, case_sensitive=False, by="key", reverse=False):304+def do_dictsort(305+ value: "t.Mapping[K, V]",306+ case_sensitive: bool = False,307+ by: 'te.Literal["key", "value"]' = "key",308+ reverse: bool = False,309+) -> "t.List[t.Tuple[K, V]]":310 """Sort a dict and yield (key, value) pairs. Because python dicts are311 unsorted you may want to use this function to order them by either312 key or value:313 29 unmodified lines343 return sorted(value.items(), key=sort_func, reverse=reverse)344 345 346 @environmentfilter295-def do_sort(environment, value, reverse=False, case_sensitive=False, attribute=None):347+def do_sort(348+ environment: "Environment",349+ value: "t.Iterable[V]",350+ reverse: bool = False,351+ case_sensitive: bool = False,352+ attribute: t.Optional[t.Union[str, int]] = None,353+) -> "t.List[V]":354 """Sort an iterable using Python's :func:`sorted`.355 356 .. sourcecode:: jinja357 41 unmodified lines399 return sorted(value, key=key_func, reverse=reverse)400 401 402 @environmentfilter345-def do_unique(environment, value, case_sensitive=False, attribute=None):403+def do_unique(404+ environment: "Environment",405+ value: "t.Iterable[V]",406+ case_sensitive: bool = False,407+ attribute: t.Optional[t.Union[str, int]] = None,408+) -> "t.Iterator[V]":409 """Returns a list of unique items from the given iterable.410 411 .. sourcecode:: jinja412 18 unmodified lines431 seen.add(key)432 yield item433 434 372-def _min_or_max(environment, value, func, case_sensitive, attribute):435+def _min_or_max(436+ environment: "Environment",437+ value: "t.Iterable[V]",438+ func: "t.Callable[..., V]",439+ case_sensitive: bool,440+ attribute: t.Optional[t.Union[str, int]],441+) -> "t.Union[V, Undefined]":442 it = iter(value)443 444 try:445 first = next(it)6 unmodified lines452 return func(chain([first], it), key=key_func)453 454 455 @environmentfilter387-def do_min(environment, value, case_sensitive=False, attribute=None):456+def do_min(457+ environment: "Environment",458+ value: "t.Iterable[V]",459+ case_sensitive: bool = False,460+ attribute: t.Optional[t.Union[str, int]] = None,461+) -> "t.Union[V, Undefined]":462 """Return the smallest item from the sequence.463 464 .. sourcecode:: jinja465 6 unmodified lines472 return _min_or_max(environment, value, min, case_sensitive, attribute)473 474 475 @environmentfilter402-def do_max(environment, value, case_sensitive=False, attribute=None):476+def do_max(477+ environment: "Environment",478+ value: "t.Iterable[V]",479+ case_sensitive: bool = False,480+ attribute: t.Optional[t.Union[str, int]] = None,481+) -> "t.Union[V, Undefined]":482 """Return the largest item from the sequence.483 484 .. sourcecode:: jinja485 5 unmodified lines491 """492 return _min_or_max(environment, value, max, case_sensitive, attribute)493 494 416-def do_default(value, default_value="", boolean=False):495+def do_default(496+ value: "V",497+ default_value: "V" = "", # type: ignore498+ boolean: bool = False,499+) -> "V":500 """If the value is undefined it will return the passed default value,501 otherwise the value of the variable:502 503 .. sourcecode:: jinja16 unmodified lines520 in the chain without getting an :exc:`~jinja2.UndefinedError`.521 """522 if isinstance(value, Undefined) or (boolean and not value):523 return default_value524+525 return value526 527 528 @evalcontextfilter445-def do_join(eval_ctx, value, d="", attribute=None):529+def do_join(530+ eval_ctx: "EvalContext",531+ value: t.Iterable,532+ d: str = "",533+ attribute: t.Optional[t.Union[str, int]] = None,534+) -> str:535 """Return a string which is the concatenation of the strings in the536 sequence. The separator between elements is an empty string per537 default, you can define it with the optional parameter:538 25 unmodified lines564 # if any of the items has. If yes we do a coercion to Markup565 if not hasattr(d, "__html__"):566 value = list(value)567 do_escape = False568+569 for idx, item in enumerate(value):570 if hasattr(item, "__html__"):571 do_escape = True572 else:573 value[idx] = str(item)574+575 if do_escape:576 d = escape(d)577 else:578 d = str(d)579+580 return d.join(value)581 582 # no html involved, to normal joining583 return soft_str(d).join(map(soft_str, value))584 585 494-def do_center(value, width=80):586+def do_center(value: str, width: int = 80) -> str:587 """Centers the value in a field of a given width."""496- return str(value).center(width)588+ return soft_str(value).center(width)589 590 591 @environmentfilter500-def do_first(environment, seq):592+def do_first(593+ environment: "Environment", seq: "t.Iterable[V]"594+) -> "t.Union[V, Undefined]":595 """Return the first item of a sequence."""596 try:597 return next(iter(seq))598 except StopIteration:599 return environment.undefined("No first item, sequence was empty.")600 601 602 @environmentfilter509-def do_last(environment, seq):510- """511- Return the last item of a sequence.603+def do_last(604+ environment: "Environment", seq: "t.Reversible[V]"605+) -> "t.Union[V, Undefined]":606+ """Return the last item of a sequence.607 608 Note: Does not work with generators. You may want to explicitly609 convert it to a list:610 7 unmodified lines618 return environment.undefined("No last item, sequence was empty.")619 620 621 @contextfilter527-def do_random(context, seq):622+def do_random(context: "Context", seq: "t.Sequence[V]") -> "t.Union[V, Undefined]":623 """Return a random item from the sequence."""624 try:625 return random.choice(seq)626 except IndexError:627 return context.environment.undefined("No random item, sequence was empty.")628 629 535-def do_filesizeformat(value, binary=False):630+def do_filesizeformat(value: t.Union[str, float, int], binary: bool = False) -> str:631 """Format the value like a 'human-readable' file size (i.e. 13 kB,632 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,633 Giga, etc.), if the second parameter is set to `True` the binary634 prefixes are used (Mebi, Gibi).9 unmodified lines644 ("EiB" if binary else "EB"),645 ("ZiB" if binary else "ZB"),646 ("YiB" if binary else "YB"),647 ]648+649 if bytes == 1:650 return "1 Byte"651 elif bytes < base:652 return f"{int(bytes)} Bytes"653 else:654 for i, prefix in enumerate(prefixes):655 unit = base ** (i + 2)656+657 if bytes < unit:658 return f"{base * bytes / unit:.1f} {prefix}"659+660 return f"{base * bytes / unit:.1f} {prefix}"661 662 565-def do_pprint(value):663+def do_pprint(value: t.Any) -> str:664 """Pretty print a variable. Useful for debugging."""567- return pformat(value)665+ return t.cast(str, pformat(value))666 667 668 _uri_scheme_re = re.compile(r"^([\w.+-]{2,}:(/){0,2})$")669 670 671 @evalcontextfilter672 def do_urlize(575- eval_ctx,576- value,577- trim_url_limit=None,578- nofollow=False,579- target=None,580- rel=None,581- extra_schemes=None,582-):673+ eval_ctx: "EvalContext",674+ value: str,675+ trim_url_limit: t.Optional[int] = None,676+ nofollow: bool = False,677+ target: t.Optional[str] = None,678+ rel: t.Optional[str] = None,679+ extra_schemes: t.Optional[t.Iterable[str]] = None,680+) -> str:681 """Convert URLs in text into clickable links.682 683 This may not recognize links in some situations. Usually, a more684 comprehensive formatter, such as a Markdown library, is a better62 unmodified lines747 748 return rv749 750 653-def do_indent(s, width=4, first=False, blank=False):751+def do_indent(s: str, width: int = 4, first: bool = False, blank: bool = False) -> str:752 """Return a copy of the string with each line indented by 4 spaces. The753 first line and blank lines are not indented by default.754 755 :param width: Number of spaces to indent by.31 unmodified lines787 return rv788 789 790 @environmentfilter693-def do_truncate(env, s, length=255, killwords=False, end="...", leeway=None):791+def do_truncate(792+ env: "Environment",793+ s: str,794+ length: int = 255,795+ killwords: bool = False,796+ end: str = "...",797+ leeway: t.Optional[int] = None,798+) -> str:799 """Return a truncated copy of the string. The length is specified800 with the first parameter which defaults to ``255``. If the second801 parameter is ``true`` the filter will cut the text at length. Otherwise802 it will discard the last word. If the text was in fact17 unmodified lines820 can be reconfigured globally.821 """822 if leeway is None:823 leeway = env.policies["truncate.leeway"]824+825 assert length >= len(end), f"expected length >= {len(end)}, got {length}"826 assert leeway >= 0, f"expected leeway >= 0, got {leeway}"827+828 if len(s) <= length + leeway:829 return s830+831 if killwords:832 return s[: length - len(end)] + end833+834 result = s[: length - len(end)].rsplit(" ", 1)[0]835 return result + end836 837 838 @environmentfilter839 def do_wordwrap(731- environment,732- s,733- width=79,734- break_long_words=True,735- wrapstring=None,736- break_on_hyphens=True,737-):840+ environment: "Environment",841+ s: str,842+ width: int = 79,843+ break_long_words: bool = True,844+ wrapstring: t.Optional[str] = None,845+ break_on_hyphens: bool = True,846+) -> str:847 """Wrap a string to the given width. Existing newlines are treated848 as paragraphs to be wrapped separately.849 850 :param s: Original text to wrap.13 unmodified lines864 865 .. versionchanged:: 2.7866 Added the ``wrapstring`` parameter.867 """759-868 import textwrap869 762- if not wrapstring:870+ if wrapstring is None:871 wrapstring = environment.newline_sequence872 873 # textwrap.wrap doesn't consider existing newlines when wrapping.874 # If the string has a newline before width, wrap will still insert15 unmodified lines890 ]891 )892 893 894+_word_re = re.compile(r"\w+")895+896+786-def do_wordcount(s):897+def do_wordcount(s: str) -> int:898 """Count the words in that string."""899 return len(_word_re.findall(soft_str(s)))900 901 791-def do_int(value, default=0, base=10):902+def do_int(value: t.Any, default: int = 0, base: int = 10) -> int:903 """Convert the value into an integer. If the904 conversion doesn't work it will return ``0``. You can905 override this default using the first parameter. You906 can also override the default base (10) in the second3 unmodified lines910 """911 try:912 if isinstance(value, str):913 return int(value, base)914+915 return int(value)916 except (TypeError, ValueError):917 # this quirk is necessary so that "42.23"|int gives 42.918 try:1 unmodified line920 except (TypeError, ValueError):921 return default922 923 812-def do_float(value, default=0.0):924+def do_float(value: t.Any, default: float = 0.0) -> float:925 """Convert the value into a floating point number. If the926 conversion doesn't work it will return ``0.0``. You can927 override this default using the first parameter.928 """2 unmodified lines931 except (TypeError, ValueError):932 return default933 934 823-def do_format(value, *args, **kwargs):935+def do_format(value: str, *args: t.Any, **kwargs: t.Any) -> str:936 """Apply the given values to a `printf-style`_ format string, like937 ``string % values``.938 939 .. sourcecode:: jinja15 unmodified lines955 if args and kwargs:956 raise FilterArgumentError(957 "can't handle positional and keyword arguments at the same time"958 )959+960 return soft_str(value) % (kwargs or args)961 962 850-def do_trim(value, chars=None):963+def do_trim(value: str, chars: t.Optional[str] = None) -> str:964 """Strip leading and trailing characters, by default whitespace."""965 return soft_str(value).strip(chars)966 967 855-def do_striptags(value):968+def do_striptags(value: "t.Union[str, HasHTML]") -> str:969 """Strip SGML/XML tags and replace adjacent whitespace by one space."""970 if hasattr(value, "__html__"):858- value = value.__html__()971+ value = t.cast("HasHTML", value).__html__()972+973 return Markup(str(value)).striptags()974 975 862-def do_slice(value, slices, fill_with=None):976+def do_slice(977+ value: "t.Collection[V]", slices: int, fill_with: "t.Optional[V]" = None978+) -> "t.Iterator[t.List[V]]":979 """Slice an iterator and return a list of lists containing980 those items. Useful if you want to create a div containing981 three ul tags that represent columns:982 16 unmodified lines999 length = len(seq)1000 items_per_slice = length // slices1001 slices_with_extra = length % slices1002 offset = 01003+1004 for slice_number in range(slices):1005 start = offset + slice_number * items_per_slice1006+1007 if slice_number < slices_with_extra:1008 offset += 11009+1010 end = offset + (slice_number + 1) * items_per_slice1011 tmp = seq[start:end]1012+1013 if fill_with is not None and slice_number >= slices_with_extra:1014 tmp.append(fill_with)1015+1016 yield tmp1017 1018 898-def do_batch(value, linecount, fill_with=None):1019+def do_batch(1020+ value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None1021+) -> "t.Iterator[t.List[V]]":1022 """1023 A filter that batches items. It works pretty much like `slice`1024 just the other way round. It returns a list of lists with the1025 given number of items. If you provide a second parameter this10 unmodified lines1036 </tr>1037 {%- endfor %}1038 </table>1039 """917- tmp = []1040+ tmp: "t.List[V]" = []1041+1042 for item in value:1043 if len(tmp) == linecount:1044 yield tmp1045 tmp = []1046+1047 tmp.append(item)1048+1049 if tmp:1050 if fill_with is not None and len(tmp) < linecount:1051 tmp += [fill_with] * (linecount - len(tmp))1052+1053 yield tmp1054 1055 929-def do_round(value, precision=0, method="common"):1056+def do_round(1057+ value: float,1058+ precision: int = 0,1059+ method: 'te.Literal["common", "ceil", "floor"]' = "common",1060+) -> float:1061 """Round the number to a given precision. The first1062 parameter specifies the precision (default is ``0``), the1063 second the rounding method:1064 19 unmodified lines1084 -> 431085 """1086 if method not in {"common", "ceil", "floor"}:1087 raise FilterArgumentError("method must be common, ceil or floor")1088+1089 if method == "common":1090 return round(value, precision)1091+1092 func = getattr(math, method)960- return func(value * (10 ** precision)) / (10 ** precision)1093+ return t.cast(float, func(value * (10 ** precision)) / (10 ** precision))1094 1095 963-# Use a regular tuple repr here. This is what we did in the past and we964-# really want to hide this custom type as much as possible. In particular965-# we do not want to accidentally expose an auto generated repr in case966-# people start to print this out in comments or something similar for967-# debugging.968-_GroupTuple = namedtuple("_GroupTuple", ["grouper", "list"])969-_GroupTuple.__repr__ = tuple.__repr__ # type: ignore970-_GroupTuple.__str__ = tuple.__str__ # type: ignore1096+class _GroupTuple(t.NamedTuple):1097+ grouper: t.Any1098+ list: t.List1099 1100+ # Use the regular tuple repr to hide this subclass if users print1101+ # out the value during debugging.1102+ def __repr__(self):1103+ return tuple.__repr__(self)1104 1105+ def __str__(self):1106+ return tuple.__str__(self)1107+1108+1109 @environmentfilter974-def do_groupby(environment, value, attribute):1110+def do_groupby(1111+ environment: "Environment", value: "t.Iterable[V]", attribute: t.Union[str, int]1112+) -> "t.List[t.Tuple[t.Any, t.List[V]]]":1113 """Group a sequence of objects by an attribute using Python's1114 :func:`itertools.groupby`. The attribute can use dot notation for1115 nested access, like ``"address.city"``. Unlike Python's ``groupby``,1116 the values are sorted first so only one group is returned for each33 unmodified lines1150 ]1151 1152 1153 @environmentfilter1016-def do_sum(environment, iterable, attribute=None, start=0):1154+def do_sum(1155+ environment: "Environment",1156+ iterable: "t.Iterable[V]",1157+ attribute: t.Optional[t.Union[str, int]] = None,1158+ start: "V" = 0, # type: ignore1159+) -> "V":1160 """Returns the sum of a sequence of numbers plus the value of parameter1161 'start' (which defaults to 0). When the sequence is empty it returns1162 start.1163 8 unmodified lines1172 attributes. Also the `start` parameter was moved on to the right.1173 """1174 if attribute is not None:1175 iterable = map(make_attrgetter(environment, attribute), iterable)1176+1177 return sum(iterable, start)1178 1179 1036-def do_list(value):1180+def do_list(value: "t.Iterable[V]") -> "t.List[V]":1181 """Convert the value into a list. If it was a string the returned list1182 will be a list of characters.1183 """1184 return list(value)1185 1186 1043-def do_mark_safe(value):1187+def do_mark_safe(value: str) -> Markup:1188 """Mark the value as safe which means that in an environment with automatic1189 escaping enabled this variable will not be escaped.1190 """1191 return Markup(value)1192 1193 1050-def do_mark_unsafe(value):1194+def do_mark_unsafe(value: str) -> str:1195 """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""1196 return str(value)1197 1198 1199+@typing.overload1200+def do_reverse(value: str) -> str:1201+ ...1202+1203+1204+@typing.overload1205+def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]":1206+ ...1207+1208+1209 def do_reverse(value):1210 """Reverse the object or return an iterator that iterates over it the other1211 way round.1212 """1213 if isinstance(value, str):1214 return value[::-1]1215+1216 try:1217 return reversed(value)1218 except TypeError:1219 try:4 unmodified lines1224 raise FilterArgumentError("argument must be iterable")1225 1226 1227 @environmentfilter1073-def do_attr(environment, obj, name):1228+def do_attr(1229+ environment: "Environment", obj: t.Any, name: str1230+) -> t.Union[Undefined, t.Any]:1231 """Get an attribute of an object. ``foo|attr("bar")`` works like1232 ``foo.bar`` just that always an attribute is returned and items are not1233 looked up.1234 8 unmodified lines1243 value = getattr(obj, name)1244 except AttributeError:1245 pass1246 else:1090- if environment.sandboxed and not environment.is_safe_attribute(1091- obj, name, value1092- ):1093- return environment.unsafe_undefined(obj, name)1247+ if environment.sandboxed:1248+ environment = t.cast("SandboxedEnvironment", environment)1249+1250+ if not environment.is_safe_attribute(obj, name, value):1251+ return environment.unsafe_undefined(obj, name)1252+1253 return value1254+1255 return environment.undefined(obj=obj, name=name)1256 1257 1258+@typing.overload1259+def do_map(1260+ context: "Context", value: t.Iterable, name: str, *args: t.Any, **kwargs: t.Any1261+) -> t.Iterable:1262+ ...1263+1264+1265+@typing.overload1266+def do_map(1267+ context: "Context",1268+ value: t.Iterable,1269+ *,1270+ attribute: str = ...,1271+ default: t.Optional[t.Any] = None,1272+) -> t.Iterable:1273+ ...1274+1275+1276 @contextfilter1099-def do_map(*args, **kwargs):1277+def do_map(context, value, *args, **kwargs):1278 """Applies a filter on a sequence of objects or looks up an attribute.1279 This is useful when dealing with lists of objects but you are really1280 only interested in a certain value of it.1281 31 unmodified lines1313 Added the ``default`` parameter.1314 1315 .. versionadded:: 2.71316 """1139- seq, func = prepare_map(args, kwargs)1140- if seq:1141- for item in seq:1317+ if value:1318+ func = prepare_map(context, args, kwargs)1319+1320+ for item in value:1321 yield func(item)1322 1323 1324 @contextfilter1146-def do_select(*args, **kwargs):1325+def do_select(1326+ context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1327+) -> "t.Iterator[V]":1328 """Filters a sequence of objects by applying a test to each object,1329 and only selecting the objects with the test succeeding.1330 1331 If no test is specified, each object will be evaluated as a boolean.16 unmodified lines1348 (n for n in numbers if test_divisibleby(n, 3))1349 1350 .. versionadded:: 2.71351 """1171- return select_or_reject(args, kwargs, lambda x: x, False)1352+ return select_or_reject(context, value, args, kwargs, lambda x: x, False)1353 1354 1355 @contextfilter1175-def do_reject(*args, **kwargs):1356+def do_reject(1357+ context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1358+) -> "t.Iterator[V]":1359 """Filters a sequence of objects by applying a test to each object,1360 and rejecting the objects with the test succeeding.1361 1362 If no test is specified, each object will be evaluated as a boolean.11 unmodified lines1374 (n for n in numbers if not test_odd(n))1375 1376 .. versionadded:: 2.71377 """1195- return select_or_reject(args, kwargs, lambda x: not x, False)1378+ return select_or_reject(context, value, args, kwargs, lambda x: not x, False)1379 1380 1381 @contextfilter1199-def do_selectattr(*args, **kwargs):1382+def do_selectattr(1383+ context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1384+) -> "t.Iterator[V]":1385 """Filters a sequence of objects by applying a test to the specified1386 attribute of each object, and only selecting the objects with the1387 test succeeding.1388 15 unmodified lines1404 (u for user in users if test_none(user.email))1405 1406 .. versionadded:: 2.71407 """1223- return select_or_reject(args, kwargs, lambda x: x, True)1408+ return select_or_reject(context, value, args, kwargs, lambda x: x, True)1409 1410 1411 @contextfilter1227-def do_rejectattr(*args, **kwargs):1412+def do_rejectattr(1413+ context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1414+) -> "t.Iterator[V]":1415 """Filters a sequence of objects by applying a test to the specified1416 attribute of each object, and rejecting the objects with the test1417 succeeding.1418 13 unmodified lines1432 (u for user in users if not test_none(user.email))1433 1434 .. versionadded:: 2.71435 """1249- return select_or_reject(args, kwargs, lambda x: not x, True)1436+ return select_or_reject(context, value, args, kwargs, lambda x: not x, True)1437 1438 1439 @evalcontextfilter1253-def do_tojson(eval_ctx, value, indent=None):1440+def do_tojson(1441+ eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None1442+) -> Markup:1443 """Serialize an object to a string of JSON, and mark it safe to1444 render in HTML. This filter is only for use in HTML documents.1445 1446 The returned string is safe to render in HTML documents and17 unmodified lines1464 1465 return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)1466 1467 1279-def prepare_map(args, kwargs):1280- context = args[0]1281- seq = args[1]1282-1283- if len(args) == 2 and "attribute" in kwargs:1468+def prepare_map(1469+ context: "Context", args: t.Tuple, kwargs: t.Dict[str, t.Any]1470+) -> t.Callable[[t.Any], t.Any]:1471+ if not args and "attribute" in kwargs:1472 attribute = kwargs.pop("attribute")1473 default = kwargs.pop("default", None)1474+1475 if kwargs:1476 raise FilterArgumentError(1477 f"Unexpected keyword argument {next(iter(kwargs))!r}"1478 )1479+1480 func = make_attrgetter(context.environment, attribute, default=default)1481 else:1482 try:1293- name = args[2]1294- args = args[3:]1483+ name = args[0]1484+ args = args[1:]1485 except LookupError:1486 raise FilterArgumentError("map requires a filter argument")1487 1488 def func(item):1489 return context.environment.call_filter(1490 name, item, args, kwargs, context=context1491 )1492 1303- return seq, func1493+ return func1494 1495 1306-def prepare_select_or_reject(args, kwargs, modfunc, lookup_attr):1307- context = args[0]1308- seq = args[1]1496+def prepare_select_or_reject(1497+ context: "Context",1498+ args: t.Tuple,1499+ kwargs: t.Dict[str, t.Any],1500+ modfunc: t.Callable[[t.Any], t.Any],1501+ lookup_attr: bool,1502+) -> t.Callable[[t.Any], t.Any]:1503 if lookup_attr:1504 try:1311- attr = args[2]1505+ attr = args[0]1506 except LookupError:1507 raise FilterArgumentError("Missing parameter for attribute name")1508+1509 transfunc = make_attrgetter(context.environment, attr)1510 off = 11511 else:1512 off = 01 unmodified line1514 def transfunc(x):1515 return x1516 1517 try:1323- name = args[2 + off]1324- args = args[3 + off :]1518+ name = args[off]1519+ args = args[1 + off :]1520 1521 def func(item):1522 return context.environment.call_test(name, item, args, kwargs)1523 1524 except LookupError:1525 func = bool1526 1332- return seq, lambda item: modfunc(func(transfunc(item)))1527+ return lambda item: modfunc(func(transfunc(item)))1528 1529 1335-def select_or_reject(args, kwargs, modfunc, lookup_attr):1336- seq, func = prepare_select_or_reject(args, kwargs, modfunc, lookup_attr)1337- if seq:1338- for item in seq:1530+def select_or_reject(1531+ context: "Context",1532+ value: "t.Iterable[V]",1533+ args: t.Tuple,1534+ kwargs: t.Dict[str, t.Any],1535+ modfunc: t.Callable[[t.Any], t.Any],1536+ lookup_attr: bool,1537+) -> "t.Iterator[V]":1538+ if value:1539+ func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)1540+1541+ for item in value:1542 if func(item):1543 yield item1544 1545 55 unmodified linesmodified:src/jinja2/runtime.py+4 added-1 removed
18 unmodified lines19 from .utils import missing20 from .utils import Namespace # noqa: F40121 from .utils import object_type_repr22 23+if t.TYPE_CHECKING:24+ from .environment import Environment25+26 # these variables are exported to the template runtime27 exported = [28 "LoopContext",29 "TemplateReference",158 unmodified lines188 189 def __init__(self, environment, parent, name, blocks, globals=None):190 self.parent = parent191 self.vars = {}189- self.environment = environment192+ self.environment: "Environment" = environment193 self.eval_ctx = EvalContext(self.environment, name)194 self.exported_vars = set()195 self.name = name196 self.globals_keys = set() if globals is None else set(globals)737 unmodified linesmodified:src/jinja2/tests.py+29 added-28 removed
1 """Built-in template tests used with the ``is`` operator."""2 import operator3-import re3+import typing as t4 from collections import abc5 from numbers import Number6 7 from .runtime import Undefined8 from .utils import environmentfunction9 10-number_re = re.compile(r"^-?\d+(\.\d+)?$")11-regex_type = type(number_re)12-test_callable = callable10+if t.TYPE_CHECKING:11+ from .environment import Environment12 13 15-def test_odd(value):14+def test_odd(value: int) -> bool:15 """Return true if the variable is odd."""16 return value % 2 == 117 18 20-def test_even(value):19+def test_even(value: int) -> bool:20 """Return true if the variable is even."""21 return value % 2 == 022 23 25-def test_divisibleby(value, num):24+def test_divisibleby(value: int, num: int) -> bool:25 """Check if a variable is divisible by a number."""26 return value % num == 027 28 30-def test_defined(value):29+def test_defined(value: t.Any) -> bool:30 """Return true if the variable is defined:31 32 .. sourcecode:: jinja33 8 unmodified lines42 """43 return not isinstance(value, Undefined)44 45 47-def test_undefined(value):46+def test_undefined(value: t.Any) -> bool:47 """Like :func:`defined` but the other way round."""48 return isinstance(value, Undefined)49 50 51 @environmentfunction53-def test_filter(env, value):52+def test_filter(env: "Environment", value: str) -> bool:53 """Check if a filter exists by name. Useful if a filter may be54 optionally available.55 56 .. code-block:: jinja9 unmodified lines66 return value in env.filters67 68 69 @environmentfunction71-def test_test(env, value):70+def test_test(env: "Environment", value: str) -> bool:71 """Check if a test exists by name. Useful if a test may be72 optionally available.73 74 .. code-block:: jinja12 unmodified lines87 """88 return value in env.tests89 90 92-def test_none(value):91+def test_none(value: t.Any) -> bool:92 """Return true if the variable is none."""93 return value is None94 95 97-def test_boolean(value):96+def test_boolean(value: t.Any) -> bool:97 """Return true if the object is a boolean value.98 99 .. versionadded:: 2.11100 """101 return value is True or value is False102 103 105-def test_false(value):104+def test_false(value: t.Any) -> bool:105 """Return true if the object is False.106 107 .. versionadded:: 2.11108 """109 return value is False110 111 113-def test_true(value):112+def test_true(value: t.Any) -> bool:113 """Return true if the object is True.114 115 .. versionadded:: 2.11116 """117 return value is True118 119 120 # NOTE: The existing 'number' test matches booleans and floats122-def test_integer(value):121+def test_integer(value: t.Any) -> bool:122 """Return true if the object is an integer.123 124 .. versionadded:: 2.11125 """126 return isinstance(value, int) and value is not True and value is not False127 128 129 # NOTE: The existing 'number' test matches booleans and integers131-def test_float(value):130+def test_float(value: t.Any) -> bool:131 """Return true if the object is a float.132 133 .. versionadded:: 2.11134 """135 return isinstance(value, float)136 137 139-def test_lower(value):138+def test_lower(value: str) -> bool:139 """Return true if the variable is lowercased."""140 return str(value).islower()141 142 144-def test_upper(value):143+def test_upper(value: str) -> bool:144 """Return true if the variable is uppercased."""145 return str(value).isupper()146 147 149-def test_string(value):148+def test_string(value: t.Any) -> bool:149 """Return true if the object is a string."""150 return isinstance(value, str)151 152 154-def test_mapping(value):153+def test_mapping(value: t.Any) -> bool:154 """Return true if the object is a mapping (dict etc.).155 156 .. versionadded:: 2.6157 """158 return isinstance(value, abc.Mapping)159 160 162-def test_number(value):161+def test_number(value: t.Any) -> bool:162 """Return true if the variable is a number."""163 return isinstance(value, Number)164 165 167-def test_sequence(value):166+def test_sequence(value: t.Any) -> bool:167 """Return true if the variable is a sequence. Sequences are variables168 that are iterable.169 """170 try:171 len(value)172 value.__getitem__173 except Exception:174 return False175+176 return True177 178 179-def test_sameas(value, other):179+def test_sameas(value: t.Any, other: t.Any) -> bool:180 """Check if an object points to the same memory address than another181 object:182 183 .. sourcecode:: jinja4 unmodified lines188 """189 return value is other190 191 192-def test_iterable(value):192+def test_iterable(value: t.Any) -> bool:193 """Check if it's possible to iterate over an object."""194 try:195 iter(value)196 except TypeError:197 return False198+199 return True200 201 201-def test_escaped(value):202+def test_escaped(value: t.Any) -> bool:203 """Check if the value is escaped."""204 return hasattr(value, "__html__")205 206 206-def test_in(value, seq):207+def test_in(value: t.Any, seq: t.Container) -> bool:208 """Check if value is in seq.209 210 .. versionadded:: 2.10211 """20 unmodified lines232 "mapping": test_mapping,233 "number": test_number,234 "sequence": test_sequence,235 "iterable": test_iterable,235- "callable": test_callable,236+ "callable": callable,237 "sameas": test_sameas,238 "escaped": test_escaped,239 "in": test_in,240 "==": operator.eq,15 unmodified linesmodified:src/jinja2/utils.py+11 added-6 removed
193 unmodified lines194 )195 _email_re = re.compile(r"^\S+@\w[\w.-]*\.\w+$")196 197 198-def urlize(text, trim_url_limit=None, rel=None, target=None, extra_schemes=None):198+def urlize(199+ text: str,200+ trim_url_limit: t.Optional[int] = None,201+ rel: t.Optional[str] = None,202+ target: t.Optional[str] = None,203+ extra_schemes: t.Optional[t.Iterable[str]] = None,204+) -> str:205 """Convert URLs in text into clickable links.206 207 This may not recognize links in some situations. Usually, a more208 comprehensive formatter, such as a Markdown library, is a better155 unmodified lines364 return "\n\n".join(result)365 return Markup("\n".join(f"<p>{escape(x)}</p>" for x in result))366 367 362-def url_quote(obj, charset="utf-8", for_qs=False):368+def url_quote(obj: t.Any, charset: str = "utf-8", for_qs: bool = False) -> str:369 """Quote a string for use in a URL using the given charset.370 365- This function is misnamed, it is a wrapper around366- :func:`urllib.parse.quote`.367-371 :param obj: String or bytes to quote. Other types are converted to372 string then encoded to bytes using the given charset.373 :param charset: Encode text to bytes using this charset.374 :param for_qs: Quote "/" and use "+" for spaces.237 unmodified lines612 613 return autoescape614 615 613-def htmlsafe_json_dumps(obj, dumps=None, **kwargs):616+def htmlsafe_json_dumps(617+ obj: t.Any, dumps: t.Optional[t.Callable[..., str]] = None, **kwargs: t.Any618+) -> Markup:619 """Serialize an object to a string of JSON with :func:`json.dumps`,620 then replace HTML-unsafe characters with Unicode escapes and mark621 the result safe with :class:`~markupsafe.Markup`.622 131 unmodified lines