Skip to content
Myr

Merge pull request #1465 from wombatonfire/groupby-case-sensitive

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

Add case_sensitive parameter to groupby() filter

authored by David Lord · committed by GitHub · parents 20eb7f5, e690f7c · Browse files · 4 files+86 added−6 removed
This commit

State

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

Diff stats

4 files+86 added−6 removed

  • tests:+39 added−0 removed
  • other:+47 added−6 removed

4 files+86 added−6 removed

modified:src/jinja2/filters.py+44 added-6 removed
1161 unmodified lines
1162 environment: "Environment",1163 value: "t.Iterable[V]",1164 attribute: t.Union[str, int],1165 default: t.Optional[t.Any] = None,1166) -> "t.List[t.Tuple[t.Any, t.List[V]]]":1166 case_sensitive: bool = False,1167) -> "t.List[_GroupTuple]":1168 """Group a sequence of objects by an attribute using Python's1169 :func:`itertools.groupby`. The attribute can use dot notation for1170 nested access, like ``"address.city"``. Unlike Python's ``groupby``,1171 the values are sorted first so only one group is returned for each
31 unmodified lines
1203 <ul>{% for city, items in users|groupby("city", default="NY") %}1204 <li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li>1205 {% endfor %}</ul>12061207 Like the :func:`~jinja-filters.sort` filter, sorting and grouping is1208 case-insensitive by default. The ``key`` for each group will have1209 the case of the first item in that group of values. For example, if1210 a list of users has cities ``["CA", "NY", "ca"]``, the "CA" group1211 will have two values. This can be disabled by passing1212 ``case_sensitive=True``.12131214 .. versionchanged:: 3.11215 Added the ``case_sensitive`` parameter. Sorting and grouping is1216 case-insensitive by default, matching other filters that do1217 comparisons.12181219 .. versionchanged:: 3.01220 Added the ``default`` parameter.12211222 .. versionchanged:: 2.61223 The attribute supports dot notation for nested access.1224 """1212 expr = make_attrgetter(environment, attribute, default=default)1213 return [1225 expr = make_attrgetter(1226 environment,1227 attribute,1228 postprocess=ignore_case if not case_sensitive else None,1229 default=default,1230 )1231 out = [1232 _GroupTuple(key, list(values))1233 for key, values in groupby(sorted(value, key=expr), expr)1234 ]12351236 if not case_sensitive:1237 # Return the real key from the first value instead of the lowercase key.1238 output_expr = make_attrgetter(environment, attribute, default=default)1239 out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]12401241 return out124212431244@async_variant(sync_do_groupby) # type: ignore1245async def do_groupby(1246 environment: "Environment",1247 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1248 attribute: t.Union[str, int],1249 default: t.Optional[t.Any] = None,1225) -> "t.List[t.Tuple[t.Any, t.List[V]]]":1226 expr = make_attrgetter(environment, attribute, default=default)1227 return [1250 case_sensitive: bool = False,1251) -> "t.List[_GroupTuple]":1252 expr = make_attrgetter(1253 environment,1254 attribute,1255 postprocess=ignore_case if not case_sensitive else None,1256 default=default,1257 )1258 out = [1259 _GroupTuple(key, await auto_to_list(values))1260 for key, values in groupby(sorted(await auto_to_list(value), key=expr), expr)1261 ]12621263 if not case_sensitive:1264 # Return the real key from the first value instead of the lowercase key.1265 output_expr = make_attrgetter(environment, attribute, default=default)1266 out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]12671268 return out126912701271@pass_environment1272def sync_do_sum(1273 environment: "Environment",1274 iterable: "t.Iterable[V]",
566 unmodified lines
modified:tests/test_async_filters.py+20 added
55 unmodified lines
56 "",57 ]585960@pytest.mark.parametrize(61 ("case_sensitive", "expect"),62 [63 (False, "a: 1, 3\nb: 2\n"),64 (True, "A: 3\na: 1\nb: 2\n"),65 ],66)67def test_groupby_case(env_async, case_sensitive, expect):68 tmpl = env_async.from_string(69 "{% for k, vs in data|groupby('k', case_sensitive=cs) %}"70 "{{ k }}: {{ vs|join(', ', attribute='v') }}\n"71 "{% endfor %}"72 )73 out = tmpl.render(74 data=[{"k": "a", "v": 1}, {"k": "b", "v": 2}, {"k": "A", "v": 3}],75 cs=case_sensitive,76 )77 assert out == expect787980@mark_dualiter("items", lambda: [("a", 1), ("a", 2), ("b", 1)])81def test_groupby_tuple_index(env_async, items):82 tmpl = env_async.from_string(83 """
190 unmodified lines
modified:tests/test_filters.py+19 added
617 unmodified lines
618 ]619 )620 assert out == "NY: emma, john\nWA: smith\n"621622 @pytest.mark.parametrize(623 ("case_sensitive", "expect"),624 [625 (False, "a: 1, 3\nb: 2\n"),626 (True, "A: 3\na: 1\nb: 2\n"),627 ],628 )629 def test_groupby_case(self, env, case_sensitive, expect):630 tmpl = env.from_string(631 "{% for k, vs in data|groupby('k', case_sensitive=cs) %}"632 "{{ k }}: {{ vs|join(', ', attribute='v') }}\n"633 "{% endfor %}"634 )635 out = tmpl.render(636 data=[{"k": "a", "v": 1}, {"k": "b", "v": 2}, {"k": "A", "v": 3}],637 cs=case_sensitive,638 )639 assert out == expect640641 def test_filtertag(self, env):642 tmpl = env.from_string(643 "{% filter upper|replace('FOO', 'foo') %}foobar{% endfilter %}"644 )
229 unmodified lines
modified:CHANGES.rst+3 added
31 unmodified lines
32 :pr:`1612`33- Add ``items`` filter. :issue:`1561`34- Subscriptions (``[0]``, etc.) can be used after filters, tests, and35 calls when the environment is in async mode. :issue:`1573`36- The ``groupby`` filter is case-insensitive by default, matching37 other comparison filters. Added the ``case_sensitive`` parameter to38 control this. :issue:`1463`394041Version 3.0.342-------------
911 unmodified lines