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 pallets#1781
  • Loading branch information
sileht committed Dec 23, 2022
1 parent ae53ea5 commit a076db8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
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 a076db8

Please sign in to comment.