Skip to content
Myr

Merge pull request #1384 from pallets/typing-filters-tests

Before adoption: this commit came in with the history the project adopted, so no landing records it.

add type annotations to filters and tests

authored by David Lord · committed by GitHub · parents 43d4228, f0a9f31 · 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

6 files+509 added−206 removed

modified:src/jinja2/asyncfilters.py+121 added-30 removed
1import typing2import typing as t3from functools import wraps4from itertools import groupby56from . import filters7from .asyncsupport import auto_aiter8from .asyncsupport import auto_await910if t.TYPE_CHECKING:11 from .environment import Environment12 from .nodes import EvalContext13 from .runtime import Context14 from .runtime import Undefined1516 V = t.TypeVar("V")17188async def auto_to_seq(value):19async def auto_to_seq(20 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",21) -> "t.List[V]":22 seq = []2324 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)3031 return seq323319async 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):34async 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 )4647 async for item in auto_aiter(value):48 if func(item):49 yield item505152def dualfilter(normal_filter, async_filter):53 wrap_evalctx = False5455 if getattr(normal_filter, "environmentfilter", False) is True:5657 def is_async(args):58 return args[0].is_async
9 unmodified lines
6869 @wraps(normal_filter)70 def wrapper(*args, **kwargs):71 b = is_async(args)7273 if wrap_evalctx:74 args = args[1:]7576 if b:77 return async_filter(*args, **kwargs)7879 return normal_filter(*args, **kwargs)8081 if wrap_evalctx:82 wrapper.evalcontextfilter = True8384 wrapper.asyncfiltervariant = True5685 return wrapper868788def asyncfiltervariant(original):
3 unmodified lines
92 return decorator939495@asyncfiltervariant(filters.do_first)68async def do_first(environment, seq):96async 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.")103104105@asyncfiltervariant(filters.do_groupby)76async def do_groupby(environment, value, attribute):106async 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 ]116117118@asyncfiltervariant(filters.do_join)87async def do_join(eval_ctx, value, d="", attribute=None):119async 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)126127128@asyncfiltervariant(filters.do_list)92async def do_list(value):129async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":130 return await auto_to_seq(value)131132133@asyncfiltervariant(filters.do_reject)97async def do_reject(*args, **kwargs):98 return async_select_or_reject(args, kwargs, lambda x: not x, False)134async 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)141142143@asyncfiltervariant(filters.do_rejectattr)102async def do_rejectattr(*args, **kwargs):103 return async_select_or_reject(args, kwargs, lambda x: not x, True)144async 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)151152153@asyncfiltervariant(filters.do_select)107async def do_select(*args, **kwargs):108 return async_select_or_reject(args, kwargs, lambda x: x, False)154async 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)161162163@asyncfiltervariant(filters.do_selectattr)112async def do_selectattr(*args, **kwargs):113 return async_select_or_reject(args, kwargs, lambda x: x, True)164async 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)171172173@typing.overload174def 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 ...182183184@typing.overload185def 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 ...193194195@asyncfiltervariant(filters.do_map)117async def do_map(*args, **kwargs):118 seq, func = filters.prepare_map(args, kwargs)119 if seq:120 async for item in auto_aiter(seq):196async def do_map(context, value, *args, **kwargs):197 if value:198 func = filters.prepare_map(context, args, kwargs)199200 async for item in auto_aiter(value):201 yield await auto_await(func(item))202203204@asyncfiltervariant(filters.do_sum)125async def do_sum(environment, iterable, attribute=None, start=0):205async 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 = start212213 if attribute is not None:214 func = filters.make_attrgetter(environment, attribute)215 else:216
1 unmodified line
218 return x219220 async for item in auto_aiter(iterable):221 rv += func(item)222223 return rv224225226@asyncfiltervariant(filters.do_slice)140async def do_slice(value, slices, fill_with=None):227async 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)233234235ASYNC_FILTERS = {
13 unmodified lines
modified:src/jinja2/environment.py+1 added-1 removed
317 unmodified lines
318 self.newline_sequence = newline_sequence319 self.keep_trailing_newline = keep_trailing_newline320321 # runtime information322 self.undefined = undefined322 self.undefined: t.Type[Undefined] = undefined323 self.optimized = optimized324 self.finalize = finalize325 self.autoescape = autoescape326
1086 unmodified lines
modified:src/jinja2/filters.py+343 added-140 removed
1"""Built-in template filters used with the ``|`` operator."""2import math3import random4import re5import typing6import typing as t7from collections import abc6from collections import namedtuple8from itertools import chain9from itertools import groupby1011from markupsafe import escape
6 unmodified lines
18from .utils import pformat19from .utils import url_quote20from .utils import urlize2121_word_re = re.compile(r"\w+")22_word_beginning_split_re = re.compile(r"([-\s({\[<]+)")22if 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: F4012829 K = t.TypeVar("K")30 V = t.TypeVar("V")31 F = t.TypeVar("F", bound=t.Callable[..., t.Any])3233 class HasHTML(te.Protocol):34 def __html__(self) -> str:35 pass363725def contextfilter(f):38def 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 f444533def evalcontextfilter(f):46def 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`.5051 .. versionadded:: 2.452 """40 f.evalcontextfilter = True53 f.evalcontextfilter = True # type: ignore54 return f555644def environmentfilter(f):57def 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 f636452def ignore_case(value):65def 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())7071 return value7258def make_attrgetter(environment, attribute, postprocess=None, default=None):7374def 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)8666 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)9091 if default is not None and isinstance(item, Undefined):92 item = default
5 unmodified lines
9899 return attrgetter10010181def make_multi_attrgetter(environment, attribute, postprocess=None):102def 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 lines
113 attribute values.114115 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]12199 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]123124 def attrgetter(item: t.Any) -> t.List[t.Any]:125 items = [None] * len(parts)126127 for i, attribute_part in enumerate(parts):128 item_i = item129130 for part in attribute_part:131 item_i = environment.getitem(item_i, part)132133 if postprocess is not None:134 item_i = postprocess(item_i)135136 items[i] = item_i137138 return items139140 return attrgetter141142115def _prepare_attribute_parts(attr):143def _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 []148118 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]151152 return [attr]153124def do_forceescape(value):154155def 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__()159160 return escape(str(value))161162131def do_urlencode(value):163def 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.167168 Basic wrapper around :func:`urllib.parse.quote` when given a169 string, or :func:`urllib.parse.urlencode` for a dict or iterable.
11 unmodified lines
181 if isinstance(value, str) or not isinstance(value, abc.Iterable):182 return url_quote(value)183184 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: ignore188189 return "&".join(190 f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items191 )192193194@evalcontextfilter161def do_replace(eval_ctx, s, old, new, count=None):195def 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 first
8 unmodified lines
210 -> d'oh, d'oh, aaargh211 """212 if count is None:213 count = -1214215 if not eval_ctx.autoescape:216 return str(s).replace(str(old), str(new), count)217218 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)226227 return s.replace(soft_str(old), soft_str(new), count)228229191def do_upper(s):230def do_upper(s: str) -> str:231 """Convert a value to uppercase."""232 return soft_str(s).upper()233234196def do_lower(s):235def do_lower(s: str) -> str:236 """Convert a value to lowercase."""237 return soft_str(s).lower()238239240@evalcontextfilter202def do_xmlattr(_eval_ctx, d, autospace=True):241def 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 lines
267 f'{escape(key)}="{escape(value)}"'268 for key, value in d.items()269 if value is not None and not isinstance(value, Undefined)270 )271272 if autospace and rv:273 rv = " " + rv274232 if _eval_ctx.autoescape:275 if eval_ctx.autoescape:276 rv = Markup(rv)277278 return rv279280237def do_capitalize(s):281def 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()286287288_word_beginning_split_re = re.compile(r"([-\s({\[<]+)")289290244def do_title(s):291def 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 lines
300 ]301 )302303257def do_dictsort(value, case_sensitive=False, by="key", reverse=False):304def 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 lines
343 return sorted(value.items(), key=sort_func, reverse=reverse)344345346@environmentfilter295def do_sort(environment, value, reverse=False, case_sensitive=False, attribute=None):347def 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`.355356 .. sourcecode:: jinja357
41 unmodified lines
399 return sorted(value, key=key_func, reverse=reverse)400401402@environmentfilter345def do_unique(environment, value, case_sensitive=False, attribute=None):403def 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.410411 .. sourcecode:: jinja412
18 unmodified lines
431 seen.add(key)432 yield item433434372def _min_or_max(environment, value, func, case_sensitive, attribute):435def _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)443444 try:445 first = next(it)
6 unmodified lines
452 return func(chain([first], it), key=key_func)453454455@environmentfilter387def do_min(environment, value, case_sensitive=False, attribute=None):456def 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.463464 .. sourcecode:: jinja465
6 unmodified lines
472 return _min_or_max(environment, value, min, case_sensitive, attribute)473474475@environmentfilter402def do_max(environment, value, case_sensitive=False, attribute=None):476def 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.483484 .. sourcecode:: jinja485
5 unmodified lines
491 """492 return _min_or_max(environment, value, max, case_sensitive, attribute)493494416def do_default(value, default_value="", boolean=False):495def 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:502503 .. sourcecode:: jinja
16 unmodified lines
520 in the chain without getting an :exc:`~jinja2.UndefinedError`.521 """522 if isinstance(value, Undefined) or (boolean and not value):523 return default_value524525 return value526527528@evalcontextfilter445def do_join(eval_ctx, value, d="", attribute=None):529def 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 lines
564 # 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 = False568569 for idx, item in enumerate(value):570 if hasattr(item, "__html__"):571 do_escape = True572 else:573 value[idx] = str(item)574575 if do_escape:576 d = escape(d)577 else:578 d = str(d)579580 return d.join(value)581582 # no html involved, to normal joining583 return soft_str(d).join(map(soft_str, value))584585494def do_center(value, width=80):586def 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)589590591@environmentfilter500def do_first(environment, seq):592def 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.")600601602@environmentfilter509def do_last(environment, seq):510 """511 Return the last item of a sequence.603def do_last(604 environment: "Environment", seq: "t.Reversible[V]"605) -> "t.Union[V, Undefined]":606 """Return the last item of a sequence.607608 Note: Does not work with generators. You may want to explicitly609 convert it to a list:610
7 unmodified lines
618 return environment.undefined("No last item, sequence was empty.")619620621@contextfilter527def do_random(context, seq):622def 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.")628629535def do_filesizeformat(value, binary=False):630def 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 lines
644 ("EiB" if binary else "EB"),645 ("ZiB" if binary else "ZB"),646 ("YiB" if binary else "YB"),647 ]648649 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)656657 if bytes < unit:658 return f"{base * bytes / unit:.1f} {prefix}"659660 return f"{base * bytes / unit:.1f} {prefix}"661662565def do_pprint(value):663def 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))666667668_uri_scheme_re = re.compile(r"^([\w.+-]{2,}:(/){0,2})$")669670671@evalcontextfilter672def 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.682683 This may not recognize links in some situations. Usually, a more684 comprehensive formatter, such as a Markdown library, is a better
62 unmodified lines
747748 return rv749750653def do_indent(s, width=4, first=False, blank=False):751def 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.754755 :param width: Number of spaces to indent by.
31 unmodified lines
787 return rv788789790@environmentfilter693def do_truncate(env, s, length=255, killwords=False, end="...", leeway=None):791def 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 fact
17 unmodified lines
820 can be reconfigured globally.821 """822 if leeway is None:823 leeway = env.policies["truncate.leeway"]824825 assert length >= len(end), f"expected length >= {len(end)}, got {length}"826 assert leeway >= 0, f"expected leeway >= 0, got {leeway}"827828 if len(s) <= length + leeway:829 return s830831 if killwords:832 return s[: length - len(end)] + end833834 result = s[: length - len(end)].rsplit(" ", 1)[0]835 return result + end836837838@environmentfilter839def 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.849850 :param s: Original text to wrap.
13 unmodified lines
864865 .. versionchanged:: 2.7866 Added the ``wrapstring`` parameter.867 """759868 import textwrap869762 if not wrapstring:870 if wrapstring is None:871 wrapstring = environment.newline_sequence872873 # textwrap.wrap doesn't consider existing newlines when wrapping.874 # If the string has a newline before width, wrap will still insert
15 unmodified lines
890 ]891 )892893894_word_re = re.compile(r"\w+")895896786def do_wordcount(s):897def do_wordcount(s: str) -> int:898 """Count the words in that string."""899 return len(_word_re.findall(soft_str(s)))900901791def do_int(value, default=0, base=10):902def 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 second
3 unmodified lines
910 """911 try:912 if isinstance(value, str):913 return int(value, base)914915 return int(value)916 except (TypeError, ValueError):917 # this quirk is necessary so that "42.23"|int gives 42.918 try:
1 unmodified line
920 except (TypeError, ValueError):921 return default922923812def do_float(value, default=0.0):924def 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 lines
931 except (TypeError, ValueError):932 return default933934823def do_format(value, *args, **kwargs):935def 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``.938939 .. sourcecode:: jinja
15 unmodified lines
955 if args and kwargs:956 raise FilterArgumentError(957 "can't handle positional and keyword arguments at the same time"958 )959960 return soft_str(value) % (kwargs or args)961962850def do_trim(value, chars=None):963def 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)966967855def do_striptags(value):968def 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__()972973 return Markup(str(value)).striptags()974975862def do_slice(value, slices, fill_with=None):976def 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 lines
999 length = len(seq)1000 items_per_slice = length // slices1001 slices_with_extra = length % slices1002 offset = 010031004 for slice_number in range(slices):1005 start = offset + slice_number * items_per_slice10061007 if slice_number < slices_with_extra:1008 offset += 110091010 end = offset + (slice_number + 1) * items_per_slice1011 tmp = seq[start:end]10121013 if fill_with is not None and slice_number >= slices_with_extra:1014 tmp.append(fill_with)10151016 yield tmp10171018898def do_batch(value, linecount, fill_with=None):1019def 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 this
10 unmodified lines
1036 </tr>1037 {%- endfor %}1038 </table>1039 """917 tmp = []1040 tmp: "t.List[V]" = []10411042 for item in value:1043 if len(tmp) == linecount:1044 yield tmp1045 tmp = []10461047 tmp.append(item)10481049 if tmp:1050 if fill_with is not None and len(tmp) < linecount:1051 tmp += [fill_with] * (linecount - len(tmp))10521053 yield tmp10541055929def do_round(value, precision=0, method="common"):1056def 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 lines
1084 -> 431085 """1086 if method not in {"common", "ceil", "floor"}:1087 raise FilterArgumentError("method must be common, ceil or floor")10881089 if method == "common":1090 return round(value, precision)10911092 func = getattr(math, method)960 return func(value * (10 ** precision)) / (10 ** precision)1093 return t.cast(float, func(value * (10 ** precision)) / (10 ** precision))10941095963# 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: ignore1096class _GroupTuple(t.NamedTuple):1097 grouper: t.Any1098 list: t.List10991100 # 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)11041105 def __str__(self):1106 return tuple.__str__(self)110711081109@environmentfilter974def do_groupby(environment, value, attribute):1110def 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 each
33 unmodified lines
1150 ]115111521153@environmentfilter1016def do_sum(environment, iterable, attribute=None, start=0):1154def 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 lines
1172 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)11761177 return sum(iterable, start)117811791036def do_list(value):1180def 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)118511861043def do_mark_safe(value):1187def 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)119211931050def do_mark_unsafe(value):1194def do_mark_unsafe(value: str) -> str:1195 """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""1196 return str(value)119711981199@typing.overload1200def do_reverse(value: str) -> str:1201 ...120212031204@typing.overload1205def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]":1206 ...120712081209def 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]12151216 try:1217 return reversed(value)1218 except TypeError:1219 try:
4 unmodified lines
1224 raise FilterArgumentError("argument must be iterable")122512261227@environmentfilter1073def do_attr(environment, obj, name):1228def 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 lines
1243 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)12491250 if not environment.is_safe_attribute(obj, name, value):1251 return environment.unsafe_undefined(obj, name)12521253 return value12541255 return environment.undefined(obj=obj, name=name)125612571258@typing.overload1259def do_map(1260 context: "Context", value: t.Iterable, name: str, *args: t.Any, **kwargs: t.Any1261) -> t.Iterable:1262 ...126312641265@typing.overload1266def do_map(1267 context: "Context",1268 value: t.Iterable,1269 *,1270 attribute: str = ...,1271 default: t.Optional[t.Any] = None,1272) -> t.Iterable:1273 ...127412751276@contextfilter1099def do_map(*args, **kwargs):1277def 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 lines
1313 Added the ``default`` parameter.13141315 .. 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)13191320 for item in value:1321 yield func(item)132213231324@contextfilter1146def do_select(*args, **kwargs):1325def 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.13301331 If no test is specified, each object will be evaluated as a boolean.
16 unmodified lines
1348 (n for n in numbers if test_divisibleby(n, 3))13491350 .. 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)135313541355@contextfilter1175def do_reject(*args, **kwargs):1356def 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.13611362 If no test is specified, each object will be evaluated as a boolean.
11 unmodified lines
1374 (n for n in numbers if not test_odd(n))13751376 .. 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)137913801381@contextfilter1199def do_selectattr(*args, **kwargs):1382def 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 lines
1404 (u for user in users if test_none(user.email))14051406 .. 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)140914101411@contextfilter1227def do_rejectattr(*args, **kwargs):1412def 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 lines
1432 (u for user in users if not test_none(user.email))14331434 .. 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)143714381439@evalcontextfilter1253def do_tojson(eval_ctx, value, indent=None):1440def 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.14451446 The returned string is safe to render in HTML documents and
17 unmodified lines
14641465 return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)146614671279def prepare_map(args, kwargs):1280 context = args[0]1281 seq = args[1]12821283 if len(args) == 2 and "attribute" in kwargs:1468def 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)14741475 if kwargs:1476 raise FilterArgumentError(1477 f"Unexpected keyword argument {next(iter(kwargs))!r}"1478 )14791480 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")14871488 def func(item):1489 return context.environment.call_filter(1490 name, item, args, kwargs, context=context1491 )14921303 return seq, func1493 return func149414951306def prepare_select_or_reject(args, kwargs, modfunc, lookup_attr):1307 context = args[0]1308 seq = args[1]1496def 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")15081509 transfunc = make_attrgetter(context.environment, attr)1510 off = 11511 else:1512 off = 0
1 unmodified line
1514 def transfunc(x):1515 return x15161517 try:1323 name = args[2 + off]1324 args = args[3 + off :]1518 name = args[off]1519 args = args[1 + off :]15201521 def func(item):1522 return context.environment.call_test(name, item, args, kwargs)15231524 except LookupError:1525 func = bool15261332 return seq, lambda item: modfunc(func(transfunc(item)))1527 return lambda item: modfunc(func(transfunc(item)))152815291335def 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:1530def 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)15401541 for item in value:1542 if func(item):1543 yield item15441545
55 unmodified lines
modified:src/jinja2/runtime.py+4 added-1 removed
18 unmodified lines
19from .utils import missing20from .utils import Namespace # noqa: F40121from .utils import object_type_repr2223if t.TYPE_CHECKING:24 from .environment import Environment2526# these variables are exported to the template runtime27exported = [28 "LoopContext",29 "TemplateReference",
158 unmodified lines
188189 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 lines
modified:src/jinja2/tests.py+29 added-28 removed
1"""Built-in template tests used with the ``is`` operator."""2import operator3import re3import typing as t4from collections import abc5from numbers import Number67from .runtime import Undefined8from .utils import environmentfunction910number_re = re.compile(r"^-?\d+(\.\d+)?$")11regex_type = type(number_re)12test_callable = callable10if t.TYPE_CHECKING:11 from .environment import Environment121315def test_odd(value):14def test_odd(value: int) -> bool:15 """Return true if the variable is odd."""16 return value % 2 == 1171820def test_even(value):19def test_even(value: int) -> bool:20 """Return true if the variable is even."""21 return value % 2 == 0222325def test_divisibleby(value, num):24def test_divisibleby(value: int, num: int) -> bool:25 """Check if a variable is divisible by a number."""26 return value % num == 0272830def test_defined(value):29def test_defined(value: t.Any) -> bool:30 """Return true if the variable is defined:3132 .. sourcecode:: jinja33
8 unmodified lines
42 """43 return not isinstance(value, Undefined)444547def test_undefined(value):46def test_undefined(value: t.Any) -> bool:47 """Like :func:`defined` but the other way round."""48 return isinstance(value, Undefined)495051@environmentfunction53def test_filter(env, value):52def test_filter(env: "Environment", value: str) -> bool:53 """Check if a filter exists by name. Useful if a filter may be54 optionally available.5556 .. code-block:: jinja
9 unmodified lines
66 return value in env.filters676869@environmentfunction71def test_test(env, value):70def test_test(env: "Environment", value: str) -> bool:71 """Check if a test exists by name. Useful if a test may be72 optionally available.7374 .. code-block:: jinja
12 unmodified lines
87 """88 return value in env.tests899092def test_none(value):91def test_none(value: t.Any) -> bool:92 """Return true if the variable is none."""93 return value is None949597def test_boolean(value):96def test_boolean(value: t.Any) -> bool:97 """Return true if the object is a boolean value.9899 .. versionadded:: 2.11100 """101 return value is True or value is False102103105def test_false(value):104def test_false(value: t.Any) -> bool:105 """Return true if the object is False.106107 .. versionadded:: 2.11108 """109 return value is False110111113def test_true(value):112def test_true(value: t.Any) -> bool:113 """Return true if the object is True.114115 .. versionadded:: 2.11116 """117 return value is True118119120# NOTE: The existing 'number' test matches booleans and floats122def test_integer(value):121def test_integer(value: t.Any) -> bool:122 """Return true if the object is an integer.123124 .. versionadded:: 2.11125 """126 return isinstance(value, int) and value is not True and value is not False127128129# NOTE: The existing 'number' test matches booleans and integers131def test_float(value):130def test_float(value: t.Any) -> bool:131 """Return true if the object is a float.132133 .. versionadded:: 2.11134 """135 return isinstance(value, float)136137139def test_lower(value):138def test_lower(value: str) -> bool:139 """Return true if the variable is lowercased."""140 return str(value).islower()141142144def test_upper(value):143def test_upper(value: str) -> bool:144 """Return true if the variable is uppercased."""145 return str(value).isupper()146147149def test_string(value):148def test_string(value: t.Any) -> bool:149 """Return true if the object is a string."""150 return isinstance(value, str)151152154def test_mapping(value):153def test_mapping(value: t.Any) -> bool:154 """Return true if the object is a mapping (dict etc.).155156 .. versionadded:: 2.6157 """158 return isinstance(value, abc.Mapping)159160162def test_number(value):161def test_number(value: t.Any) -> bool:162 """Return true if the variable is a number."""163 return isinstance(value, Number)164165167def test_sequence(value):166def 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 False175176 return True177178179def test_sameas(value, other):179def test_sameas(value: t.Any, other: t.Any) -> bool:180 """Check if an object points to the same memory address than another181 object:182183 .. sourcecode:: jinja
4 unmodified lines
188 """189 return value is other190191192def test_iterable(value):192def 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 False198199 return True200201201def test_escaped(value):202def test_escaped(value: t.Any) -> bool:203 """Check if the value is escaped."""204 return hasattr(value, "__html__")205206206def test_in(value, seq):207def test_in(value: t.Any, seq: t.Container) -> bool:208 """Check if value is in seq.209210 .. versionadded:: 2.10211 """
20 unmodified lines
232 "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 lines
modified:src/jinja2/utils.py+11 added-6 removed
193 unmodified lines
194)195_email_re = re.compile(r"^\S+@\w[\w.-]*\.\w+$")196197198def urlize(text, trim_url_limit=None, rel=None, target=None, extra_schemes=None):198def 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.206207 This may not recognize links in some situations. Usually, a more208 comprehensive formatter, such as a Markdown library, is a better
155 unmodified lines
364 return "\n\n".join(result)365 return Markup("\n".join(f"<p>{escape(x)}</p>" for x in result))366367362def url_quote(obj, charset="utf-8", for_qs=False):368def 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.370365 This function is misnamed, it is a wrapper around366 :func:`urllib.parse.quote`.367371 :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 lines
612613 return autoescape614615613def htmlsafe_json_dumps(obj, dumps=None, **kwargs):616def 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