Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(filter): unique with async generator #1782

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.rst
Expand Up @@ -8,6 +8,8 @@ Unreleased
- Use modern packaging metadata with ``pyproject.toml`` instead of ``setup.cfg``.
:pr:`1793`

- 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(
sileht marked this conversation as resolved.
Show resolved Hide resolved
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