Skip to content

Commit

Permalink
fix(filter): unique with async generator
Browse files Browse the repository at this point in the history
unique() filter doesn't work chained after a filter that return an async generator.

This introduces a async variant of the filter transform the async
generator into a list to be able to apply the unique filter.

Fixes #1781
  • Loading branch information
sileht committed Dec 23, 2022
1 parent ae53ea5 commit 934f628
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGES.rst
Expand Up @@ -5,6 +5,9 @@ Version 3.2.0

Unreleased

- Fix ``unique()`` when chained with `reject()` or `rejectattr()`
:issue:`1781`


Version 3.1.2
-------------
Expand Down
14 changes: 13 additions & 1 deletion src/jinja2/filters.py
Expand Up @@ -410,7 +410,7 @@ def do_sort(


@pass_environment
def do_unique(
def sync_do_unique(
environment: "Environment",
value: "t.Iterable[V]",
case_sensitive: bool = False,
Expand Down Expand Up @@ -442,6 +442,18 @@ def do_unique(
yield item


@async_variant(sync_do_unique) # type: ignore
async def do_unique(
environment: "Environment",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
case_sensitive: bool = False,
attribute: t.Optional[t.Union[str, int]] = None,
) -> "t.Iterator[V]":
return sync_do_unique(
environment, await auto_to_list(value), case_sensitive, attribute
)


def _min_or_max(
environment: "Environment",
value: "t.Iterable[V]",
Expand Down
7 changes: 7 additions & 0 deletions tests/test_async_filters.py
Expand Up @@ -245,6 +245,13 @@ def test_slice(env_async, items):
)


def test_unique_with_async_gen(env_async):
items = ["a", "b", "c", "c", "a", "d", "z"]
tmpl = env_async.from_string("{{ items|reject('==', 'z')|unique|list }}")
out = tmpl.render(items=items)
assert out == "['a', 'b', 'c', 'd']"


def test_custom_async_filter(env_async):
async def customfilter(val):
return str(val)
Expand Down

0 comments on commit 934f628

Please sign in to comment.