Skip to content

Commit

Permalink
make unique filter async-aware
Browse files Browse the repository at this point in the history
  • Loading branch information
sileht authored and davidism committed Dec 19, 2024
1 parent a4abbfd commit 76af711
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ Unreleased
:pr:`1960`
- The runtime uses the correct ``concat`` function for the current environment
when calling block references. :issue:`1701`
- Make ``|unique`` async-aware, allowing it to be used after another
async-aware filter. :issue:`1781`


Version 3.1.4
Expand Down
14 changes: 13 additions & 1 deletion src/jinja2/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,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 @@ -470,6 +470,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
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,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, run_async_fn):
async def customfilter(val):
return str(val)
Expand Down

0 comments on commit 76af711

Please sign in to comment.